(一)Tensorflow函数解析:变量及会话

环境

  • 每篇10个函数
  • Tensorflow1.12.0
  • Ubuntu18.04
  • numpy1.15.4

1 tf.constant()

tf.constant(value, shape=None, dtype=none, name=‘Const’ ,verify_shape=False)

1.0 变量列表

序号参数描述
1value输出类型的值
2dtype结果张量的类型
3shape可选张量的形状
4name张量名称
5verify_shape布尔值,确定值的形状

1.2 例解

import tensorflow as tf 

a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
c = tf.constant([1, 2, 3, 4, 5, 6])
d = tf.constant([[1,2,3],[4,5,6]])
result = a + b
print(a)
print(result)
print(c.shape)
print(c.get_shape())
print(tf.shape(c))
print(d)
print(d.shape)
print(d.get_shape())
print(tf.shape(d))

with tf.Session() as sess:
	print(sess.run(result))
	print(a.eval())

【结果】

Tensor("a:0", shape=(2,), dtype=float32)
Tensor("add:0", shape=(2,), dtype=float32)
(6,)
(6,)
Tensor("Shape:0", shape=(1,), dtype=int32)
Tensor("Const_1:0", shape=(2, 3), dtype=int32)
(2, 3)
(2, 3)
Tensor("Shape_1:0", shape=(2,), dtype=int32)
Tensor("Shape:0", shape=(1,), dtype=int32)
[ 3.  5.]
[ 1.  2.]

【解读】

0.tf.constant参数说明:value表示给变量赋值,值可为数值或列表;shape为变量维度(行,列)。
1.tf.constant是一个计算,结果是一个张量,如print(a),结果为Tensor("a:0", shape=(2,), dtype=float32)。其中,a:0是属性名字,张量的唯一标识符。
2.张量的维度:c.shape=c.get_shape(),tf.shape(c)是c的整体结构。
3.维度shape(row, column)。d的shape,为(2, 3),2行3列。
4.tf.Session()执行定义的运算。sess.run运行计算,可通过tf.Tensor.eval函数获取张量的取值。如a.eval(),result.eval()。

2 Session()

2.1 初始化参数

__init__(
		target=' ',
		graph=None,
		config=None
)

2.2 参数列表

序号参数描述
1target连接的执行引擎
2graph载入的图结构
3configConfigProto协议状态配置会话

2.3 例解

2.3.1. 创建默认会话

  • Demo1
import tensorflow as tf
tf.reset_default_graph()

v1 = tf.Variable([250], name="v_1")

sess = tf.Session()
init_op =  tf.global_variables_initializer()
sess.run(init_op)
# 在这种模式下,不能使用eval(),因为没有注册session
# print("variable value: {}".format(sess(v1.eval())))
print("variable value: {}".format(sess.run(v1)))
sess.close()
  • Result
variable value: [250]
variable value: [250]
  • Demo2
import tensorflow as tf

v1 = tf.Variable(250, name="v_1")
with tf.Session() as sess:
    init_op =  tf.global_variables_initializer()
    sess.run(init_op)
    print("variable value: {}".format(v1.eval()))
    print("variable value: {}".format(sess.run(v1)))
  • Result
variable value: 250
variable value: 250
  • Analysis
    (1) 新建会话有两种默认方式,with结构或tf.Session(),然后关闭;
    (2) 获取张量值,有两种方法,eval()和直接运行run();

2.3.2 交互会话

import tensorflow as tf

sess = tf.InteractiveSession()
print(result.eval())
sess.close()

2.3.3. 上下文管理器会话

import tensorflow as tf
tf.reset_default_graph()
# 新建图
g = tf.Graph()
# 新图作为默认的图,构建图结构
with g.as_default():
    v1 = tf.Variable([250], name="v_1")

with tf.Session(graph=g) as sess:
    # 初始化变量
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print("variable tensor: {}".format(v1))
    print("variable name: {}".format(v1.name))
    print("variable value: {}".format(sess.run(v1)))
  • Result
variable tensor: <tf.Variable 'v_1:0' shape=(1,) dtype=int32_ref>
variable name: v_1:0
variable value: [250]

2.3.4 ConfigProto Protocol Buffer会话

import tensorflow as tf

config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)
sess1 = tf.InteractiveSession(config=config)
sess2 = tf.Session(config=config)

3 ConfigProto

  • ConfigProto(allow_soft_placement=True, log_device_placement=True)
1.ConfigProto可配置类似并行的线程数,GPU分配策略、运算超时时间等参数。
2.allow_soft_placement设为True,GPU上的运算可移植到CPU上,不会报错。
3.log_device_placement生产环境中,设置为False减少日志量。

4 tf.Variable

Tensorflow通过变量名称创建或获取变量。
tf.Variable()

4.1 初始化参数

__init__(
		initial_value=None,
		trainable=True,
		collections=None,
		validate_shape=True,
		caching_device=None,
		name=None,
		variable_def=None,
		dtype=None,
		expected_shape=None,
		import_scope=None,
		constraint=None,
		use_resource=None,
		synchronization=tf.VariableSynchronization.AUTO,
		aggregation=tf.VariableAggregation.NONE
)

4.2 参数功能

序号参数描述
1initial_value张量或python对象转换的张量,初始值,若没有指定形状,则validate_shape=False,若需要返回值,则需指定数据类型dtype
2trainable默认True,即该变量为可训练的变量,可以添加到图的集合中
3collections新建图中集合的键列表,新建的变量可添加到集合中
4validate_shape若为False,则可不指定数据形状,默认为True,需要指定数据形状
5caching_device选择处理变量的设备
6name变量名称,实际在计算图中的名称
7variable_defVariableDef协议状态,若不空,则从图中存在的变量重新建立变量,如载入模型过程中,新建图结构时定义的变量,即利用模型中的变量进行定义
8dtype变量类型,有int32, float32等
9expected_shape张量形状,若设置则将张量设置为该形状
10import_scope给变量添加命名空间,即将变量添加到命名空间中
11constraint优化器更新后应用与变量的可选投影函数
12use_resource是否使用源变量
13synchronization未使用
14aggregation未使用

5 tf.get_variable

5.1 初始化参数

tf.get_variable(
		name,
		shape,
		dtype=None,
		initializer=None,
		regularizer=None,
		trainable=True,
		collections=None,
		caching_device=None,
		partitioner=None,
		validate_shape=True,
		use_resource=None,
		custom_getter=None
		constraint=None,
		variable_def=None,
		synchronization=tf.VariableSynchronization.AUTO,
		aggregation=tf.VariableAggregation.NONE
)

5.2 参数功能

序号参数描述
1name新建或存在变量的名称,实际在计算图中的名称
2shape新建或存在变量的形状
3dtype新建或存在变量的形状,默认为float
4initializer初始化变量
5regularizer函数,将新建的变量结果添加到集合中
2trainable默认True,即该变量为可训练的变量,可以添加到图的集合中
3collections新建图中集合的键列表,新建的变量可添加到集合中
5caching_device选择处理变量的设备
4partitioner分割器,接受完全定义的张量形状和新建的变量类型
4validate_shape若为False,则可不指定数据形状,默认为True,需要指定数据形状
10use_resource是否使用源变量
12custom_getter作为第一个参数接受真正的getter,允许你重写内部get变量方法
13constraint优化器更新后应用与变量的可选投影函数
14synchronization未使用
15aggregation未使用

:shape在卷积神经网络中为4个列向量,如[3, 3, 3, 16]

第n个数字描述
13表示滑动窗口宽
23表示滑动窗口高
33表示当前图像深度
416表示卷积计算后下一层网络输入图像的深度

6 rnn_cell

6.1 MultiRNNCell

功能:创建一个由多个RNNCells按序列组成的RNN单元, 返回tensor或tensor列表.
警告:未来版本2.0中将会移除,使用tf.keras.layers.StackedRNNCells代替.

序号参数描述
1cellsRNNCells的列表将按照这个cells顺序组成
2state_is_tuple为True接受并返回的状态是n维的tuple,n=len(cells),若为False,状态都按照列连接

6.2 BasicLSTMCell

功能:基本LSTM循环神经网络单元.
基于:http://arxiv.org/abs/1409.2329
高级功能使用LSTMCell.

__init__(
		num_units,
		forget_bias=1.0,
		state_is_tuple=True,
		activation=None,
		name=None,
		variable_def=None,
		dtype=None,
		**kwargs
)
序号参数描述
1num_unitsint,在LSTM单元中的单元数量
2forget_biasfloat,遗忘门的偏置,从CudnnLSTM训练节点中载入时需要手动设为0.0
3state_is_tuple若为True,接受并返回c_state和m_state的2维tuple,若为False,则依据列排序
4activationstates中的激活函数,默认为tanh
5reuseboolean重复使用scope变量的标志位,True重复使用,False重复使用
6name新建或存在变量的名称,实际在计算图中的名称
7dtype默认的layer类型
8**kwargsdict,通用layer属性的关键词名称

6.3 LSTMCell

功能:LSTM循环神经网络单元.
未来2.0版本将使用tf.keras.layers.LSTMCell代替.

__init__(
		num_units,
		use_peepholes,
		cell_clip,
		initializer,
		num_proj,
		proj_clip,
		num_unit_shards,
		num_proj_shards,
		forget_bias=1.0,
		state_is_tuple=True,
		activation=None,
		name=None,
		variable_def=None,
		dtype=None,
		**kwargs
)
序号参数描述
1num_unitsint,在LSTM单元中的单元数量
2use_peepholesbool,设True启用diagonal/peephole连接
3cell_clip可选,float值,若在单元输出激活之前单元状态被该值截断
4initializer可选,用于权重和投影矩阵的初始值设定
5num_proj可选,投影矩阵的输出维度,若为None,则没有投影
6proj_clip可选,float值,若num_proj>0且pro_clip不为空,投影值在[-proj_clip,proj_clip]之间
7num_unit_shards将被variable_scope代替
8num_proj_shards将被variable_scope代替
9forget_biasfloat,遗忘门的偏置,从CudnnLSTM训练节点中载入时需要手动设为0.0
10state_is_tuple若为True,接受并返回c_state和m_state的2维tuple,若为False,则依据列排序
11activationstates中的激活函数,默认为tanh
12reuseboolean重复使用scope变量的标志位,True重复使用,False重复使用
13name新建或存在变量的名称,实际在计算图中的名称
14dtype默认的layer类型
15**kwargsdict,通用layer属性的关键词名称

[参考文献]
[1]https://tensorflow.google.cn/api_docs/python/tf/constant
[2]https://tensorflow.google.cn/api_docs/python/tf/Variable
[3]https://tensorflow.google.cn/api_docs/python/tf/get_variable
[4]https://tensorflow.google.cn/api_docs/python/tf/session
[5]https://www.tensorflow.org/versions/r1.13/api_docs/python/tf/nn/rnn_cell?hl=en


持续更新ing
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值