当前位置:网站首页>动手学深度学习_线性回归
动手学深度学习_线性回归
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)边栏推荐
猜你喜欢

(十四)平衡二叉树

【go语言入门笔记】12、指针
![[Deep Learning 21 Days Learning Challenge] 1. My handwriting was successfully recognized by the model - CNN implements mnist handwritten digit recognition model study notes](/img/62/ab3dbbd7d4d0009c7cba5e45879f25.png)
[Deep Learning 21 Days Learning Challenge] 1. My handwriting was successfully recognized by the model - CNN implements mnist handwritten digit recognition model study notes

【CV-Learning】卷积神经网络

flink-sql所有语法详解

简单明了,数据库设计三大范式

MySql的concat和group_concat的区别

postgresql 游标(cursor)的使用

npm install dependency error npm ERR! code ENOTFOUNDnpm ERR! syscall getaddrinfonpm ERR! errno ENOTFOUND

多项式回归(PolynomialFeatures)
随机推荐
WARNING: sql version 9.2, server version 11.0.Some psql features might not work.
postgresql 事务隔离级别与锁
SQL练习 2022/7/3
剑指 Offer 2022/7/8
sql中group by的用法
k9s-终端UI工具
MySQL最左前缀原则【我看懂了hh】
智能合约安全——私有数据访问
Kubernetes基础入门(完整版)
剑指 Offer 2022/7/4
lmxcms1.4
双重指针的使用
ReentrantLock(公平锁、非公平锁)可重入锁原理
Linear Regression 02---Boston Housing Price Prediction
Install dlib step pit record, error: WARNING: pip is configured with locations that require TLS/SSL
NFT市场开源系统
fill_between in Matplotlib; np.argsort() function
MySql--存储引擎以及索引
(十一)树--堆排序
TensorFlow2学习笔记:4、第一个神经网模型,鸢尾花分类