python - 如何将两个 LSTM 与 Keras 连接起来?

标签 python keras neural-network lstm

有类似的问题,但它们要么已过时,要么不适用于我的情况。

这是我的代码:

  left = Sequential()
  left.add(LSTM(units=24,input_shape=(left_X.shape[1], left_X.shape[2])))
  left.add(Dense(1))

  right = Sequential()
  right.add(LSTM(units=24,input_shape=(right_X.shape[1], right_X.shape[2])))
  right.add(Dense(1))

  model = Sequential()
  model.add(Concatenate([left,right]))  
  model.add(Flatten())
  model.add(Dense(1, activation='linear'))

  model.compile(loss='mse',
          optimizer='adam',
          metrics=['mae'])

 history = model.fit([left_X, right_X], train_y, 
                epochs=40,
                validation_split=0.2,
                verbose=1)

它为 fit 引发了一个断言错误

  585             # since `Sequential` depends on `Model`.
    586             if isinstance(inputs, list):
--> 587                 assert len(inputs) == 1
    588                 inputs = inputs[0]
    589             self.build(input_shape=(None,) + inputs.shape[1:])

最佳答案

我使用以下使用 Keras 函数式 API 的代码解决了这个问题:

inp1 = Input(shape=(train_X_1.shape[1], train_X_1.shape[2]))
inp2 = Input(shape=(train_X_2.shape[1], train_X_2.shape[2]))
inp3 = Input(shape=(train_X_3.shape[1], train_X_3.shape[2]))

x = SimpleRNN(10)(inp1)
x = Dense(1)(x)

y = LSTM(10)(inp2)
y = Dense(1)(y)

z = LSTM(10)(inp3)
z = Dense(1)(z)

w = concatenate([x, y, z])

# u =  Dense(3)(w)
out =  Dense(1, activation='linear')(w)

model = Model(inputs=[inp1, inp2, inp3], outputs=out)

model.compile(loss='logcosh',
        optimizer='adam',
        metrics=['mae'])

history = model.fit([train_X_1, train_X_2, train_X_3], train_y, 
                epochs=20,
                validation_split=0.1,
                verbose=1)

关于python - 如何将两个 LSTM 与 Keras 连接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956998/

相关文章:

python - 加载 EMNIST-letters 数据集

python - 解析 CSV 文件,并将其写入另一种 CSV 格式

tensorflow - 如何增加 Keras 中的数据训练偏差?

python - 自动编码器最后一层的 Keras 尺寸不匹配

java - 使用神经网络发现关系

neural-network - 图灵完备性有多大用处?神经网络图灵完备吗?

python tcp服务器向多个客户端发送数据

python - 按下一个键时只增加一个

python - 在 Keras 损失函数中 reshape TensorFlow 张量?

python - Spacy:如何确定过拟合的参数?