处理顺序数据的注意机制,考虑每个时间戳的上下文

keras-self-attention的Python项目详细描述


凯拉斯自我关注

TravisCoveragePyPICodacy Badge

处理顺序数据的注意机制,考虑每个时间戳的上下文。

安装

pip install keras-self-attention

用法

基本

默认情况下,注意层使用附加注意,并在计算相关性时考虑整个上下文。下面的代码创建了一个关注层,它遵循第一节中的公式(attention_activatione_{t, t'}的激活函数):

importkerasfromkeras_self_attentionimportSeqSelfAttentionmodel=keras.models.Sequential()model.add(keras.layers.Embedding(input_dim=10000,output_dim=300,mask_zero=True))model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=128,return_sequences=True)))model.add(SeqSelfAttention(attention_activation='sigmoid'))model.add(keras.layers.Dense(units=5))model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['categorical_accuracy'],)model.summary()

局部注意力

对于一个数据来说,全球环境可能过于宽泛。参数attention_width控制本地上下文的宽度:

fromkeras_self_attentionimportSeqSelfAttentionSeqSelfAttention(attention_width=15,attention_activation='sigmoid',name='Attention',)

乘法注意

你可以通过设置attention_type

fromkeras_self_attentionimportSeqSelfAttentionSeqSelfAttention(attention_width=15,attention_type=SeqSelfAttention.ATTENTION_TYPE_MUL,attention_activation=None,kernel_regularizer=keras.regularizers.l2(1e-6),use_attention_bias=False,name='Attention',)

正则化

要使用正则化器,请将attention_regularizer_weight设置为正数:

importkerasfromkeras_self_attentionimportSeqSelfAttentioninputs=keras.layers.Input(shape=(None,))embd=keras.layers.Embedding(input_dim=32,output_dim=16,mask_zero=True)(inputs)lstm=keras.layers.Bidirectional(keras.layers.LSTM(units=16,return_sequences=True))(embd)att=SeqSelfAttention(attention_type=SeqSelfAttention.ATTENTION_TYPE_MUL,kernel_regularizer=keras.regularizers.l2(1e-4),bias_regularizer=keras.regularizers.l1(1e-4),attention_regularizer_weight=1e-4,name='Attention')(lstm)dense=keras.layers.Dense(units=5,name='Dense')(att)model=keras.models.Model(inputs=inputs,outputs=[dense])model.compile(optimizer='adam',loss={'Dense':'sparse_categorical_crossentropy'},metrics={'Dense':'categorical_accuracy'},)model.summary(line_length=100)

加载模型

确保将SeqSelfAttention添加到自定义对象:

importkeraskeras.models.load_model(model_path,custom_objects=SeqSelfAttention.get_custom_objects())

仅历史记录

当只能使用历史数据时,将history_only设置为True

SeqSelfAttention(attention_width=3,history_only=True,name='Attention',)

多头

请参考keras-multi-head

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何在安卓中更改SeekBar颜色?(以编程方式)   java在本地测试SpringOpenShift应用程序   java为什么局部变量仍然显示警告,尽管方法中使用了值?   未解析java Spring启动验证消息   java MultiSelectListPreference是否获取检查值?   xml签名中的java引用验证   eclipse JWNL(Java WordNet库)和WordNet   java Firebase addValueEventListener是否异步工作?   单选按钮的java@FindBy注释   通过JAVA Web服务调用时,安卓 ClassNotFound异常?   java Try catch不起作用(总是执行catch代码)   为什么Eclipse在尝试导入现有java项目或创建新项目时关闭时没有任何错误消息?   java Genesys Composer应用程序与Eclipse RCP应用程序有何不同   java替换方法无法正常工作   使用JavaFX8构建java MOJO   Spark使用Java没有可用的实时SolrServer来处理此请求   Java Optaplanner在不同的机器上进行不同的计算   在类之间导入java变量   在或多个运营商SAP Java中   java Hibernate保存SQL异常