在Keras中将顺序转换为功能 [英] Convert Sequential to Functional in Keras
问题描述
我有一个按顺序样式编写的keras代码.但是我想切换Functional mode
,因为我想使用merge
函数.但是在声明Model(x, out)
时,我在下面遇到了一个错误.我的Functional API代码有什么问题?
I have a keras code written in Sequential style. But I am trying to switch Functional mode
because I want to use merge
function. But I faced an error below when declaring Model(x, out)
. What is wrong in my Functional API code?
# 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:图形已断开:无法获得张量的值 层上的Tensor("input_40:0",shape =(?, 1,16),dtype = float32) "input_40".可以访问以下先前的层,而不会出现问题: ['input_39','lstm_37']
RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("input_40:0", shape=(?, 1, 16), dtype=float32) at layer "input_40". The following previous layers were accessed without issue: ['input_39', 'lstm_37']
已更新
谢谢@MarcinMożejko.我终于做到了.
Updated
Thank you @Marcin Możejko. I finally did it.
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, ...)
推荐答案
一个人可能注意到,对Input((seq_len, out_size))
调用创建的对象的引用仅可从merge
函数调用环境访问.而且-它没有添加到Model
定义-是什么使图形断开连接.您需要做的是:
One may notice that reference of an object created by a Input((seq_len, out_size))
call is accesible only from merge
funciton call evironment. Moreover - it's not add to a Model
definition - what makes graph disconnected. What you need to do is:
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
这篇关于在Keras中将顺序转换为功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!