I have the following python code:

from keras.applications import InceptionResNetV2
#conv_base.summary ()
# Extract features
import os, shutil
from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 16

def extract_features(directory, sample_count):
    features = np.zeros(shape=(sample_count, 3, 3, 1536))  # Must be equal to the output of the convolutional base
    labels = np.zeros(shape=(sample_count))
    # Preprocess data
    generator = datagen.flow_from_directory(directory,
                                            batch_size = batch_size,
    # Pass data through convolutional base
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size: (i + 1) * batch_size] = features_batch
        labels[i * batch_size: (i + 1) * batch_size] = labels_batch
        i += 1
        if i * batch_size >= sample_count:
    return features, labels

train_features, train_labels = extract_features(train_dir, 384)  # Agree with our small dataset size
validation_features, validation_labels = extract_features(validation_dir, 80)
test_features, test_labels = extract_features(test_dir, 86)

I get the following error:

  File "<ipython-input-31-6bdd0a78c5f7>", line 26, in <module>
    train_features, train_labels = extract_features(train_dir, 384)

  File "<ipython-input-31-6bdd0a78c5f7>", line 20, in extract_features
    labels[i * batch_size: (i + 1) * batch_size] = labels_batch

ValueError: could not broadcast input array from the shape (16,4) into shape (16)


1 Answer 1


Your data generator retrieves your labels as categorical and based on the error, I assume you have 4 classes. However, in your extract_features function, you are first initializing a labels array of shape=(sample_count) instead of shape=(sample_count, 4). In your for loop, you are getting a labels_batch from the generator which apparently has a shape of (16, 4) and you are trying to save it as part of your initialized labels array which has a shape of (sample_count) instead of (sample_count, 4) and that's why it complains.

In short, you should change:

labels = np.zeros(shape=(sample_count))


labels = np.zeros(shape=(sample_count, 4))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.