具有多个输入的 Keras 顺序模型,Tensorflow 1.9.0

Keras sequential model with multiple inputs, Tensorflow 1.9.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 got the following list of 1 arrays:
[array([[[-1.07920336,  1.16782929,  1.40131554, -0.30052492],
         [-0.50067655,  0.54517916, -0.87033621, -0.22922157]],

        [[-0.53766128, -0.03527806, -0.14637072,  2.32319071],
         [ 0...

我认为,问题在于,一旦我通过数据进行训练,输入的形状不正确或者我有数据类型问题。因此,数组周围有一个额外的列表括号。

我使用的是 Tensorflow 1.9.0(由于项目限制)。我已经检查了搜索功能并尝试了提供的解决方案 。以下是重现我的错误的示例代码:

import numpy as np
import tensorflow as tf
from tensorflow import keras
import keras.backend as K
from tensorflow.keras import layers, models

def main():

    ip1 = keras.layers.Input(shape=(4,))
    ip2 = keras.layers.Input(shape=(4,))
    dense = layers.Dense(3, activation='sigmoid', input_dim=4)  # Passing the value in a weighted manner
    merge_layer = layers.Concatenate()([ip1, ip2])  # Concatenating the outputs of the first network
    y = layers.Dense(6, activation='sigmoid')(merge_layer)  # Three fully connected layers
    y = layers.Dense(4, activation='sigmoid')(y)
    model = keras.Model(inputs=[ip1, ip2], outputs=y)

    model.compile(optimizer='adam',
                  loss='mean_squared_error')
    model.summary()

    # dataset shape: 800 samples, 2 inputs for sequential model, 4 input size
    X_train = np.random.randn(800, 2, 4)
    y_train = np.random.randn(800, 4)
    X_test = np.random.randn(200, 2, 4)
    y_test = np.random.randn(200, 4)

    history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1000, batch_size=32)


 if __name__ == '__main__':
     main()

当有多个输入时,keras 需要多个数组的列表。列表的大小对应于您对模型的输入数量。

所以基本上你需要传递 2 个数组的列表,每个数组的形状为 (X,4)

X_train1 = np.random.randn(800, 4)
X_train2=np.random.randn(800,4)
y_train = np.random.randn(800, 4)
X_test1 = np.random.randn(200, 4)
X_test2 = np.random.randn(200, 4)
y_test = np.random.randn(200, 4)

history = model.fit([X_train1,X_train2], y_train, validation_data=([X_test1,X_test2], y_test), epochs=1000, batch_size=32)