0
我在學習tensorflow,並且修改了tensorflow在其網站上提供的線性迴歸代碼,可以進行二次迴歸。然而,與其在線性模型中減少損失一樣,損失會爆炸,我不知道爲什麼它會這樣做。Tensorflow問題
代碼,在蟒蛇2.7.12:
import tensorflow as tf
# Model parameters
A = tf.Variable([0], dtype=tf.float32)
B = tf.Variable([0], dtype=tf.float32)
C = tf.Variable([0], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
model = A*(x**2)+B*x+C
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [0, 1, 2, 3]
y_train = [0, 1, 4, 9]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(100):
sess.run(train, {x: x_train, y: y_train})
# evaluate training accuracy
curr_A, curr_B, curr_C, curr_loss = sess.run([A, B, C, loss], {x: x_train, y: y_train})
print("A: %s B: %s C: %s loss: %s"%(curr_A, curr_B, curr_C, curr_loss))
這裏是輸出:
A: [ -1.85999073e+10] B: [ -6.90063821e+09] C: [ -2.75790080e+09] loss: 4.55068e+22
我在做什麼錯?謝謝。
編輯:發佈錯誤的代碼第一
這可能是因爲你現在在錯誤的每個數據點而言過沖。這可能會導致本地最小值在每次迭代中不斷增加的數額。仔細看看tf.square(model - y),看看它是否按照您的預期工作可能會有好處。我的ML知識僅限於理論 - 特別是在TensorFlow方面 – Steve
@Steve大部分是正確的。你確實幫助我專注於此。我檢查了優化器,我傳入的值太大了。使用0.001允許函數收斂。 – Jeff