在 TensorFlow 中,我可以通过两种方式初始化变量:
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) x = tf.Variable([-.3], tf.float32) b = tf.Variable([-.3], tf.float32) linear_model = W * x + b
global_variable_intializer()
变量声明后调用:import tensorflow as tf W = tf.Variable([.3], tf.float32) x = 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)
两者有什么区别?初始化变量的最佳方法是什么?
编辑
这是我正在运行的实际程序:
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]}))