(一)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 变量列表

序号 参数 描述
1 value 输出类型的值
2 dtype 结果张量的类型
3 shape 可选张量的形状
4 name 张量名称
5 verify_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 参数列表

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

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: 
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 参数功能

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

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 参数功能

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

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

第n个数字 描述
1 3表示滑动窗口宽
2 3表示滑动窗口高
3 3表示当前图像深度
4 16表示卷积计算后下一层网络输入图像的深度

6 rnn_cell

6.1 MultiRNNCell

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

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

你可能感兴趣的:(#,TensorFlow1.x)