import matplotlib.pyplot as plt
import torch
import numpy as np
x = torch.linspace(0,100,100).type(torch.FloatTensor)
rand = torch.randn(100)* 10
y = x + rand
x_train = x[ : -10]
x_test = x[-10 : ]
y_train = y[ : -10]
y_test = y[-10 : ]
a = torch.rand(1, requires_grad=True)
b = torch.rand(1, requires_grad=True)
learning_rate = 0.0001
"""对a,b进行迭代计算。"""
for i in range(1000):
predictons = a.expand_as(x_train) * x_train + b.expand_as(x_train)
loss = torch.mean((predictons - y_train) ** 2)
print('loss:', loss)
loss.backward()
a.data = a.data - learning_rate * a.grad
b.data = b.data - learning_rate * b.grad
a.grad.data.zero_()
b.grad.data.zero_()
x_data = x_train.data.numpy()
x_pred = x_test.data.numpy()
plt.figure(figsize = (10, 7))
plt.plot(x_data, y_train.data.numpy(), 'o')
plt.plot(x_pred, y_test.data.numpy(), 's')
x_data = np.r_[x_data, x_test.data.numpy()]
xplot = plt.plot(x_data, a.data.numpy() * x_data + b.data.numpy())
yplot = plt.plot(x_pred, a.data.numpy() * x_pred + b.data.numpy(), 'o')
plt.xlabel('X')
plt.ylabel('Y')
str1 = str(a.data.numpy()[0]) + 'x +' + str(b.data.numpy()[0])
plt.legend([xplot, yplot],['Data', str1])
plt.show()