0
首先當線性模型發散,道歉,如果我做一個愚蠢的錯誤 - 這是我第一次tensorflow計劃之一。爲了我的辯護 - 我已經搜索了這個主題,並沒有找到任何合理的解釋。Tensorflow:添加例子來訓練矢量
代碼
該代碼適於從Getting Started guide。它採用的梯度來訓練簡單的線性模型:
import tensorflow as tf
# Define a linear model. The initial values are wrong (W=0.3, b=0.3),
# and should converge to (W=-1, b=1).
# Variables
W = tf.Variable([.3], tf.float32)
b = tf.Variable([.3], tf.float32)
x = tf.placeholder(tf.float32)
# Linear model
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# Loss function and optimizer
square_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(square_deltas)
init = tf.global_variables_initializer()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# Tensorflow session
sess = tf.Session()
sess.run(init)
# Train!
for i in range(100):
sess.run(train, {x:[1, 2, 3, 4, 5, 6],
y:[0, -1, -2, -3, -4, -5]})
print(sess.run([W, b]))
結果
當模型被訓練爲100次,其結果是:
[array([-0.97550046], dtype=float32), array([ 0.89605999], dtype=float32)]
當模型被訓練1000次,其結果是越接近(-1,1),如所預期:
[array([-0.9999997], dtype=float32), array([ 0.99999875], dtype=float32)]
問題
當添加另一示例的訓練樣本:
sess.run(train, {x:[1, 2, 3, 4, 5, 6, 7],
y:[0, -1, -2, -3, -4, -5, -6]})
的結果(100本1000次迭代,分別地)發散:
[array([ 1.65981654e+28], dtype=float32), array([ 3.35185014e+27], dtype=float32)]
[array([ nan], dtype=float32), array([ nan], dtype=float32)]
爲什麼添加另一示例失敗模型?
改變學習率0.001,也reduce_sum應該reduce_mean(否則學習速率的變化意味着當你添加更多的樣本) – lejlot