线性回归利用数理统计中的回归分析来确定两种或两种以上变量间相互依赖的定量关系,其表达式为:
y = w*x + b + e,
误差e服从均值0的正态分布。线性回归的损失函数是:
利用随机梯度下降法更新参数w和b来最小化损失函数,最终学得w和b的数值。
from __future__ import print_function
import torch as t
from matplotlib import pyplot as plt
from IPython import display
# 设置随机数种子,保证在不同计算机上运行时下面的输出一致
t.manual_seed(1000)
def get_fake_data(batch_size=8):
# 产生随机数据:y=x*2+3,加上了一些噪声
x = t.rand(batch_size, 1) * 20
y = x * 2 + (1 + t.randn(batch_size, 1)) * 3
return x, y
# 随机初始化参数
w = t.rand(1, 1)
b = t.zeros(1, 1)
lr = 0.001 # 学习率
for ii in range(20000):
x, y = get_fake_data()
# forward:计算loss
y_pred = x.mm(w) + b.expand_as(y)
loss = 0.5 * (y_pred - y) ** 2 # 均方误差
loss = loss.sum()
# backward:手动计算梯度
dloss = 1
dy_pred = dloss * (y_pred - y)
dw = x.t().mm(dy_pred)
db = dy_pred.sum()
# 更新参数
w.sub_(lr * dw)
b.sub_(lr * db)
if ii%1000 ==0:
# 画图
display.clear_output(wait=True)
x = t.arange(0, 20).view(-1, 1)
y = x.mm(w.long()) + b.expand_as(x)
plt.plot(x.numpy(), y.numpy()) # predicted
x2, y2 = get_fake_data(batch_size=20)
plt.scatter(x2.numpy(), y2.numpy()) # true data
# x轴范围(0, 20),y轴范围(0, 41)
plt.xlim(0, 20)
plt.ylim(0, 41)
plt.show()
plt.pause(0.5)
# 输出w和b
print(w.squeeze().item(), b.squeeze().item())
输入:print(w.squeeze(), b.squeeze()[0])
出错:
in <module>
print(w.squeeze()[0], b.squeeze()[0])
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
解决方法:将[0]改为.item()
print(w.squeeze().item(), b.squeeze().item())
正确输出结果: