当前位置:网站首页>动手学深度学习_线性回归
动手学深度学习_线性回归
2022-08-04 05:29:00 【CV小Rookie】
目录
pytorch实现
线性回归
线性回归(Linear Regression)可以追溯到19世纪初, 它在回归的各种标准工具中最简单而且最流行。 线性回归基于几个简单的假设: 首先,假设自变量x和因变量y之间的关系是线性的, 即y可以表示为x中元素的加权和,这里通常允许包含观测值的一些噪声; 其次,我们假设任何噪声都比较正常,如噪声遵循正态分布。

线性模型可以表示为:
向量版本:
线性模型可以看做单层全连接神经网络

输入为x1,…,xd, 因此输入层中的输入数(或称为特征维度,feature dimensionality)为d。 网络的输出为o1,因此输出层中的输出数是1。
平方损失函数
现在模型已经有了,下一步要进行预测就必须有损失函数,我们使用平方损失:

这里有个系数 1/2 是因为进行求导时,平方 2 可以和 1/2 抵消,方便计算。
为了去衡量在整个模型的质量,所有的
要进行求和,要求平均,如果不求平均,那么梯度就会比较大,反向传播更新时,梯度过大是不希望看到的(如果不求平均,那么学习率就要求平均)

训练参数时,我们希望找到一组参数
使得在所有样本上有最低的损失。

pytorch实现
# 作者 :CV小Rookie
# 创建时间: 2022/7/29 20:41
# 文件名: linear_regression_easy.py
import numpy as np
from torch.utils import data
import torch
from torch import nn
from d2l import torch as d2l
# 利用 d2l 中的 synthetic_data 生成数据
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)
# 读取数据集
def load_array(data_arrays, batch_siz, is_train=True):
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_siz, shuffle=is_train)
batch_size = 10
data_iter = load_array((features, labels), batch_size)
# 定义模型
net = nn.Sequential(nn.Linear(2, 1))
# 初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
#定义损失函数
loss = nn.MSELoss()
# 定义优化算法
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
# 训练
num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X) ,y)
trainer.zero_grad()
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')
w = net[0].weight.data
print('w的估计误差:', true_w - w.reshape(true_w.shape))
b = net[0].bias.data
print('b的估计误差:', true_b - b)边栏推荐
猜你喜欢

纳米级完全删除MYSQL5.7以及一些吐槽

安装dlib踩坑记录,报错:WARNING: pip is configured with locations that require TLS/SSL

Thoroughly understand box plot analysis

TensorFlow2 study notes: 4. The first neural network model, iris classification

Delphi-C side interesting menu operation interface design

PHP课堂笔记(一)

(六)递归

win云服务器搭建个人博客失败记录(wordpress,wamp)

(十五)B-Tree树(B-树)与B+树

TensorFlow2 study notes: 6. Overfitting and underfitting, and their mitigation solutions
随机推荐
sklearn中的pipeline机制
yolov3中数据读入(一)
Th in thymeleaf: href use notes
组原模拟题
剑指 Offer 2022/7/2
IvNWJVPMLt
【深度学习21天学习挑战赛】2、复杂样本分类识别——卷积神经网络(CNN)服装图像分类
win云服务器搭建个人博客失败记录(wordpress,wamp)
智能合约安全——delegatecall (1)
Polynomial Regression (PolynomialFeatures)
(十)树的基础部分(二)
TensorFlow2学习笔记:7、优化器
彻底搞懂箱形图分析
CTFshow—Web入门—信息(1-8)
pgsql函数中的return类型
android基础 [超级详细android存储方式解析(SharedPreferences,SQLite数据库存储)]
read and study
数据库根据提纲复习
剑指 Offer 20226/30
两个APP进行AIDL通信