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时的一些坑的更多相关文章

  1. Hierarchical Attention Based Semi-supervised Network Representation Learning

    Hierarchical Attention Based Semi-supervised Network Representation Learning 1. 任务 给定:节点信息网络 目标:为每个节 ...

  2. Dual Attention Network for Scene Segmentation

    Dual Attention Network for Scene Segmentation 原始文档 https://www.yuque.com/lart/papers/onk4sn 在本文中,我们通 ...

  3. 语义分割之Dual Attention Network for Scene Segmentation

    Dual Attention Network for Scene Segmentation 在本文中,我们通过 基于自我约束机制捕获丰富的上下文依赖关系来解决场景分割任务.       与之前通过多尺 ...

  4. Paper | Residual Attention Network for Image Classification

    目录 1. 相关工作 2. Residual Attention Network 2.1 Attention残差学习 2.2 自上而下和自下而上 2.3 正则化Attention 最近看了些关于att ...

  5. A Survey of Model Compression and Acceleration for Deep Neural Network时s

    A Survey of Model Compression and Acceleration for Deep Neural Network时s 本文全面概述了深度神经网络的压缩方法,主要可分为参数修 ...

  6. 注意力机制---Attention、local Attention、self Attention、Hierarchical attention

    一.编码-解码架构 目的:解决语音识别.机器翻译.知识问答等输出输入序列长度不相等的任务. C是输入的一个表达(representation),包含了输入序列的有效信息. 它可能是一个向量,也可能是一 ...

  7. Residual Attention Network for Image Classification(CVPR 2017)详解

    一.Residual Attention Network 简介 这是CVPR2017的一篇paper,是商汤.清华.香港中文和北邮合作的文章.它在图像分类问题上,首次成功将极深卷积神经网络与人类视觉注 ...

  8. 论文解读(FedGAT)《Federated Graph Attention Network for Rumor Detection》

    论文信息 论文标题:Federated Graph Attention Network for Rumor Detection论文作者:Huidong Wang, Chuanzheng Bai, Ji ...

  9. 关于pyinstaller打包程序时设置icon时的一个坑

    关于pyinstaller打包程序时设置icon时的一个坑     之前在用pyinstaller打包程序的时候遇到了关于设置图标的一点小问题,无论在后面加--icon 或是-i都出现报错.查了下st ...

随机推荐

  1. 【429】关于ADT的访问权限

    在看老师代码的时候,发现ADT中的 struct 有时候写到了 adt.c 里面,有时候写到了 adt.h 里面,其实有些困惑,经过仔细研究,发现写在 adt.h 中的 struct 可以在 test ...

  2. Python - Django - ORM 自定义表名

    通过 Django 建立的表 命名方式为:项目名_表名 可以将该默认命名方式进行修改 models.py: from django.db import models class Person(mode ...

  3. Vue学习笔记十:过滤器

    目录 公共过滤器的写法 简易过滤器+带参数过滤器+多过滤器 私有过滤器 公共过滤器的写法 过滤器的写法还是很简单的 ,如下 <p>{{ msg | filtermsg }}</p&g ...

  4. elasticsearch5.0.1集群索引分片丢失的处理

    elasticdump命令安装 yum install npm npm install elasticdump -g 命令安装完毕,可以测试. 可能会报出nodejs的版本之类的错误,你需要升级一下版 ...

  5. Python3 IO编程之序列化

    在程序运行的过程中,所有变量都是在内存中,比如定义一个dict >>> d=dict(name='Box',age=20,score=11) 可以随时修改变量,比如把'name'改成 ...

  6. const的用法及它在C语言和C++中的不同

    (1)可以定义const常量. (2)Const可以修饰函数的参数和返回值,甚至定义体.被const修饰的东西都受到强制保护. (3)Const修饰成员函数时,用于成员函数前面,则返回值不能作为左值. ...

  7. [CF1005F]Berland and the Shortest Paths_最短路树_堆优化dij

    Berland and the Shortest Paths 题目链接:https://www.codeforces.com/contest/1005/problem/F 数据范围:略. 题解: 太鬼 ...

  8. LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

    199. 二叉树的右视图 199. Binary Tree Right Side View 题目描述 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值. Giv ...

  9. Variational Auto-encoder(VAE)变分自编码器-Pytorch

    import os import torch import torch.nn as nn import torch.nn.functional as F import torchvision from ...

  10. AVL排序二叉树树

    AVL树第一部分,(插入) AVL树是一种自平衡二叉搜索树(BST),其中对于所有节点,左右子树的高度差不能超过1. 一个AVL树的示例 上面的树是AVL树,因为每个节点的左子树和右子树的高度之间的差 ...