【问题标题】:Keras - How to remove useless dimension without hurting the computation graph?Keras - 如何在不损害计算图的情况下删除无用的维度?
【发布时间】:2019-03-29 16:02:55
【问题描述】:

在生成深度学习模型时,我使用K.squeeze 函数在前两个维度为无形状时挤压无用维度。

import keras.backend as K
>>> K.int_shape(user_input_for_TD)
(None, None, 1, 32)
>>> K.int_shape(K.squeeze(user_input_for_TD, axis=-2))
(None, None, 32)

但是,这给出了以下错误,似乎K.squeeze 函数损害了计算图,有什么解决方案可以摆脱这个问题吗?也许那个函数不支持计算梯度,这是不可微分的。

File "/home/sundong/anaconda3/envs/py36/lib/python3.6/site-packages/keras/engine/network.py", line 1325, in build_map
    node = layer._inbound_nodes[node_index]
AttributeError: 'NoneType' object has no attribute '_inbound_nodes'

下面的代码块是导致该错误的整个代码块。

user_embedding_layer = Embedding(
            input_dim=len(self.data.visit_embedding),
            output_dim=32,
            weights=[np.array(list(self.data.visit_embedding.values()))],
            input_length=1,
            trainable=False)
...
all_areas_lstm = LSTM(1024, return_sequences=True)(all_areas_rslt)   # (None, None, 1024)
user_input_for_TD = Lambda(lambda x: x[:, :, 0:1])(multiple_inputs)  # (None, None, 1) 
user_input_for_TD = TimeDistributed(user_embedding_layer)(user_input_for_TD) # (None, None, 1, 32) 
user_input_for_TD = K.squeeze(user_input_for_TD, axis=-2) # (None, None, 32) 
aggre_threeway_inputs = Concatenate()([user_input_for_TD, all_areas_lstm]) # should be (None, None, 1056) 
threeway_encoder = TimeDistributed(ThreeWay(output_dim=512))
three_way_rslt = threeway_encoder(aggre_threeway_inputs) # should be (None, None, 512) 
logits = Dense(365, activation='softmax')(three_way_rslt) # should be (None, None, 365)
self.model = keras.Model(inputs=multiple_inputs, outputs=logits)

通过删除以下两行(不使其通过嵌入层),代码可以正常工作。在这种情况下,aggre_threeway_inputs = Concatenate()([user_input_for_TD, all_areas_lstm]) 的维度是 (None, None, 1025)。

user_input_for_TD = TimeDistributed(user_embedding_layer)(user_input_for_TD)
user_input_for_TD = K.squeeze(user_input_for_TD, axis=-2)

【问题讨论】:

  • 你的意思是np.squeeze
  • @HaBom 这个指针不错,Keras 有没有等价的功能?
  • 你需要把你的squeeze函数放在一个Lambda层中,你不能把tf操作直接放到Keras层的输出中

标签: keras


【解决方案1】:

我通过使用带有索引的Lambda 层而不是K.squeeze 函数解决了这个问题。

from keras.layers import Lambda
>>> K.int_shape(user_input_for_TD)
(None, None, 1, 32)
>>> K.int_shape(Lambda(lambda x: x[:, :, 0, :])(user_input_for_TD))
(None, None, 32)

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2018-02-28
    相关资源
    最近更新 更多