【问题标题】:Attention on top of LSTM Keras关注 LSTM Keras
【发布时间】:2018-11-06 22:27:00
【问题描述】:

我正在使用 Keras 训练一个 LSTM 模型,并希望在其上添加 Attention。我是 Keras 的新手,注意。从链接How to add an attention mechanism in keras? 我了解了如何在我的 LSTM 层上添加注意力并制作了这样的模型

print('Defining a Simple Keras Model...')
lstm_model=Sequential()  # or Graph 
lstm_model.add(Embedding(output_dim=300,input_dim=n_symbols,mask_zero=True,
                    weights=[embedding_weights],input_length=input_length))  

# Adding Input Length
lstm_model.add(Bidirectional(LSTM(300)))
lstm_model.add(Dropout(0.3))
lstm_model.add(Dense(1,activation='sigmoid'))

# compute importance for each step
attention=Dense(1, activation='tanh')
attention=Flatten()
attention=Activation('softmax')
attention=RepeatVector(64)
attention=Permute([2, 1])


sent_representation=keras.layers.Add()([lstm_model,attention])
sent_representation=Lambda(lambda xin: K.sum(xin, axis=-2),output_shape=(64))(sent_representation)

sent_representation.add(Dense(1,activation='sigmoid'))

rms_prop=RMSprop(lr=0.001,rho=0.9,epsilon=None,decay=0.0)
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
print('Compiling the Model...')
sent_representation.compile(loss='binary_crossentropy',optimizer=adam,metrics=['accuracy'])
          #class_mode='binary')

earlyStopping=EarlyStopping(monitor='val_loss',min_delta=0,patience=0,
                                    verbose=0,mode='auto')

print("Train...")
sent_representation.fit(X_train, y_train,batch_size=batch_size,nb_epoch=20,
          validation_data=(X_test,y_test),callbacks=[earlyStopping])

输出将是 0/1 的情绪分析。为此,我添加了一个

 sent_representation.add(Dense(1,activation='sigmoid'))

让它给出一个二进制结果。

这是我们在运行代码时遇到的错误:

ERROR:
  File "<ipython-input-6-50a1a221497d>", line 18, in <module>
    sent_representation=keras.layers.Add()([lstm_model,attention])

  File "C:\Users\DuttaHritwik\Anaconda3\lib\site-packages\keras\engine\topology.py", line 575, in __call__
    self.assert_input_compatibility(inputs)

  File "C:\Users\DuttaHritwik\Anaconda3\lib\site-packages\keras\engine\topology.py", line 448, in assert_input_compatibility
    str(inputs) + '. All inputs to the layer '

ValueError: Layer add_1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.models.Sequential'>. Full input: [<keras.models.Sequential object at 0x00000220B565ED30>, <keras.layers.core.Permute object at 0x00000220FE853978>]. All inputs to the layer should be tensors.

你能看看并告诉我们我们做错了什么吗?

【问题讨论】:

标签: tensorflow keras deep-learning lstm attention-model


【解决方案1】:

keras.layers.Add() 接受张量,所以在

sent_representation=keras.layers.Add()([lstm_model,attention])

您将顺序模型作为输入传递,但遇到了错误。 将初始层从使用 Sequential 模型更改为使用功能 api。

lstm_section = Embedding(output_dim=300,input_dim=n_symbols,mask_zero=True, weights=[embedding_weights],input_length=input_length)( input )
lstm_section = Bidirectional(LSTM(300)) ( lstm_section )
lstm_section = Dropout(0.3)( lstm_section ) 
lstm_section = Dense(1,activation='sigmoid')( lstm_section )

lstm_section 是一个张量,然后可以在您的 Add() 调用中替换 lstm_model

由于您使用的是函数式 API 而不是 Sequential,因此您还需要创建模型,使用 your_model = keras.models.Model( inputs, sent_representation )

还值得注意的是,您提供的链接中的注意力模型是相乘而不是相加,因此可能值得使用keras.layers.Multiply()

编辑

刚刚注意到您的注意力部分也没有构建图表,因为您没有将每一层传递到下一层。应该是:

attention=Dense(1, activation='tanh')( lstm_section )
attention=Flatten()( attention )
attention=Activation('softmax')( attention )
attention=RepeatVector(64)( attention )
attention=Permute([2, 1])( attention )

【讨论】:

  • 我试过这样做sent_representation=Add()([lstm_section, attention])但是这个错误出来了:Layer add_3 was called with an input that isn't a symbolic tensor. Received type: &lt;class 'keras.layers.core.Permute'&gt;. Full input: [&lt;keras.layers.core.Permute object at 0x000001D0B2E28048&gt;, &lt;keras.layers.core.Permute object at 0x000001D0B2E28048&gt;]. All inputs to the layer should be tensors.因为它似乎一个是张量其他不是,我也尝试过:sent_representation=Add()([lstm_section, lstm_section])sent_representation=Add()([attention, attention])错误仍然存​​在。跨度>
  • 编辑答案以解决该问题
  • 这就是我现在得到的:ValueError: Layer add_8 was called with an input that isn't a symbolic tensor. Received type: &lt;class 'keras.layers.core.Dense'&gt;. Full input: [&lt;keras.layers.core.Dense object at 0x000001D0BA937E80&gt;, &lt;keras.layers.core.Permute object at 0x000001D0B4B85CC0&gt;]. All inputs to the layer should be tensors.
  • 在我实施更改后,代码对我有用。您能否编辑您的原始帖子并添加代码的当前状态?
猜你喜欢
  • 2019-12-03
  • 2018-09-16
  • 1970-01-01
  • 2016-12-07
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多