教程: https://www.bilibili.com/video/BV1Y7411d7Ys?p=2&vd_source=715b347a0d6cb8aa3822e5a102f366fe
数据集:
x
d
a
t
a
=
[
1.0
,
2.0
,
3.0
]
y
d
a
t
a
=
[
2.0
,
4.0
,
6.0
]
x_{data} = [1.0, 2.0, 3.0] \\y_{data} = [2.0, 4.0, 6.0]
xdata=[1.0,2.0,3.0]ydata=[2.0,4.0,6.0]
参数初始值:
w
1
=
1.0
w
2
=
1.0
b
=
1.0
w_1=1.0\\w_2=1.0\\b=1.0
w1=1.0w2=1.0b=1.0
模型:
y
=
w
1
∗
x
2
+
w
2
∗
x
+
b
y = w_1*x^2+w_2*x+b
y=w1∗x2+w2∗x+b
import torch
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
w1 = torch.Tensor([1.0])
w1.requires_grad = True
w2 = torch.Tensor([1.0])
w2.requires_grad = True
b = torch.Tensor([1.0])
b.requires_grad = True
epoch_p = []
loss_p = []
def forward(x):
return w1 * x ** 2 + w2 * x + b
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
for epoch in range(100):
for x, y in zip(x_data, y_data):
l = loss(x, y)
l.backward()
print('\tgrad:', x, y, w1.grad.item(), w2.grad.item(), b.grad.item())
w1.data = w1.data - 0.01 * w1.grad.data
w2.data = w2.data - 0.01 * w2.grad.data
b.data = b.data - 0.01 * b.grad.data
w1.grad.data.zero_()
w2.grad.data.zero_()
b.grad.data.zero_()
loss_p.append(l.item())
epoch_p.append(epoch)
print('Epoch:', epoch, l.item())
print("predict(aftertraining)",4,forward(4).item())
plt.figure()
plt.plot(epoch_p, loss_p, c = 'b')
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.show()