ValueError:输入数组应具有与目标数组相同的样本数。找到32个输入样本和128个目标样本

时间:2018-05-04 22:27:15

标签: python numpy keras

我在这里按照本教程进行图像分类。 链接:[Keras图像分类] [1]

我将代码扩展为8个类,但是我收到了以下错误:

ValueError: Input arrays should have the same number of samples as target arrays. Found 32 input samples and 128 target samples

我的火车顶级型号代码如下:

def train_top_model():
   train_data = np.load(open('bottleneck_features_train', 'rb'))
   train_labels = np.array([0] * (nb_train_samples // 8) + [1] * (nb_train_samples // 8) + [2] * (nb_train_samples // 8) + [3] * (nb_train_samples // 8) + [4] * (nb_train_samples // 8) + [5] * (nb_train_samples // 8) + [6] * (nb_train_samples // 8) + [7] * (nb_train_samples // 8))
   validation_data = np.load(open('bottleneck_features_validation', 'rb'))
   validation_labels = np.array([0] * (nb_train_samples // 8) + [1] * (nb_train_samples // 8) + [2] * (nb_train_samples // 8) + [3] * (nb_train_samples // 8) + [4] * (nb_train_samples // 8) + [5] * (nb_train_samples // 8) + [6] * (nb_train_samples // 8) + [7] * (nb_train_samples // 8))
   train_labels = keras.utils.to_categorical(train_labels, num_classes = 8)
   validation_labels = keras.utils.to_categorical(validation_labels, num_classes = 8)
   model = Sequential()
   model.add(Flatten(input_shape=train_data.shape[1:]))
   model.add(Dense(512, activation='relu'))
   model.add(Dropout(0.5))
   model.add(Dense(8, activation='softmax'))
   sgd = SGD(lr=1e-2, decay=0.00371, momentum=0.9, nesterov=False)
   model.compile(optimizer=sgd,
         loss='categorical_crossentropy', metrics=['accuracy'])
   model.fit(train_data, train_labels,
          epochs=epochs,
          batch_size=batch_size,
   validation_data=(validation_data, validation_labels))
   model.save_weights(top_model_weights_path)

我认为错误试图说的是输入应该有128个样本,但它只有32个。我不确定原因,因为我也得到了这个Found 128 images belonging to 8 classes.我认为它表明它成功获得了所有128张图像。

有人可以帮忙吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

Keras抱怨您在验证集中有32张图片,而您的验证标签包含128个元素,因为您原本忘记将nb_train_samples更改为nb_validation_samples,因此要修复它,请初始化验证标签nb_validation_samples