# 导入包
import random
import torch
from matplotlib import pyplot as plt
# import os
# os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# from d2l import torch as d2l
# 设置超参数w,b
true_w = torch.tensor([2,-3.4])
true_b = 4.2
# 构造数据集
def data(w,b,num_examples):
x = torch.normal(0,1,(num_examples,len(w))) # 随机产生变量x(期望为0,方差为1的数)
y = torch.matmul(x,w)+b # 因变量y=Xw+b
y += torch.normal(0,0.01,y.shape) # 随机噪音,均值为0方差为0.0.1
return x,y.reshape((-1,1))
features,lables= data(true_w,true_b,1000) # 产生数据集的feature和label
# print(features[0],lables[0])
# 画图显示噪声图
# fig = plt.figure()
# left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# ax1 = fig.add_axes([left, bottom, width, height])
# plt.scatter(features[:,1], lables, 1)
# ax1.set_title('area1')
# plt.show()
# 定义函数接收批量大小、特征矩阵、标签向量作为输入,生成大小为batch_size的小批量
# 给定一个样本,每次选取b个样本出来进行计算
def data_iter(batch_size,features,labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # 随机打乱下标
# 以batch_size作为步长,随机选取样本
for i in range(0,num_examples,batch_size):
batch_indices = torch.tensor(indices[i:min(i + batch_size,num_examples)]) # min意思是在最后如果索引超出了样本范围,所以使用min函数在num_examples和i+batch_size中选择最小的
yield features[batch_indices],labels[batch_indices] # 返回给feature和label
batch_size = 10 # 这里分批处理样本个数设置为10
# for x,y in data_iter(batch_size,features,lables):
# print(x,'\n',y)
# break
# 定义初始化模型参数
w = torch.normal(0,0.01,size=(2,1),requires_grad=True) # 正态分布,w是(2,1)维的张量
b = torch.zeros(1,requires_grad=True) # requires_grad=True设置为True是因为需要回归
# 定义线性回归模型
def linreg(x,w,b):
return torch.matmul(x,w)+b # 矩阵*向量 返回y(模型预测的y)
# 定义损失函数
def squared_loss(y_hat,y): # y_hat是预测值
return (y_hat - y.reshape(y_hat.shape)) **2 / 2 # **是平方
# 定义优化算法
def sgd(params,lr,batch_size):
with torch.no_grad():
# 小批量随机下降
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_() # 将梯度归零
# 训练过程
# 学习率设置0.03,设置过小会导致收敛过程非常缓慢,设置过大可能会导致不收敛
lr = 0.03
num_epochs = 3 # 整个数据扫3遍
net = linreg
loss = squared_loss
# 第一层循环是整个数据集扫三遍
# 第二层循环是x,y在所获的样本中进行模型训练,得到损失值进行累加回归计算梯度
for epoch in range(num_epochs):
for x,y in data_iter(batch_size, features, lables):
l = loss(net(x, w, b), y) # 将预测与实际的y值放入损失函数
l.sum().backward() # 计算梯度
sgd([w,b], lr, batch_size) # 调用优化算法(随机梯度下降)
# 评价一下我们的进度
with torch.no_grad():
train_l = loss(net(features, w, b), lables) # 把全部数据的label和feature传入模型,计算损失,打印
print(f'{epoch+1},loss{float(train_l.mean()):f}') # 输出每次循环之后的损失值
pytorch实现线性回归
最新推荐文章于 2024-04-21 16:29:42 发布