Keras实现Hierarchical Attention Network时的一些坑
Reshape
对于的张量x,x.shape=(a, b, c, d)的情况
若调用keras.layer.Reshape(target_shape=(-1, c, d)),
处理后的张量形状为(?, ?, c, d)
若调用tf.reshape(x, shape=[-1, c, d])
处理后的张量形状为(a*b, c, d)
为了在keras代码中实现tf.reshape的效果,用lambda层做,
调用Lambda(lambda x: tf.reshape(x, shape=[-1, c, d]))(x)
nice and cool.
输出Attention的打分
这里,我们希望attention层能够输出attention的score,而不只是计算weighted sum。
在使用时
score = Attention()(x)
weighted_sum = MyMerge()([score, x])
class Attention(Layer):
def __init__(self, **kwargs):
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 3
self.w = self.add_weight(name="attention_weight",
shape=(input_shape[-1],
input_shape[-1]),
initializer='uniform',
trainable=True
)
self.b = self.add_weight(name="attention_bias",
shape=(input_shape[-1],),
initializer='uniform',
trainable=True
)
self.v = self.add_weight(name="attention_v",
shape=(input_shape[-1], 1),
initializer='uniform',
trainable=True
)
super(Attention, self).build(input_shape)
def call(self, inputs):
x = inputs
att = K.tanh(K.dot(x, self.w) + self.b)
att = K.softmax(K.dot(att, self.v))
print(att.shape)
return att
def compute_output_shape(self, input_shape):
return input_shape[0], input_shape[1], 1
class MyMerge(Layer):
def __init__(self, **kwargs):
super(MyMerge, self).__init__(**kwargs)
def call(self, inputs):
att = inputs[0]
x = inputs[1]
att = tf.tile(att, [1, 1, x.shape[-1]])
outputs = tf.multiply(att, x)
outputs = K.sum(outputs, axis=1)
return outputs
def compute_output_shape(self, input_shape):
return input_shape[1][0], input_shape[1][2]
keras中Model的嵌套
这边是转载自https://github.com/uhauha2929/examples/blob/master/Hierarchical%20Attention%20Networks%20.ipynb
可以看到,sentEncoder是Model类型,在后面的时候通过TimeDistributed(sentEncoder),当成一个层那样被调用。
embedding_layer = Embedding(len(word_index) + 1,
EMBEDDING_DIM,
input_length=MAX_SENT_LENGTH)
sentence_input = Input(shape=(MAX_SENT_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sentence_input)
l_lstm = Bidirectional(LSTM(100))(embedded_sequences)
sentEncoder = Model(sentence_input, l_lstm)
review_input = Input(shape=(MAX_SENTS,MAX_SENT_LENGTH), dtype='int32')
review_encoder = TimeDistributed(sentEncoder)(review_input)
l_lstm_sent = Bidirectional(LSTM(100))(review_encoder)
preds = Dense(2, activation='softmax')(l_lstm_sent)
model = Model(review_input, preds)
Keras实现Hierarchical Attention Network时的一些坑的更多相关文章
- Hierarchical Attention Based Semi-supervised Network Representation Learning
Hierarchical Attention Based Semi-supervised Network Representation Learning 1. 任务 给定:节点信息网络 目标:为每个节 ...
- Dual Attention Network for Scene Segmentation
Dual Attention Network for Scene Segmentation 原始文档 https://www.yuque.com/lart/papers/onk4sn 在本文中,我们通 ...
- 语义分割之Dual Attention Network for Scene Segmentation
Dual Attention Network for Scene Segmentation 在本文中,我们通过 基于自我约束机制捕获丰富的上下文依赖关系来解决场景分割任务. 与之前通过多尺 ...
- Paper | Residual Attention Network for Image Classification
目录 1. 相关工作 2. Residual Attention Network 2.1 Attention残差学习 2.2 自上而下和自下而上 2.3 正则化Attention 最近看了些关于att ...
- A Survey of Model Compression and Acceleration for Deep Neural Network时s
A Survey of Model Compression and Acceleration for Deep Neural Network时s 本文全面概述了深度神经网络的压缩方法,主要可分为参数修 ...
- 注意力机制---Attention、local Attention、self Attention、Hierarchical attention
一.编码-解码架构 目的:解决语音识别.机器翻译.知识问答等输出输入序列长度不相等的任务. C是输入的一个表达(representation),包含了输入序列的有效信息. 它可能是一个向量,也可能是一 ...
- Residual Attention Network for Image Classification(CVPR 2017)详解
一.Residual Attention Network 简介 这是CVPR2017的一篇paper,是商汤.清华.香港中文和北邮合作的文章.它在图像分类问题上,首次成功将极深卷积神经网络与人类视觉注 ...
- 论文解读(FedGAT)《Federated Graph Attention Network for Rumor Detection》
论文信息 论文标题:Federated Graph Attention Network for Rumor Detection论文作者:Huidong Wang, Chuanzheng Bai, Ji ...
- 关于pyinstaller打包程序时设置icon时的一个坑
关于pyinstaller打包程序时设置icon时的一个坑 之前在用pyinstaller打包程序的时候遇到了关于设置图标的一点小问题,无论在后面加--icon 或是-i都出现报错.查了下st ...
随机推荐
- 【计算机视觉】OpenCV篇(4) - Pycharm+PyQt5+Python小项目实战
1.下载安装 (1)Pycharm:下载链接 (2)推荐使用Qt Designer来设计界面,如果你装的是Anaconda的话,就已经自带了designer.exe,我这里使用的是Pycharm的虚拟 ...
- 【Leetcode_easy】844. Backspace String Compare
problem 844. Backspace String Compare solution1: class Solution { public: bool backspaceCompare(stri ...
- SourceTree 免登录跳过初始设置的方法 for Windows
SourceTree安装包下载地址: 链接: https://pan.baidu.com/s/1rOPQkfNqvLGcIeZNw0aAjw 密码: 42us nodev6.9.0 和git 链接:h ...
- web端自动化——selenium测试报告生成、找到测试报告路径、实现发邮件(整合)
有这样的一个场景: 假设生成的测试报告与多人相关,每个人都去测试服务器査看就会比较麻烦,如果把这种主动的且不及时的査看变成被动且及时的査收,就方便多了. 整个程序的执行过程可以分为三个步骤: ① ...
- console.log()和alert()的区别
一直都是知道console.log()和alert()是有区别的,但是具体有什么区别就不清楚了,后来在权威指南里注意到了说alert()具有侵入性才来查一查两者的具体区别. 查询到的区别: alert ...
- String类的构造函数,析构函数、拷贝构造函数和赋值函数
(1)构造函数 String::String(const char *str) { if(str==NULL) { m_data = new char[1]; *m_data = ‘\0’; } el ...
- docker 安装 tomcat8
docker hub 查找 tomcat meiya@meiya:/etc/docker$ docker search tomcat NAME DESCRIPTION STARS OFFICIAL A ...
- quartz定时任务存储
今天不聊quartz的概念,像任务bean,触发器,调度器这些随随便便都可以百度到,其中任务bean要实现job接口.对于这些创建生成的定时任务,它可以保存在内存中,重启失效,也可以保存在数据库里重启 ...
- [WCF] - 使用 [DataMember] 标记的数据契约需要声明 Set 方法
WCF 数据结构中返回的只读属性 TotalCount 也需要声明 Set 方法. [DataContract]public class BookShelfDataModel{ public B ...
- Python 实例代码二
1.实现isNum()函数,参数为一个字符串,如果这个字符串属于整数.浮点数或复数的表示,则返回True,否则返回False def isNum(word): try: word=type(eval( ...