112、TensorFlow初始化变量

# 创建一个变量
# 最简单创建一个变量的方法就是调用 tf.get_variable function
import tensorflow as tf
# 下面创建了一个三维的张量大小是 [1,2,3]
# 这个变量会有初始值,并且和默认的数据类型是tf.float32
# 将会通过 tf.glorot_uniform_initializer 方法来进行初始化
my_variable = tf.get_variable("my_variable", [1, 2, 3])
#你可以通过tf.get_variable方法来进行初始化,指定初始值和数据类型
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3], dtype=tf.int32, initializer=tf.zeros_initializer)

# Tensorflow 提供了许多方便的初始化工具
# 或者你可以初始化一个变量的值从另一Tensor的值来得到
other_variable = tf.get_variable("other_variable", dtype=tf.int32, initializer=tf.constant([23, 42]))
#当从另一个Tensor来初始化这个Tensor的值的时候不能指定当前变量的shape
#因为会默认使用初始化Tensor的shape
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(my_variable))
    print(sess.run(my_int_variable))
    print(sess.run(other_variable))

下面是上面代码的输出值:

2018-02-17 10:36:31.319332: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
[[[ 1.04935646 -0.96311927 -0.97139096]
  [ 0.3751905  -0.123739    0.06329334]]]
[[[0 0 0]
  [0 0 0]]]
[23 42]

 

posted @ 2018-02-17 10:38  香港胖仔  阅读(221)  评论(0编辑  收藏  举报