如何在tensorflow访问一个单独的函数创建的代码兴趣
问题描述:
行变量优化之后是多个哈希(#)符号如何在tensorflow访问一个单独的函数创建的代码兴趣
为了理解的目的我运行在tensorflow简单线性回归。使用的代码IM是:
def generate_dataset():
#y = 2x+e where is the normally distributed error
x_batch = np.linspace(-1,1,101)
y_batch = 2*x_batch +np.random.random(*x_batch.shape)*0.3
return x_batch, y_batch
def linear_regression(): ##################
x = tf.placeholder(tf.float32, shape = (None,), name = 'x')
y = tf.placeholder(tf.float32, shape = (None,), name = 'y')
with tf.variable_scope('lreg') as scope: ################
w = tf.Variable(np.random.normal()) ##################
y_pred = tf.multiply(w,x)
loss = tf.reduce_mean(tf.square(y_pred - y))
return x,y, y_pred, loss
def run():
x_batch, y_batch = generate_dataset()
x, y, y_pred, loss = linear_regression()
optimizer = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
feed_dict = {x: x_batch, y: y_batch}
for _ in range(30):
loss_val, _ = session.run([loss, optimizer], feed_dict)
print('loss:', loss_val.mean())
y_pred_batch = session.run(y_pred, {x:x_batch})
print(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)) ############
print(session.run(fetches = [w])) #############
run()
我不能似乎能够获取变量(它实际上是一个运算?)的值“W”与取回调用任一“W”或“LREG/w',如果我理解正确的是由于'w'在linear_regression()中定义的事实,并且它不借助其名称空间来运行()。但是,我可以通过对其变量名'lreg/vairable:0'的访问来访问'w'。优化器工作得很好并且更新被完美应用
优化器如何访问'w'并应用更新,如果您能够让我深入了解'w'如何在linear_regression( )并运行()
答
您创建的每个操作和变量都是张量流graph中的一个节点。当你没有明确地创建一个图,就像你的情况一样,那么就会使用一个默认图。
此行将w添加到默认图形。
w = tf.Variable(np.random.normal())
此行访问图以进行计算
loss_val, _ = session.run([loss, optimizer], feed_dict)
您可以检查图这样
tf.get_default_graph().as_graph_def()
非常感谢你的反应。我有一个后续问题:为什么从run()运行时抛出一个错误print(session.run(fetches = [w]))? NameError:名称'w'未定义。想要提醒你print(session.run(fetches = ['lreg/variable:0'])取得'w'的值 – Nitin
你必须保持python变量和tensorflow变量分离在你的脑海中。 Tensorflow图有一个名为w的变量,并不意味着python在当前范围内有一个名为w的变量。 – Aaron