如何使用 for loop 创建 Keras 多 LSTM 层?



我正在尝试使用for 循环Keras中实现多层LSTM,本教程能够优化层数,这显然是一个超参数。在教程中,作者使用skopt表示hyper-parameter optimization。我使用函数式 API 来创建我的模型。为简单起见,我将input_tensor的形状更改为任意值。 我的模型是:

from keras.layers.core import Dense
from keras.layers import LSTM, Input
from keras.models import Model
from keras.optimizers import RMSprop
from keras.initializers import glorot_uniform, glorot_normal, RandomUniform

input_tensor = Input(shape=(10, 20))
def create_model(learning_rate, num_lstm_layers, num_lstm_units, activation):
init = glorot_normal(seed=None)
init1 = RandomUniform(minval=-0.05, maxval=0.05)
x = Input(shape=(10, 20))

for i in range(num_lstm_layers):
name = 'layer_lstm_{0}'.format(i+1)
if( (i==0) and (num_lstm_layers==1) ):
x = LSTM(units=num_lstm_units, dropout=0.2, recurrent_dropout=0.2, 
return_sequences=False, kernel_initializer=init, 
activation=activation, name=name)(x)
elif(i != (num_lstm_layers-1) ):
x = LSTM(units=num_lstm_units, dropout=0.2, recurrent_dropout=0.2,  
return_sequences=True, kernel_initializer=init, 
activation=activation, name=name)(x)
else:
x = LSTM(units=num_lstm_units, dropout=0.2, recurrent_dropout=0.2,  
return_sequences=False, kernel_initializer=init, 
activation=activation, name=name)(x)
x = Dense(1, activation='linear', kernel_initializer= init1)(x)
model = Model(input_tensor, x)
optimizer = RMSprop(lr=learning_rate, rho=0.9, epsilon=None, decay=0.0)
model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'] )
return model      

每当我尝试将模型拟合到数据时,都会遇到此错误:

值错误:变量 layer_lstm_1_14/内核/的初始值设定项来自 在控制流构造(如循环或条件(内。什么时候 在循环或条件内创建变量,使用 lambda 作为 初始 化。

到目前为止,我已经知道应该在某个地方添加一个lambda函数或keras Lambda layer。 另外,我在单独的python脚本中测试了该模型,如下所示:

model = create_model(learning_rate=1e-3, num_lstm_layers=3, num_lstm_units=64, activation='linear')

但它再次给了我这个错误:

值错误:图断开连接:无法获取张量的值 Tensor("input_2:0", shape=(?, 10, 20(, dtype=float32( at layer "input_2"。访问以下先前的图层没有问题: []

我还尝试创建Sequential版本的模型。但遇到了同样的错误。

编辑1:编辑if 语句从if( i==0): 到if( (i==0) and (num_lstm_layers==1) ):通过这样做并进行 André 建议的更改,您可以使用 for 循环创建 LSTM 模型。

正如我在评论中所说,我不担心你的 for 循环,而是担心输入。我不是 100% 确定,但认为您应该尝试删除

input_tensor = Input(shape=(10, 20)) 

。它位于create_model(...)函数之前,并编辑内部函数的创建,如下所示:

input_tensor = x = Input(shape=(10, 20))

继续阅读,你说你得到Graph disconnected: cannot obtain value for tensor.这听起来肯定像您的输入没有连接。我建议的更改应该连接您的输入和输出(分别是Model(...)的第一个和第二个参数(。

最新更新