【发布时间】:2018-12-22 07:16:59
【问题描述】:
我正在使用 Tensorflow 探索线性回归。这是我来自this notebook的代码。
import tensorflow as tf
import numpy as np
learning_rate = 0.01
x_train = np.linspace(-1,1,101)
y_train = 2*x_train + np.random.randn(*x_train.shape) * 0.33
X = tf.placeholder("float")
Y = tf.placeholder("float")
def model(X, w):
return tf.multiply(X,w)
w = tf.Variable(0.0, name = "weights")
training_epochs = 100
y_model = model(X,w)
cost = tf.reduce_mean(tf.square(Y-y_model))
train_op = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for epoch in range(training_epochs):
for (x,y) in zip(x_train,y_train):
sess.run(train_op, feed_dict = {X:x, Y: y})
print(sess.run(w))
它试图最小化成本函数。根据这个问题的answers,我认为tf.reduce_mean() 会像np.mean() 一样工作。
但是,每次将一对(x,y) 馈送到train_op 时,w 的权重似乎不是根据 THE 对而是根据之前的所有对更新。
对此有何解释?这是否与与优化器一起工作有关?
【问题讨论】:
-
However, every time a pair of (x,y) is fed to the train_op, the weight w seems to update not according to THE pair but to all previous pairs.是什么意思 -
@UmangGupta 嗨!对我来说,代码的直觉是每次 sess.run(train_op, feed_dict = {X:x, Y: y}) 运行时, w 都会更新为关于那对 x,y 或 x_train[i], y_train[i] ,所以基本上我们应该得到斜率,y/x 代表 w 的值。跨度>
-
是的,你的理解还可以。但有一些警告。斜率 = dloss/dx,通常与 y/x 不同,它应该等于 w 的变化,而不是 w 的变化。
-
根据model(),最小化square(y-y_model)的w应该是 y/x,对吧?所以只是连接点 (x,y) 和 (0,0) 的线的斜率。
-
不,你对优化过程和梯度的理解是完全错误的。
标签: python tensorflow