tensorflow - LSTM Keras 之上的 Attention

标签 tensorflow keras deep-learning lstm attention-model

我正在使用 Keras 训练 LSTM 模型,并希望在其之上添加注意力机制。我是 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.

您能看一下并告诉我们我们在这里做错了什么吗?

最佳答案

keras.layers.Add() 采用张量,因此位于

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

您正在传递一个顺序模型作为输入并收到错误。 将初始层从使用顺序模型更改为使用函数式 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(输入,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 )

关于tensorflow - LSTM Keras 之上的 Attention,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564473/

相关文章:

python - 在 Tensorflow 中将张量转换为 numpy 数组?

tensorflow - 在 keras 中连接和添加有什么区别?

python - 如何使用经过训练的模型编写 keras 以读取我自己的图片?

tensorflow - 是否可以在 GPU 上训练模型,然后在 CPU 上进行预测

audio - 如何在机器学习中处理长音频片段?

python - 如何在 CNN block 上应用 TimeDistributed 层?

python - Tensorflow 训练错误

python - Keras:在不同的模型中使用相同的层(共享权重)

python - 来自 tf.keras.preprocessing.image.ImageDataGenerator.flow_from_directory 的 tf.data.Dataset?

python - 错误 : Failed to load the native TensorFlow runtime