来自for循环的Keras LSTM,使用具有自定义层数的功能性API

时间:2019-01-17 18:02:41

标签: machine-learning keras lstm keras-layer

我正在尝试通过keras功能API建立一个网络,该API提供两个包含LSTM层和FC(密集)层的单元数的列表。我想分析20个连续的分段(批次),每个分段包含fs个时间步长和2个值(每个时间步长2个特征)。这是我的代码:

Rec = [4,4,4]  
FC = [8,4,2,1]    
def keras_LSTM(Rec,FC,fs, n_witness, lr=0.04, optimizer='Adam'):
    model_LSTM = Input(batch_shape=(20,fs,n_witness))
    return_state_bool=True
    for i in range(shape(Rec)[0]):
        nRec = Rec[i]
        if i == shape(Rec)[0]-1:
            return_state_bool=False
        model_LSTM = LSTM(nRec, return_sequences=True,return_state=return_state_bool,
                     stateful=True, input_shape=(None,n_witness),            
                     name='LSTM'+str(i))(model_LSTM)
    for j in range(shape(FC)[0]):
        nFC = FC[j]
        model_LSTM = Dense(nFC)(model_LSTM)
        model_LSTM = LeakyReLU(alpha=0.01)(model_LSTM)
    nFC_final = 1
    model_LSTM = Dense(nFC_final)(model_LSTM)
    predictions = LeakyReLU(alpha=0.01)(model_LSTM)

    full_model_LSTM = Model(inputs=model_LSTM, outputs=predictions)
    model_LSTM.compile(optimizer=keras.optimizers.Adam(lr=lr, beta_1=0.9, beta_2=0.999,
                    epsilon=1e-8, decay=0.066667, amsgrad=False), loss='mean_squared_error')
    return full_model_LSTM

model_new = keras_LSTM(Rec, FC, fs=fs, n_witness=n_wit)
model_new.summary()

编译时出现以下错误:

ValueError:图形已断开连接:无法获取层“ input_1”上的张量Tensor(“ input_1:0”,shape =(20,2048,2),dtype = float32)的值。可以顺利访问以下先前的图层:[]

我实际上不太了解,但是怀疑这可能与输入有关?

1 个答案:

答案 0 :(得分:0)

我通过修改代码的第4行来解决了该问题,如下所示:

x = model_LSTM = Input(batch_shape=(20,fs,n_witness))

以及第21行,如下所示:

full_model_LSTM = Model(inputs=x, outputs=predictions)