我理解代码1 是使用tf.train.GradientDescentOptimizer
的线性回归的代码,属于TensorFlow库(黑匣子)。
代码2 是在没有GradientDescentOptimizer
的情况下执行相同操作的代码示例。
是没有黑匣子的代码。
我想在代码2中添加偏见(# hypothesis = X * W + b
)。在这种情况下,代码(渐变,下降,更新等)应该如何?
代码1
import tensorflow as tf
x_train = [1, 2, 3]
y_train = [1, 2, 3]
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
W = tf.Variable(5.)
b = tf.Variable(5.)
hypothesis = X * W + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))
learning_rate = 0.1
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
gvs = optimizer.compute_gradients(cost, [W, b])
apply_gradients = optimizer.apply_gradients(gvs)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(21):
gradient_val, cost_val, _ = sess.run(
[gvs, cost, apply_gradients], feed_dict={X: x_train, Y: y_train})
print("%3d Cost: %10s, W': %10s, W: %10s, b': %10s, b: %10s" %
(step, round(cost_val, 5),
round(gradient_val[0][0] * learning_rate, 5), round(gradient_val[0][1], 5),
round(gradient_val[1][0] * learning_rate, 5), round(gradient_val[1][1], 5)))
代码2
import tensorflow as tf
x_train = [1, 2, 3]
y_train = [1, 2, 3]
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
W = tf.Variable(5.)
# b = tf.Variable(5.) # Bias
hypothesis = X * W
# hypothesis = X * W + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X) * 2
descent = W - learning_rate * gradient
update = tf.assign(W, descent)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(W))
for step in range(21):
gradient_val, update_val, cost_val = sess.run(
[gradient, update, cost], feed_dict={X: x_train, Y: y_train})
print(step, gradient_val * learning_rate, update_val, cost_val)
答案 0 :(得分:1)
我已提到An Introduction to Gradient Descent and Linear Regression
代码2
MethodA: (classX)
Dim _repRunner As New ReportRunner()
_repRunner.Run
Process flow:
(start process) class(X)MethodA->class(f)MethodB->class(g)MethodC->class(g)MetodC->class(h)MethodD->class(i)MethodE->class(i)MethodF->(classX)MethodA (end proceess)