繁体   English   中英

具有多个输入的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM