1 python machine-learning tensorflow
import tensorflow as tf
import numpy as np
#date generation
x_data = np.float32(np.random.rand(2, 100))
y_data = np.dot([0.1, 0.2], x_data) + 0.3
#linear model
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
#minimize variance
loss = tf.reduce_sum(tf.square(y - y_data)) #why I cannot use sum here
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
#initialization
init = tf.global_variables_initializer()
#graph initialization
sess = tf.Session()
sess.run(init)
#train network
for step in range(201):
sess.run(train)
#if step % 20 == 0:
print(step, sess.run(W), sess.run(b), sess.run(loss))
Run Code Online (Sandbox Code Playgroud)
嗨,我在使用 tensorflow 实现玩具模型时遇到了一个问题。当我使用tf.reduce_sum()函数作为损失函数时,优化器未能收敛。事实上,损失变得越来越大。但是当我将损失函数从tf.reduce_sum()更改为tf.reduce_mean() 时,优化器成功运行。任何人都可以说出为什么tf.reduce_sum()不适用于这个模型,但tf.reduce_mean()呢?
一次对所有样本求和的损失大于平均损失。
例如,让我们假设我们想要的 y_data = [1.2, 3.2, 2.4] 和预测的 y = [1, 3, 3]
然后通过以下几行:
tf.reduce_sum(tf.square(y - y_data))
Run Code Online (Sandbox Code Playgroud)
损失将变成:
0.04 + 0.04 + 0.36 = 0.44
相反,如果您使用 reduce 意味着相同的预测将导致更低的损失,在这种情况下
0.44/3 = 0.14666
因此,当您使用 reduce_sum 跳过可能的局部最小值时,您的梯度和参数更新也会更大。
此外,优化器中的学习率是每个示例的损失,如果您想在批处理中获得相同的效果,您需要将学习率除以批量大小以成功训练模型或使用 reduce_mean 来训练模型。
| 归档时间: |
|
| 查看次数: |
1684 次 |
| 最近记录: |