P41原书的代码是低版本TensorFlow的,为适应高版本的TensorFlow,代码修改为如下:
解决办法:因为上述代码写法是TensorFlow旧版本的写法,将Line6 和Line10 改如下如下可以实现代码的正常运行:
v = tf.get_variable("v",initializer=tf.zeros_initializer()(shape = [1]))
v = tf.get_variable( "v",initializer=tf.ones_initializer()(shape = [1]))
明显有一个更新提示,表示该初始化的语句也需要进行更新:tf.initialize_all_variables().run() 变成 tf.global_variables_initializer().run()
更改之后最终代码为:
import tensorflow as tf
g1=tf.Graph()
with g1.as_default():
v = tf.get_variable("v", initializer=tf.zeros_initializer()(shape=[1]))
g2=tf.Graph()
with g2.as_default():
v = tf.get_variable("v", initializer=tf.ones_initializer()(shape=[1]))
with tf.Session(graph=g1) as sess:
tf.global_variables_initializer().run()
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))
with tf.Session(graph=g2) as sess:
tf.global_variables_initializer().run()
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))