1. TensorFlowTrainable类

 1 class TensorFlowTrainable(object):
2 def __init__(self):
3 self.parameters = []
4
5 def get_weights(self, dim_in, dim_out, name, trainable=True):
6 shape = (dim_out, dim_in)
7 weightsInitializer = tf.constant_initializer(
8 self.truncated_normal(shape=shape, stddev=0.01, mean=0.))
9 weights = tf.get_variable(
10 initializer=weightsInitializer, shape=shape, trainable=True, name=name)
11 if trainable:
12 self.parameters.append(weights)
13 return weights
14 def get_4Dweights(self, filter_height, filter_width, in_channels, out_channels, name, trainable=True):
15 shape = (filter_height, filter_width, in_channels, out_channels)
16 weightsInitializer = tf.constant_initializer(
17 self.truncated_normal(shape=shape, stddev=0.01, mean=0))
18 weights = tf.get_variable(
19 initializer=weightsInitializer, shape=shape, trainable=True, name=name)
20 if trainable:
21 self.parameters.append(weights)
22 return weights
23 def get_biases(self, dim_out, name, trainable=True):
24 shape = (dim_out, 1)
25 initialBiases = tf.constant_initializer(np.zeros(shape))
26 biases = tf.get_variable(
27 initializer=initialBiases, shape=shape, trainable=True, name=name)
28 if trainable:
29 self.parameters.append(biases)
30 return biases
31 @staticmethod
32 def truncated_normal(shape, stddev, mean=0.):
33 rand_init = np.random.normal(loc=mean, scale=stddev, size=shape)
34 inf_mask = rand_init < (mean - 2 * stddev)
35 rand_init = rand_init * \
36 np.abs(1 - inf_mask) + inf_mask * (mean - 2 * stddev)
37 sup_mask = rand_init > (mean + 2 * stddev)
38 rand_init = rand_init * \
39 np.abs(1 - sup_mask) + sup_mask * (mean + 2 * stddev)
40 return rand_init

@staticmethod

静态方法,类可以不用实例化就可以调用该方法,当然也可以实例化后调用。

所以要注意这里前面几个函数用到的self.truncated_normal()并不是一开始我以为的tf.truncated_normal()这个正态分布函数(我就奇怪为什么是self.而不是tf.,名字一样的0.0)。

那么这个函数传入参数为shape和stddev,形状和标准差。返回一个形状为shape的截断正态分布数组。

其余函数,get_weights是得到shape=(dim_out, dim_in)的截断正太分布权重,get_4Dweights是得到shape=(filter_height, filter_width, in_channels, out_channels)的截断正态分布权重,get_biases是得到shape=(dim_out, 1)的初始零向量偏置。

2. LSTMCell类

 class LSTMCell(TensorFlowTrainable):
def __init__(self, num_units, **kwargs):
super(LSTMCell, self).__init__()
self._num_units = num_units # 单元的个数
self.w_i = self.get_weights(
dim_in=2 * self._num_units, dim_out=self._num_units, name="w_i") # 输入门权重
self.w_f = self.get_weights(dim_in=2 * self._num_units, dim_out=self._num_units, name="w_f") # 忘记门权重
self.w_o = self.get_weights(dim_in=2 * self._num_units, dim_out=self._num_units, name="w_o") # 输出门权重
self.w_c = self.get_weights(dim_in=2 * self._num_units, dim_out=self._num_units, name="w_c") # 数据输入权重
self.b_i = self.get_biases(dim_out=self._num_units, name="b_i") # 输入门偏重
self.b_f = self.get_biases(dim_out=self._num_units, name="b_f") # 忘记门偏重
self.b_o = self.get_biases(dim_out=self._num_units, name="b_o") # 输出门偏重
self.b_c = self.get_biases(dim_out=self._num_units, name="b_c") # 数据输入偏重
self.c = [self.get_biases(dim_out=self._num_units, name="c", trainable=False)] # 记忆细胞状态偏重
def initialize_something(self, input):
# 对输入做一定的变换,包括转置、展开、扩展为度等,并把数值初始化为1
self.batch_size_vector = 1 + 0 * tf.expand_dims(tf.unstack(tf.transpose(input, [1, 0]))[0], 0)
# 初始化
self.h = [self.get_biases(dim_out=self._num_units, name="h", trainable=False) * self.batch_size_vector] def process(self, input, **kwargs):
H = tf.concat([tf.transpose(input, perm=[1, 0]),self.h[-1]], 0) # 将输入数据与上一时刻的记忆信息整合成一个新的输入
i = tf.sigmoid(x=tf.add(tf.matmul(self.w_i, H), self.b_i)) # 经过输入门后的数据
f = tf.sigmoid(x=tf.add(tf.matmul(self.w_f, H), self.b_f)) # 经过忘记门后的数据
o = tf.sigmoid(x=tf.add(tf.matmul(self.w_o, H), self.b_o)) # 经过输出门后的数据
c = f * self.c[-1] + i * tf.tanh(x=tf.add(tf.matmul(self.w_c, H), self.b_c))
# 原代码:h = o * tf.tanh(x=self.c[-1])
h = o * tf.tanh(x=self.c[-1])
self.c.append(c)
self.h.append(h) @property
def features(self):
return self.h[-1] # 将最后一个的向量输出

tf.transpose(input, [dimension_1, dimenaion_2,..,dimension_n]): 这里[1, 0]就是把第0,1维交换位置了。

tf.stack()这是一个矩阵拼接的函数,tf.unstack()则是一个矩阵分解的函数.

stack把两个矩阵按某个轴拼接起来,与tf.concat有所区分。

如拼接两个shape=(4, 3)的矩阵:

concat拼接axis=0后的矩阵是shape=(8, 3),拼接axis=1后,shape=(4,6)

stack拼接axis=0后的矩阵是shape=(2, 4, 3),拼接axis=1后的矩阵是shape=(4, 2, 3),拼接axis=0后的矩阵是shape=(4, 3, 1),

input.shape=(m, n)

H.shape=(2n, m)

i.shape=(n, m)

c.shape=(n, m)

h.shape=(n, m)

@property   装饰器

用装饰器函数把 get/set 方法“装饰”成属性调用:
 class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def get_score(self):
return self.__score
def set_score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score

- >

 class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score

详见@property装饰器

python super:

Python: 你不知道的 super


小结


  • 事实上,super 和父类没有实质性的关联。
  • super(cls, inst) 获得的是 cls 在 inst 的 MRO 列表中的下一个类。

ATTENTION NETWORK分析的更多相关文章

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

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

  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. Residual Attention Network for Image Classification(CVPR 2017)详解

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

  6. 5、AFM(Attention+FM)-----Attentional Factorization Machines:Learning the Weight of Feature Interactions via Attention Network

    1.摘要: 提出一个Attentional FM,Attention模型+因子分解机,其通过Attention学习到特征交叉的权重.因为很显然不是所有的二阶特征交互的重要性都是一样的,如何通过机器自动 ...

  7. 《Graph Attention Network》阅读笔记

    基本信息 论文题目:GRAPH ATTENTION NETWORKS 时间:2018 期刊:ICLR 主要动机 探讨图谱(Graph)作为输入的情况下如何用深度学习完成分类.预测等问题:通过堆叠这种层 ...

  8. Keras实现Hierarchical Attention Network时的一些坑

    Reshape 对于的张量x,x.shape=(a, b, c, d)的情况 若调用keras.layer.Reshape(target_shape=(-1, c, d)), 处理后的张量形状为(?, ...

  9. graph attention network(ICLR2018)官方代码详解(tensorflow)-稀疏矩阵版

    论文地址:https://arxiv.org/abs/1710.10903 代码地址: https://github.com/Diego999/pyGAT 之前非稀疏矩阵版的解读:https://ww ...

随机推荐

  1. 12.Android-SQLiteOpenHelper使用

    1.SQLite介绍 SQLite,是一款轻型的数据库,它的优缺点有如下: 轻量级,适合嵌入式设备,并且本身不依赖第三方的软件,使用它也不需要“安装”. 并发(包括多进程和多线程)读写方面的性能不太理 ...

  2. 配置IDEA默认作者@author

    IDEA安装目录下,使用文本编辑器打开~/bin/idea64.exe.vmoptions文件 在最后添加:-Duser.name=Your name 保存重启IDEA,Done

  3. 【PCIE-4】---PCIE中部分概念或问题总结(很基础很重要)

    前面三小节,介绍了PCIE的基本知识和概念,以及扫描流程.在不求甚解的情况下,我想各位小伙伴应该对PCIE有了个宏观的认识,OK,那么本章我们在之前的基础上,再单独把一些概念和更深层次的问题摘出来具体 ...

  4. 重载运算符-operator

    先看段代码: struct node { friend bool operator< (node n1, node n2){ // 优先取最小的,它与下面的 // 是等价的 return n1. ...

  5. TCP/IP协议与HTTP协议(一)

    1.什么是TCP/IP  如果要了解一个人,可以从他归属的集体聊起来.我们的HTTP协议就属于TCP/IP协议家族中的一员,了解HTTP协议再整个网络流程中的地位,也能更加充分的理解HTTP协议. 要 ...

  6. isStatic:检测数据是不是除了symbol外的原始数据

    function isStatic(value) { return( typeof value === 'string' || typeof value === 'number' || typeof ...

  7. Activiti 规则任务(businessRuleTask)

    Activiti 规则任务(businessRuleTask) 作者:Jesai 目前国内研究Activiti规则任务businessRuleTask)的文章在网上应该不超出3篇 小觑夜漫酒作伴,破晓 ...

  8. ORM _meta

    import os if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'XadminDemon.se ...

  9. Java入门 - 高级教程 - 04.序列化

    原文地址:http://www.work100.net/training/java-serialization.html 更多教程:光束云 - 免费课程 序列化 序号 文内章节 视频 1 概述 2 序 ...

  10. Beat our dice game and get the flag 击败我们的骰子游戏拿到旗子

    文件名:ebCTF-Teaser-BIN100-Dice.exe 话不多说 用PEID一看没壳 拖进OD 让我们摇出31337这五个数字才能拿到正确的flag cmp dword ptr ss:[eb ...