pytorch实现线性回归
线性回归应用:如计算房价与面积/房龄的线性函数关系,参数面积越大,一般房价越高(正比,y=kx正斜率k);年代越长,一般房价越低(反比,y=kx负斜率k)。假设房价与两个参数呈线性关系,则初始化参数时,取 true_w = [2, -3.4]
import numpy as np
import torch
import random
from matplotlib import pyplot as plt
def show(sample, labels):
print('show')
plt.scatter(sample, labels, 1)
plt.show()
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # 样本的读取顺序是随机的
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # 最后一次可能不足一个batch
yield features.index_select(0, j), labels.index_select(0, j)
def linreg(X, w, b):
return torch.mm(X, w) + b
def squared_loss(y_hat, y):
# 注意这里返回的是向量, 另外, pytorch里的MSELoss并没有除以 2
return (y_hat - y.view(y_hat.size())) ** 2 / 2
def sgd(params, lr, batch_size):
for param in params:
param.data -= lr * param.grad / batch_size # 注意这里更改param时用的param.data
def main():
# 生成 1000*2 数据
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = torch.randn(num_examples, num_inputs, dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float32)
# show(features[:, 0].numpy(), labels.numpy())
# show(features[:, 1].numpy(), labels.numpy())
# 按照batch_size取数据
batch_size = 10
# for X, y in data_iter(batch_size, features, labels):
# print(X, y)
# break
# 随机初始化w b
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
print("w b : ", '\n', w, '\n', b)
# 设置超参数 网络与损失函数
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
# 训练
for epoch in range(num_epochs): # 训练模型一共需要num_epochs个迭代周期
# 在每一个迭代周期中,会使用训练数据集中所有样本一次(假设样本数能够被批量大小整除)。X
# 和y分别是小批量样本的特征和标签
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y).sum() # l是有关小批量X和y的损失
l.backward() # 小批量的损失对模型参数求梯度
sgd([w, b], lr, batch_size) # 使用小批量随机梯度下降迭代模型参数,更新w, b
# 不要忘了梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item())) # .item()得到一个元素张量里面的元素值
print(true_w, '\n', w)
print(true_b, '\n', b)
if __name__ == '__main__':
main()
结果:
w b :
tensor([[ 0.0056],
[-0.0033]], requires_grad=True)
tensor([0.], requires_grad=True)
epoch 1, loss 0.034380
epoch 2, loss 0.000122
epoch 3, loss 0.000049
[2, -3.4]
tensor([[ 1.9996],
[-3.3998]], requires_grad=True)
4.2
tensor([4.2002], requires_grad=True)
参考学习,把学习中的知识整合,并非自己实现。
参考:https://tangshusen.me/Dive-into-DL-PyTorch/#/chapter03_DL-basics/3.2_linear-regression-scratch