python线性回归实现

编程入门 行业动态 更新时间:2024-10-15 20:20:55

python<a href=https://www.elefans.com/category/jswz/34/1768154.html style=线性回归实现"/>

python线性回归实现

import random
import torch# ①根据带有噪声的线性模型构造一个人造数据集。 使用线性模型参数w=[2,−3.4]  b=4.2和噪声项ϵ生成数据集及其标签
def synthetic_data(w, b, num_examples):"""生成 y = Xw + b + 噪声。"""# 生成均值为0,标准差为1,行为num_examples = 1000,列为len(w)=2的矩阵,也就是从一个标准正态分布N~(0,1),提取一个1000*2的矩阵。X = torch.normal(0, 1, (num_examples, len(w)))# 此时X为1000*2的矩阵,也就是二维张量,w为向量,也就是一维张量,符合normal运算的第四种情况,此时将w转置为列向量,也就是2*1的矩阵,做矩阵乘法结果为1000*1的列向量。y = torch.matmul(X, w)+b# 生成均值为0,标准差为0.01的噪声加上y,返回新的yy += torch.normal(0, 0.01, y.shape)# 返回X 将y转置成1列后返回return X, y.reshape((-1, 1))
# 定义w
true_w = torch.tensor([2, -3.4])
# 定义b
true_b = 4.2
# 生成数据集和标签
features, labels = synthetic_data(true_w, true_b, 1000)
# 打印第一个特征和标签,观察数据集和特征格式
print('features:', features[0], '\nlabel:', labels[0])# ②定义一个data_iter 函数, 该函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size的小批量
def data_iter(batch_size, features, labels):# features的len应该是1000num_examples = len(features)# rang(1000)的一个数据再list一下组成一个列表indices = list(range(num_examples))# 把序列进行一下乱序random.shuffle(indices)# 返回一个数据集和标签for i in range(0, num_examples, batch_size):batch_indices = torch.tensor(indices[i:min(i + batch_size, num_examples)])yield features[batch_indices], labels[batch_indices]
# 定义尺寸
batch_size = 10
# 打印
for X, y in data_iter(batch_size, features, labels):print(X, '\n', y)break# ③定义 初始化模型参数
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)# ④定义模型
def linreg(X, w, b):"""线性回归模型。"""return torch.matmul(X, w) + b# ⑤定义损失函数
def squared_loss(y_hat, y):"""均方损失。"""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_sizeparam.grad.zero_()# ⑦训练过程
# 定义学习率(理解为梯度下降中的步长不知道对不对)
lr = 0.03
# 定义学习几轮
num_epochs = 5
# 定义网络
net = linreg
# 定义损失函数
loss = squared_lossfor epoch in range(num_epochs):for X, y in data_iter(batch_size, features, labels):l = loss(net(X, w, b), y)l.sum().backward()sgd([w, b], lr, batch_size)with torch.no_grad():train_l = loss(net(features, w, b), labels)print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')print(f'b的估计误差: {true_b - b}')

学习第三轮时候基本已经稳定

epoch 1, loss 0.035958
w的估计误差: tensor([ 0.0963, -0.1706])
b的估计误差: tensor([0.1828])
epoch 2, loss 0.000128
w的估计误差: tensor([ 0.0048, -0.0085])
b的估计误差: tensor([0.0081])
epoch 3, loss 0.000050
w的估计误差: tensor([ 0.0003, -0.0001])
b的估计误差: tensor([0.0006])
epoch 4, loss 0.000050
w的估计误差: tensor([4.5466e-04, 1.8120e-05])
b的估计误差: tensor([0.0004])
epoch 5, loss 0.000050
w的估计误差: tensor([3.6359e-05, 3.4094e-05])
b的估计误差: tensor([0.0004])Process finished with exit code 0

更多推荐

python线性回归实现

本文发布于:2023-11-15 06:26:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线性   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!