导入自动梯度运算包,主要用Variable这个类
from torch.autograd import Variable
import matplotlib.pyplot as plt
生成100个0—100间的数
x = Variable(torch.linspace(0, 100, 100).type(torch.FloatTensor))
生成100个正态分布随机数,均值为0,方差为10
rand = Variable(torch.randn(100)) * 10
y = x + rand
将Variable转换为数组,绘图
plt.plot(x.data.numpy(), y.data.numpy(),‘o’)
plt.xlabel(‘X’)
plt.ylabel(‘Y’)
plt.show()
找到一条直线,使得它到所有点 的距离都很小
设置拟合参数变量
a = Variable(torch.rand(1), requires_grad=True)
b = Variable(torch.rand(1), requires_grad=True)
print(‘Initial parameters:’, [a, b])
设置学习率
learning_rate =0.0001
for i in range(1000):
predictions = a.expand_as(x) * x + b.expand_as(x)