一. 函数的作用
该函数的主要功能是声明一个变量,用于生成一个初始值为initial-value的变量,必须指定初始化值!!
(与tf.get_variable()的区别详见其他博客)
二. 函数的参数说明
1. 函数的整体结构如下:
tf.Variable(initial_value, trainable, collections, validate_shape, caching_device, name, variable_def, dtype,
expected_shape, import_scope, shape)
2. 函数中的各个参数解释如下:
- initial_value: 初始化变量值,默认值None,通常可以搭配tensorflow 随机生成函数,常见的生成函数如下:
随机生成函数:
tf.random_normal(shape, mean, stddev, dtype, seed, name)
tf.truncated_normal(shape, mean, stddev, dtype, seed, name)
tf.random_uniform(shape, minval, maxval, dtype, seed, name)
tf.random_gamma(shape, alpha, brta, dtype, seed, name)
固定生成函数:
tf.zeros(shape, dtype, name)
tf.ones(shape, dtype, name)
tf.fill(dims, value, name)
tf.constant(value, dtype, shape, name, verify_shape)
- trainable: 若为‘True’,则该变量为可训练变量,自动被加入GraphKeys.TRAINABLE_VARIABLES。
- coolections: 为一个集合列表的关键字,新变量将被添加到这个集合中,默认[GraphKeys.GLOBAL_VARIABLES]。
- validate_shape: 默认为True,表示该变量的形状不接受更改。
- caching_device: 可选设备字符串,描述应该缓存变量以供读取的位置。
- name: 定义该变量的名称,默认为“Variable”并自动获取。
- dtype: 定义该变量的数据类型,如果设置,则initial_value将转换为给定类型。
- expected_shape: 为TensorShape。如果设置,则initial_value应具有此形状。
- import_scope: 可选字符串。要添加到变量的名称范围。仅在从协议缓冲区初始化时使用。
- shape: 定义该变量的数据形状,若搭配tensorflow 随机生成函数使用,则该参数一般忽略
注:a. 各个参数的解释可以参考相关博客
b. 可以通过tf.all_variables()函数查看所有变量,通过tf.trinable_variable()函数查看可训练变量
三. 函数的使用
1. 采用tf.Variable()进行变量创建
#*******************************导入相关模块***********************************#
import tensorflow as tf
import numpy as np
#*******************************声明两个变量***********************************#
x1 = tf.Variable(tf.random_normal([2,3], mean=0, stddev=0.1), trainable=True, name='x1')
x2 = tf.Variable(tf.constant([1,2,3,4]))
#********************************创建会话*************************************#
with tf.Session() as sess:
#-------------------变量进行初始化
init_op = tf.global_variables_initializer()
sess.run( init_op )
#-------------------输出变量及名称
print( sess.run(x1) )
print( x1.op.name )
print( sess.run(x2) )
print( x2.op.name )
#--------------------模型的输出
[[-0.07220871 -0.01207301 0.10254947]
[ 0.11671194 0.02199386 -0.03869385]]
x1
[1 2 3 4]
Variable