python - Tensorflow 线性回归不收敛到正确值
问题描述
我有一个包含 2 列、一个输入和输出列的 csv 数据集,当我使用 Excel 查找趋势线时,我得到:
y = -0.4571x + 0.9011
当我运行以下代码 w 并根据我选择的学习率和批量大小收敛到不同的值时。我玩过不同的价值观,没有任何运气。也许我错过了一些东西?
成本似乎也没有改变。
learningRate = 0.001
epochs = 2000
batchSize = 20
df = pd.read_csv("C:\\Users\\Brian\\Desktop\\data.csv")
X = df[df.columns[0]].values
Y = df[df.columns[1]].values
def getBatch(batchSize, inputs, outputs):
idx = np.arange(0,len(inputs))
np.random.shuffle(idx)
idx = idx[:batchSize]
xBatch = [inputs[i] for i in idx]
yBatch = [outputs[i] for i in idx]
xBatch = np.reshape(xBatch, (batchSize,1))
return np.asarray(xBatch), np.asarray(yBatch)
w = tf.Variable(0.0, tf.float32)
b = tf.Variable(0.0, tf.float32)
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
prediction = tf.add(tf.multiply(x,w), b)
cost = tf.reduce_sum(tf.square(prediction-y))
optimizer = tf.train.GradientDescentOptimizer(learningRate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(epochs):
xBatch, yBatch = getBatch(batchSize,X,Y)
#for (trainX, trainY) in zip(xBatch,yBatch):
sess.run(optimizer, feed_dict={x: xBatch, y: yBatch})
if(epoch+1) % 50 == 0:
c = sess.run(cost, feed_dict={x: X, y: Y})
print("Epoch:", (epoch+1), "cost=", "{:.4f}".format(c), "w=", sess.run(w), "b=", sess.run(b))
print("Optimization Finished")
trainingCost = sess.run(cost, feed_dict={x: X, y:Y})
print("Training cost=", trainingCost, "w=", sess.run(w), "b=", sess.run(b))
解决方案
当我运行以下代码 w 并根据我选择的学习率和批量大小收敛到不同的值时。
因为,如果您运行sess.run(optimizer, feed_dict={x: xBatch, y: yBatch})
TensorFlow,则会执行以下操作。
w -= learningRate * dw
其中dw
是梯度下降优化器计算的值。
所以如果你改变learningRate
然后运行程序,你会得到不同的值w
。并w
影响dw
下dw
一个影响w
。所以很难预测w
如果你改变learningRate
.