在TensorFlow中初始化变量的最佳方法是什么?

Pan*_*ami 5 python tensorflow tensor

在Tensorflow中,我可以用两种方式初始化变量:

  1. global_variable_intializer在声明变量之前调用:

    import tensorflow as tf
    
    # Initialize the global variable and session
    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)
    
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    linear_model = W * x + b
    
    Run Code Online (Sandbox Code Playgroud)
  2. global_variable_intializer声明变量后调用:

    import tensorflow as tf
    
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    linear_model = W * x + b 
    
    # Initialize the global variable and session
    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)
    
    Run Code Online (Sandbox Code Playgroud)

两者有什么区别?哪个是初始化变量的最佳方法?

编辑

这是我正在运行的实际程序:

import tensorflow as tf

# Initialize the global variable and session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)



linear_model = W * x + b

square_delta = tf.square(linear_model - y)

loss = tf.reduce_sum(square_delta)

fixW = tf.assign(W, [-1.])
fixb = tf.assign(b, [1.])

sess.run([fixW, fixb])

print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
Run Code Online (Sandbox Code Playgroud)

Pie*_*lla 5

在案例1中,变量未初始化,如果您尝试

sess.run(linear_model)
Run Code Online (Sandbox Code Playgroud)

它应该给你一些错误(我的编译器上的FailedPreconditionError).

案例2是工作案例.

命令

tf.global_variables_initializer()
Run Code Online (Sandbox Code Playgroud)

应在创建所有变量后调用,否则将引发相同的错误.

据我所知,每次调用tf.Variable时,与变量相关的节点都会添加到图形中.这些是以下内容:

Variable/initial_value
Variable
Variable/Assign
Variable/read
Run Code Online (Sandbox Code Playgroud)

(使用该命令获取到目前为止构造的节点

for n in tf.get_default_graph().as_graph_def().node:
    print n.name
Run Code Online (Sandbox Code Playgroud)

)

变量本身在您在变量/分配节点的会话中运行之前没有任何价值.

命令

init = tf.global_variables_initializer() 
Run Code Online (Sandbox Code Playgroud)

创建一个包含到目前为止构造的所有变量的所有赋值节点的单个节点,并将其与python变量'init'关联,以便在执行该行时

sess.run(init)
Run Code Online (Sandbox Code Playgroud)

所有变量都获得初始值.