【发布时间】:2020-03-24 12:13:03
【问题描述】:
我正在尝试为多元线性回归构建一个小的教育示例,但是 LOSS 一直在增加,直到它爆炸而不是变小,知道吗?
import tensorflow as tf
tf.__version__
import numpy as np
data = np.array(
[
[100,35,35,12,0.32],
[101,46,35,21,0.34],
[130,56,46,3412,12.42],
[131,58,48,3542,13.43]
]
)
x = data[:,1:-1]
y_target = data[:,-1]
def loss_function(y, pred):
return tf.reduce_mean(tf.square(y - pred))
def train(b, w, x, y, lr=0.012):
with tf.GradientTape() as t:
current_loss = loss_function(y, linear_model(x))
lr_weight, lr_bias = t.gradient(current_loss, [w, b])
w.assign_sub(lr * lr_weight)
b.assign_sub(lr * lr_bias)
epochs = 80
for epoch_count in range(epochs):
real_loss = loss_function(y_target, linear_model(x))
train(b, w, x, y_target, lr=0.12)
print(f"Epoch count {epoch_count}: Loss value: {real_loss.numpy()}")
即使我使用“正确”值(通过 scikit-learn 回归器发现)初始化权重也会发生这种情况
w = tf.Variable([-1.76770250e-04,3.46688912e-01,2.43827475e-03],dtype=tf.float64)
b = tf.Variable(-11.837184241807234,dtype=tf.float64)
【问题讨论】:
-
如果您使用 TF 优化器而不是手动分配会发生什么?
-
我认为在具有 Eager Execution 的 TF2 中这是不可能的,文档说我必须使用 GradientTape。万一我错了,你碰巧有一个代码sn-p吗? tf.train.GradientDescentOptimizer 在 TF2 中不可用
-
你绝对可以在 TF2 中使用优化器。我将在答案部分发布代码sn-p。
-
非常感谢!这行得通。仍然不清楚为什么它不能手动工作,但至少我现在有一个工作示例
-
那么,当您将其更改为 TF 优化器时,爆炸梯度问题是否消失了?
标签: tensorflow linear-regression linear-algebra gradienttape