在Keras中将顺序转换为功能

时间:2017-03-15 08:51:36

标签: python machine-learning deep-learning keras lstm

我有一个以顺序风格编写的keras代码。但我正在尝试切换Functional mode,因为我想使用merge函数。但是在宣布Model(x, out)时我遇到了一个错误。我的Functional API代码有什么问题?

# Sequential, this is working
# out_size==16, seq_len==1
model = Sequential()
model.add(LSTM(128, 
               input_shape=(seq_len, input_dim),
               activation='tanh', 
               return_sequences=True))
model.add(TimeDistributed(Dense(out_size, activation='softmax')))

# Functional API
x = Input((seq_len, input_dim))
lstm = LSTM(128, return_sequences=True, activation='tanh')(x)
td = TimeDistributed(Dense(out_size, activation='softmax'))(lstm)
out = merge([td, Input((seq_len, out_size))], mode='mul')
model = Model(input=x, output=out) # error below
  

RuntimeError:Graph disconnected:无法获取张量值   层的张量(“input_40:0”,shape =(?,1,16),dtype = float32)   “input_40”。访问以下先前的图层时没有问题:   ['input_39','lstm_37']

更新

谢谢@MarcinMożejko。我终于做到了。

x = Input((seq_len, input_dim))
lstm = LSTM(128, return_sequences=True, activation='tanh')(x)
td = TimeDistributed(Dense(out_size, activation='softmax'))(lstm)
second_input = Input((seq_len, out_size)) # object instanciated and hold as a var.
out = merge([td, second_input], mode='mul')
model = Model(input=[x, second_input], output=out) # second input provided to model.compile(...)

# then I add two inputs
model.fit([trainX, filter], trainY, ...)

1 个答案:

答案 0 :(得分:1)

有人可能会注意到,Input((seq_len, out_size))调用创建的对象的引用只能从merge函数调用环境中访问。此外 - 它没有添加到Model定义 - 图表断开连接的原因。你需要做的是:

x = Input((seq_len, input_dim))
lstm = LSTM(128, return_sequences=True, activation='tanh')(x)
td = TimeDistributed(Dense(out_size, activation='softmax'))(lstm)
second_input = Input((seq_len, out_size)) # object instanciated and hold as a var.
out = merge([td, second_input], mode='mul')
model = Model(input=[x, second_input], output=out) # second input provided to model