python - 关于tensorflow中session的解释

标签 python tensorflow

考虑示例中的以下 tensorflow 代码:

import numpy as np
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x:x_train, y:y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss  = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

我没问题,直到最后的 for 循环。

我对 sess.run(train, {x:x_train, y:y_train} 部分到底发生了什么感到困惑。据我所知,它一直在传递 x = [1,2,3,4]y = [0,-1,-2,-3] 进行训练。

然后每个循环都会更新 W 和 b 吗?然后它继续传递相同的两个 xy 并且每次从 W 和 b 的最后一个版本迭代?

两个问题:

1) 更新在哪里发生或者是隐含在 sess.run 中? sess.run(train... 是否特别知道更新的 Wb 因为它们是变量?

2) 每次都传递相同的 x 和 y 可以吗? -- 只有当我对问题 1 的想法不正确时,这个问题才有意义。如果它每次都自动更新 W,b,那么它就完全有意义,我们继续前进,直到找到最合适的。但是,如果更新没有自动发生,那么我不确定...

最佳答案

Does each loop then update W and b?

是的。

It then keeps passing the same two x and y and every time iterates from the last version of W and b?

是的。

1) Where does the update happen or is that implicit in sess.run?

TensorFlow 管道的主要概念是 the computation graph .上面的所有代码只是它的初始化。是的,它看起来具有误导性:您编写的 Python 代码,但它不像 Python 那样工作。但没关系,因为它只是 Python API。所有魔法都发生在 Tensorflow 的 C++ 核心中。这个魔法的核心是计算图。尝试在官方手册中了解更多信息或在评论中询问我。

或者更简短:是的,所有更新都是隐式进行的。

Does sess.run(train... know specifically to updated W and b because those are variables?

是的。

关于python - 关于tensorflow中session的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42712340/

相关文章:

python - 完成当前迭代后,如何结束带有套接字操作的无限循环?

python - 导入错误 : DLL load failed importing spacy

python - 在 Bokeh 1.4.0 中使用 box_select 工具“隐藏”而不是 'mute' 字形

python - 如果 Edge TPU 编译器仅支持 3 个暗淡张量,如何实现 conv2d 层?

windows - 低于3.0计算能力的GPU上的Keras?

python - 如何在 Python 的一行中将多个值添加到列表中?

python - 使用 Python 从上下文中自动选择标签

python - 在基础 Tensorflow 2.0 中运行简单回归

python - 在 keras 中加载模型后的不同预测

python - Tensorflow 2 Keras 嵌套模型子类化 - 总参数为零