从 TF 会话中获取变量



我已经介绍了这个代码片段,这是一个使用梯度下降的非常简单的线性回归模型。

让我感到困惑的是最后一行final_slope , final_intercept = sess.run([m,b]),这是从会话中获取变量而不是再次运行会话的最佳方法吗?

我希望了解此声明如何在引擎盖下运作

我的代码:

import tensorflow as tf
import numpy as np
x_data = np.linspace(0,10,10) + np.random.uniform(-1.5,1.5,10)
y_label = np.linspace(0,10,10) + np.random.uniform(-1.5,1.5,10)
m = tf.Variable(0.29220241)
b = tf.Variable(0.84038402)
error = 0
for x,y in zip(x_data,y_label):
y_hat = m*x + b
error += (y-y_hat)**2 
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = optimizer.minimize(error)
init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
epochs = 1
for i in range(epochs):
sess.run(train)

# Fetch Back Results
final_slope , final_intercept = sess.run([m,b])

根据文档

a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
# 'fetches' can be a singleton
v = session.run(a)
# v is the numpy array [10, 20]
# 'fetches' can be a list.
v = session.run([a, b])
# v a Python list with 2 numpy arrays: the numpy array [10, 20] and the
# 1-D array [1.0, 2.0]
# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
MyData = collections.namedtuple('MyData', ['a', 'b'])
v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
# v is a dict with
# v['k1'] is a MyData namedtuple with 'a' the numpy array [10, 20] and
# 'b' the numpy array [1.0, 2.0]
# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
# [10, 20].

仍然没有得到再次运行会话以提取变量的有意义信息。 我想了解每次运行会话是否是获取变量的最佳情况,或者还有另一种更好更快的方法

这里的误解可以通过您使用短语"运行会话"来说明。 会话不是"运行"的。 会话"运行"一件事。 思考过程是,在会话中,计算图的某些部分运行,由您请求的特定节点决定。 因此,当您执行session.run([y_hat])时,我们的tensorflow会话(基本上,这只是能够进行任何计算的必要条件)"运行"计算张量y_hat所需的计算图部分。 在您的情况下,y_hat需要抓取几个变量的值,并进行一些张量乘法和加法。

如果你想要图中的其他张量,你也可以"运行"它们。 有时,某些张量是在通往其他张量的途中计算的。 例如,当我们计算(y-y_hat)**2时,y_hat是沿途计算的。 我们不必为每个计算图执行整个计算图,我们可以session.run([y_hat, (y-y_hat)**2]),并且y_hat(afaik)将只计算一次。

这里的关键见解是张量不会在运行之间存储。 因此,如果您调用session.run([y_hat]) ; session.run([(y-y_hat)**2]),那么导致y_hat的所有计算都必须执行两次。

希望这有所帮助。

最新更新