无法建立模型,因为backend.squeeze没有层

时间:2018-09-17 10:18:00

标签: python tensorflow keras lstm

我正在尝试建立一个模型,在该模型中必须压缩张量,然后将其输入LSTM。

由于压缩张量不具有layer属性,因此无法编译模型。

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:/workspace/keras_test/src/testing.py", line 10, in <module>
    model = Model(inputs=model_in, outputs=output)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 93, in __init__
    self._init_graph_network(*args, **kwargs)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 237, in _init_graph_network
    self.inputs, self.outputs)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 1353, in _map_graph_network
    tensor_index=tensor_index)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 1340, in build_map
    node_index, tensor_index)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 1340, in build_map
    node_index, tensor_index)
  File "E:\ProgramData\Miniconda3\envs\py37\lib\site-packages\keras\engine\network.py", line 1312, in build_map
    node = layer._inbound_nodes[node_index]
AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

有关最低示例,请参见:

from keras import Input, backend, Model
from keras.layers import LSTM, Dense

input_shape = (128, 1, 1)
model_in = Input(tensor=Input(input_shape), shape=input_shape)
squeezed = backend.squeeze(model_in, 2)
hidden1 = LSTM(10)(squeezed)
output = Dense(1, activation='sigmoid')(hidden1)

model = Model(inputs=model_in, outputs=output)
model.summary()

如何在不丢失图层信息的情况下删除model_in的一个维度?

1 个答案:

答案 0 :(得分:3)

后端操作squeeze未包装在Lambda层中,因此生成的张量不是Keras张量。结果,它缺少诸如_inbound_nodes之类的某些属性。您可以按以下步骤包装squeeze操作:

from keras import Input, backend, Model
from keras.layers import LSTM, Dense, Lambda

input_shape = (128, 1, 1)
model_in = Input(tensor=Input(input_shape), shape=input_shape)
squeezed = Lambda(lambda x: backend.squeeze(x, 2))(model_in)
hidden1 = LSTM(10)(squeezed)
output = Dense(1, activation='sigmoid')(hidden1)

model = Model(inputs=model_in, outputs=output)
model.summary()