GraphSAGE 代码解析(二) - layers.py
原创文章~转载请注明出处哦。其他部分内容参见以下链接~
GraphSAGE 代码解析(一) - unsupervised_train.py
GraphSAGE 代码解析(三) - aggregators.py
GraphSAGE 代码解析(四) - models.py
1 # global unique layer ID dictionary for layer name assignment
2 _LAYER_UIDS = {}
3
4 def get_layer_uid(layer_name=''):
5 """Helper function, assigns unique layer IDs."""
6 if layer_name not in _LAYER_UIDS:
7 _LAYER_UIDS[layer_name] = 1
8 return 1
9 else:
10 _LAYER_UIDS[layer_name] += 1
11 return _LAYER_UIDS[layer_name]
这里_LAYER_UIDS = {} 是记录layer及其出现次数的字典。
在 get_layer_uid()函数中,若layer_name从未出现过,如今出现了,则将_LAYER_UIDS[layer_name]设为1;否则累加。
作用: 在class Layer中,当未赋variable scope的name时,通过实例化Layer的次数来标定不同的layer_id.
例子:简化一下class Layer可以看出:
class Layer():
def __init__(self):
layer = self.__class__.__name__
name = layer + '_' + str(get_layer_uid(layer))
print(name) layer1 = Layer()
layer2 = Layer() # Output:
# Layer_1
# Layer_2
2. class Layer
class Layer主要定义基本的层的API。
class Layer(object):
"""Base layer class. Defines basic API for all layer objects.
Implementation inspired by keras (http://keras.io).
# Properties
name: String, defines the variable scope of the layer.
logging: Boolean, switches Tensorflow histogram logging on/off # Methods
_call(inputs): Defines computation graph of layer
(i.e. takes input, returns output)
__call__(inputs): Wrapper for _call()
_log_vars(): Log all variables
""" def __init__(self, **kwargs):
allowed_kwargs = {'name', 'logging', 'model_size'}
for kwarg in kwargs.keys():
assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg
name = kwargs.get('name')
if not name:
layer = self.__class__.__name__.lower() # "layer"
name = layer + '_' + str(get_layer_uid(layer))
self.name = name
self.vars = {}
logging = kwargs.get('logging', False)
self.logging = logging
self.sparse_inputs = False def _call(self, inputs):
return inputs def __call__(self, inputs):
with tf.name_scope(self.name):
if self.logging and not self.sparse_inputs:
tf.summary.histogram(self.name + '/inputs', inputs)
outputs = self._call(inputs)
if self.logging:
tf.summary.histogram(self.name + '/outputs', outputs)
return outputs def _log_vars(self):
for var in self.vars:
tf.summary.histogram(self.name + '/vars/' + var, self.vars[var])
方法:
__init__(): 获取传入的name, logging, model_size参数。初始化实例变量name, vars{}, logging, sparse_inputs
_call(inputs): 定义层的计算图:获取input, 返回output.
__call__(inputs): 相当于_call()的装饰器,在实现列_call()基本功能后,丰富了其功能,这里主要通过tf.summary.histogram() 可以查看inputs与outputs分布情况的直方图。
_log_vars(): 记录所有变量。实现时主要将vars中的各个变量以直方图形式显示。
3. class Dense
Dense layer主要用于实现全连接层的基本功能。即为了最终得到 Relu(Wx + b)。
__init__(): 用于获取初始化成员变量。其中num_features_nonzero和featureless的作用目前还不清楚。
_call(): 用于实现并且返回Relu(Wx + b)
class Dense(Layer):
"""Dense layer.""" def __init__(self, input_dim, output_dim, dropout=0.,
act=tf.nn.relu, placeholders=None, bias=True, featureless=False,
sparse_inputs=False, **kwargs):
super(Dense, self).__init__(**kwargs) self.dropout = dropout self.act = act
self.featureless = featureless
self.bias = bias
self.input_dim = input_dim
self.output_dim = output_dim # helper variable for sparse dropout
self.sparse_inputs = sparse_inputs
if sparse_inputs:
self.num_features_nonzero = placeholders['num_features_nonzero'] with tf.variable_scope(self.name + '_vars'):
self.vars['weights'] = tf.get_variable('weights', shape=(input_dim, output_dim),
dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(),
regularizer=tf.contrib.layers.l2_regularizer(FLAGS.weight_decay))
if self.bias:
self.vars['bias'] = zeros([output_dim], name='bias') if self.logging:
self._log_vars() def _call(self, inputs):
x = inputs
x = tf.nn.dropout(x, 1 - self.dropout) # transform
output = tf.matmul(x, self.vars['weights']) # bias
if self.bias:
output += self.vars['bias'] return self.act(output)
GraphSAGE 代码解析(二) - layers.py的更多相关文章
- GraphSAGE 代码解析(四) - models.py
原创文章-转载请注明出处哦.其他部分内容参见以下链接- GraphSAGE 代码解析(一) - unsupervised_train.py GraphSAGE 代码解析(二) - layers.py ...
- GraphSAGE 代码解析(三) - aggregators.py
原创文章-转载请注明出处哦.其他部分内容参见以下链接- GraphSAGE 代码解析(一) - unsupervised_train.py GraphSAGE 代码解析(二) - layers.py ...
- GraphSAGE 代码解析(一) - unsupervised_train.py
原创文章-转载请注明出处哦.其他部分内容参见以下链接- GraphSAGE 代码解析(二) - layers.py GraphSAGE 代码解析(三) - aggregators.py GraphSA ...
- java代码解析二维码
java代码解析二维码一般步骤 本文采用的是google的zxing技术进行解析二维码技术,解析二维码的一般步骤如下: 一.下载zxing-core的jar包: 二.创建一个BufferedImage ...
- GraphSAGE 代码解析 - minibatch.py
class EdgeMinibatchIterator """ This minibatch iterator iterates over batches of samp ...
- asp.net C#生成和解析二维码代码
类库文件我们在文件最后面下载 [ThoughtWorks.QRCode.dll 就是类库] 使用时需要增加: using ThoughtWorks.QRCode.Codec;using Thought ...
- JavaScript “跑马灯”抽奖活动代码解析与优化(二)
既然是要编写插件.那么叫做"插件"的东西肯定是具有的某些特征能够满足我们平时开发的需求或者是提高我们的开发效率.那么叫做插件的东西应该具有哪些基本特征呢?让我们来总结一下: 1.J ...
- 用 TensorFlow 实现 k-means 聚类代码解析
k-means 是聚类中比较简单的一种.用这个例子说一下感受一下 TensorFlow 的强大功能和语法. 一. TensorFlow 的安装 按照官网上的步骤一步一步来即可,我使用的是 virtua ...
- C#使用zxing,zbar,thoughtworkQRcode解析二维码,附源代码
最近做项目需要解析二维码图片,找了一大圈,发现没有人去整理下开源的几个库案例,花了点时间 做了zxing,zbar和thoughtworkqrcode解析二维码案例,希望大家有帮助. zxing是谷歌 ...
随机推荐
- Android学习笔记_64_手机安全卫士知识点归纳(4) 流量统计 Log管理 混淆打包 加入广告 自动化测试 bug管理
android 其实就是linux 上面包装了一个java的框架. linux 系统下 所有的硬件,设备(网卡,显卡等) 都是以文件的方式来表示. 文件里面包含的有很多设备的状态信息. 所有的流量相关 ...
- EJB结合struts2创建项目、发布jboss服务器和访问、父类(BaseDaoImpl)的封装
一.环境搭建: 1.准备jboss服务器,将对应数据库的xml配置好放到jboss的发布目录下. <?xml version="1.0" encoding="UTF ...
- hadoop二次排序
import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException ...
- img的空白内容如何处理
给img加一个 vertical-align: bottom;
- java交换两个值的三种方法 经典
1.中间变量(在开发中常用) int c=a; a=b; b=c; System.out.println("a的值: "+a+" b的值: "+b); 2.按位 ...
- oracle权限配置
系统权限管理:1.系统权限分类:DBA: 拥有全部特权,是系统最高权限,只有DBA才可以创建数据库结构. RESOURCE:拥有Resource权限的用户只可以创建实体,不可以创建数据库结构. CON ...
- oracle中lock和latch的用途
本文向各位阐述Oracle的Latch机制,Latch,用金山词霸翻译是门插栓,闭锁,专业术语叫锁存器,我开始接触时就不大明白为什么不写Lock,不都是锁吗?只是翻译不同而以?研究过后才知道两者有很大 ...
- mix-blend-mode 混合模式 background-blend-mode 背景混合模式 isolation:isolate 隔离
css3 mix-blend-mode 混合模式 该属性不仅可以作用于HTML,还可以作用于SVG 兼容性: IE 8~11 Edge 12~14 Firefox 41~47 chrome 45~51 ...
- 汇编:将指定的内存中连续N个字节填写成指定的内容
1.loop指令实现 ;=============================== ;循环程序设计 ;将制定内存中连续count个字节填写成指定内容(te) ;loop指令实现 DATAS SEG ...
- 字符编码 ASCII unicode UTF-8
字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节(b ...