首页 > 解决方案 > 为什么在 Keras 中包裹一层会移除另一层的内核属性?

问题描述

我目前正在为时间序列预测创建一个基于 LSTM 的网络,我想尝试使用 Keras 的Bidirectional包装器来看看它是否可以提高我的准确性。

但是,添加包装器会导致我的输出层丢失其kernel属性,这是有问题的,因为我的优化器尝试访问它,导致编译期间崩溃。

也就是说,当我这样做时:

model = Sequential()
model.add(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
))
model.add(Dense(1))

print(hasattr(model.layers[-1], 'kernel'))

真的

但是当像这样包装 LSTM 时:

model = Sequential()
model.add(Bidirectional(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
)))
model.add(Dense(1))

print(hasattr(model.layers[-1], 'kernel'))

错误的

标签: pythontensorflowmachine-learningkeras

解决方案


解决方案是让您的网络预测某些内容,然后使用您的自定义优化器对其进行编译:

model = Sequential()
model.add(Bidirectional(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
)))
model.add(Dense(1))

model.predict(np.zeros((batch_size, look_back, features)))
print(hasattr(model.layers[-1], 'kernel'))
model.compile(optimizer=CustomOptimizer(), loss='mse')

真的


推荐阅读