keras多输入模型:预计会看到2个数组,但获得了以下1个数组的列表

时间:2019-05-19 16:43:59

标签: keras keras-layer

我正在针对mnist数据集训练功能性keras模型。有一层需要2个输入-传统输入张量和当前一批热编码标签。我想我已经将模型设置为接受2个输入,但是我得到了:

  

ValueError:检查模型时出错:传递给模型的Numpy数组列表不是模型预期的大小。预计会看到2个数组,但获得了以下1个数组的列表。 [array([[[[[0。],...

大多数答案建议将输入转换为numpy数组,但是mnist图像和标签默认为numpy数组。

batch_size = 128
num_classes = 10
epochs = 1

# Mnist part

img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Model part

images = Input(shape=input_shape, name='images_input')
labels = Input(shape=(num_classes,), name='labels_input')

x = Conv2D(32, kernel_size=(3, 3), activation='relu')(images)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(128, activation='relu', name='features')(x)
x = Dropout(0.5)(x)
x = SomeLayerWith2Inputs()([x, labels])
output = Dense(num_classes, activation='softmax')(x)

model = Model(inputs=[images, labels], outputs=output)

model.compile(
    loss=keras.losses.categorical_crossentropy,
    optimizer=keras.optimizers.Adadelta(),
    metrics=['accuracy']
)

# x_train = <type 'numpy.ndarray'> (60000, 28, 28, 1)
# y_train = <type 'numpy.ndarray'> (60000, 10)
# x_test = <type 'numpy.ndarray'> (10000, 28, 28, 1)
# y_test = <type 'numpy.ndarray'> (10000, 10)

model.fit(
    [x_train, y_train],
    y_train,
    batch_size=batch_size,
    callbacks=[tensorboard],
    epochs=epochs,
    verbose=1,
    validation_data=([x_test, y_test], y_test)
)

我也尝试过做model.fit(x={'images_input': x_train, 'labels_input': y_train}, y=y_train),但这也没用。

我正在使用Keras v2.2.4

1 个答案:

答案 0 :(得分:0)

发现了问题。还有一个tensorboard回调(原始问题未显示):

tensorboard = TensorBoard(
    batch_size=128,
    embeddings_freq=1,
    embeddings_layer_names=['features'],
    embeddings_metadata='metadata.tsv',
    embeddings_data=x_test
)

embeddings_data参数应为[x_test, y_test]