我在python3上用张量流实现了“线性回归” 当我运行代码时,predicted_y太大。
我不知道是什么问题
请告诉我。
以下是有问题的代码
import tensorflow as tf
import numpy as np
class Model(object):
def __init__(self):
self.w = tf.Variable(0.2)
self.b = tf.Variable(0.1)
self.var_list = []
self.var_list.append(self.w)
self.var_list.append(self.b)
def __call__(self, x):
return self.w*x+self.b
def loss(self, predicted_y, target_y):
return tf.reduce_mean((predicted_y-target_y)**2)
def grad(self, x, target_y):
with tf.GradientTape() as tape:
tape.watch(self.var_list)
loss_value = self.loss(self(x), target_y)
return tape.gradient(loss_value, [self.w, self.b])
def optimizer(self):
opt = tf.keras.optimizers.SGD(learning_rate=0.01)
return opt
height = np.array([[120, 140, 160, 170, 180]])
weight = np.array([[40, 50, 60, 65, 75]])
model = Model()
model(height)
opt = model.optimizer()
for _ in range(10):
print(model(height))
grads = model.grad(height, weight)
opt.apply_gradients(zip(grads, [model.w, model.b]))