我试图将Keras MNIST Siamese示例调整为使用生成器。
在示例中,我们有:
model.fit([tr_pairs[:, 0], tr_pairs[:, 1]], tr_y, batch_size=128, epochs=epochs, validation_data=([te_pairs[:, 0], te_pairs[:, 1]], te_y))
为了弄清楚生成器需要返回的形状,我做了以下操作:
np.array([tr_pairs[:, 0], tr_pairs[:, 1]]).shape
得到的结果是:
(2, 108400, 28, 28)
我的生成器返回的内容如下:
(data, labels) = my_generatordata.shape(2, 6, 300, 300, 3)labels.shape(6,)
因此,它是两个数组(用于神经网络输入),包含6张图像(batch_size),每张图像大小为300x300x3
(RGB)。
以下是fit_generator()
的使用方式:
...input_shape = (300, 300, 3)...model.fit_generator(kbg.generate(set='train'), steps_per_epoch=training_steps, epochs=1, verbose=1, callbacks=[], validation_data=kbg.generate(set='test'), validation_steps=validation_steps, use_multiprocessing=False, workers=0)
我猜测我正在向神经网络提供相同形状的数据,但却得到了以下错误:
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead gotthe following list of 1 arrays: [array([[[[[0.49803922, 0.48235294, 0.55686275], [0.63137255, 0.61176471, 0.64313725], [0.8627451 , 0.84313725, 0.84313725], ..., [0.58823529, 0.64705882, 0.631...
哪里出了问题?
回答:
由于模型有两个输入层,生成器应该产生一个包含两个数组的列表作为输入样本,对应于两个输入层,像这样:
def my_generator(args): # ... yield [first_pair, second_pair], labels
其中first_pair
和second_pair
的形状都为(n_samples, 300, 300, 3)
。