当前位置: 首页 > news >正文

pytorch 实现线性回归(深度学习)

一 查看原始函数

        y=2x+4.2

初始化

%matplotlib inline
import random
import torch
from d2l import torch as d2l

1.1 生成原始数据

def synthetic_data(w, b, num_examples):x = torch.normal(0, 1, (num_examples, len(w)))y = torch.matmul(x, w) + bprint('x:', x)print('y:', y)y += torch.normal(0, 0.01, y.shape)  # 噪声return x, y.reshape((-1 , 1))
true_w = torch.tensor([2.])
true_b = 4.2
print(f'true_w: {true_w}, true_b: {true_b}')features, labels = synthetic_data(true_w, true_b, 10)

1.2 数据转换

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):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(f'x: {x}, \ny: {y}')

1.3 初始化权重

随机初始化,w使用 均值0,方差 0.01 的随机值, b 初始化为1

w = torch.normal(0, 0.01, size = (1,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
w, b

二 执行训练

查看训练过程中的 参数变化:

print(f'true_w: {true_w}, true_b: {true_b}')def squared_loss(y_hat, y):return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2def linreg(x, w, b):return torch.matmul(x, w) + bdef sgd(params, lr, batch_size):with torch.no_grad():for param in params:# print('param:', param, 'param.grad:', param.grad)param -= lr * param.grad / batch_sizeparam.grad.zero_()lr = 0.03
num_epochs = 1000
for epoch in range(num_epochs):for x, y in data_iter(batch_size, features, labels):l = squared_loss(linreg(x, w, b), y)   # 计算总损失print('w:', w, 'b:', b)  # l:', l, '\nl.sum().backward()sgd([w, b], lr, batch_size)

 


三 测试梯度更新

初始化数据

%matplotlib inline
import random
import torch
from d2l import torch as d2ldef synthetic_data(w, b, num_examples):x = torch.normal(0, 1, (num_examples, len(w)))y = torch.matmul(x, w) + bprint('x:', x)print('y:', y)y += torch.normal(0, 0.01, y.shape)  # 噪声return x, y.reshape((-1 , 1))true_w = torch.tensor([2.])
true_b = 4.2
print(f'true_w: {true_w}, true_b: {true_b}')features, labels = synthetic_data(true_w, true_b, 10)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):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(f'x: {x}, \ny: {y}')w = torch.normal(0, 0.01, size = (1,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
w, b

3.1 测试更新

print(f'true_w: {true_w}, true_b: {true_b}')def squared_loss(y_hat, y):return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2def linreg(x, w, b):return torch.matmul(x, w) + bdef sgd(params, lr, batch_size):with torch.no_grad():for param in params:print('param:', param, 'param.grad:', param.grad)
#             param -= lr * param.grad / batch_size
#             param.grad.zero_()lr = 0.03
num_epochs = 2
for epoch in range(num_epochs):for x, y in data_iter(batch_size, features, labels):l = squared_loss(linreg(x, w, b), y)   # 计算总损失print(f'\nepoch: {epoch},w:', w, 'b:', b)  # l:', l, '\nl.sum().backward()  # 计算更新梯度sgd([w, b], lr, batch_size)

使用 l.sum().backward()  # 计算更新梯度:

不使用更新时:

print(f'true_w: {true_w}, true_b: {true_b}')def squared_loss(y_hat, y):return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2def linreg(x, w, b):return torch.matmul(x, w) + bdef sgd(params, lr, batch_size):with torch.no_grad():for param in params:print('param:', param, 'param.grad:', param.grad)
#             param -= lr * param.grad / batch_size
#             param.grad.zero_()lr = 0.03
num_epochs = 2
for epoch in range(num_epochs):for x, y in data_iter(batch_size, features, labels):l = squared_loss(linreg(x, w, b), y)   # 计算总损失print(f'\nepoch: {epoch},w:', w, 'b:', b)  # l:', l, '\n# l.sum().backward()  # 计算更新梯度sgd([w, b], lr, batch_size)#     break

相关文章:

  • 力扣72. 编辑距离(动态规划)
  • EasyRecovery软件免费版与付费版有哪些功能区别?
  • Ps:污点修复画笔工具
  • 【Linux】线程同步
  • 《白话C++》第10章 STL和boost,Page67~70 std::auto_ptr
  • react中如何做到中断diff过程和恢复
  • 中科院一区论文复现,改进蜣螂算法,Fuch映射+反向学习+自适应步长+随机差分变异,MATLAB代码...
  • (13)Hive调优——动态分区导致的小文件问题
  • 【大数据Hive】hive 表设计常用优化策略
  • 链表的回文结构
  • 【Java万花筒】数据流的舵手:大数据处理和调度库对比指南
  • C语言if语句底层原理,从汇编深入理解
  • MIT-BEVFusion系列八--onnx导出1 综述及相机网络导出
  • StarRocks表设计——分区分桶与副本数
  • 基于微信小程序的健身房私教预约系统,附源码
  • isset在php5.6-和php7.0+的一些差异
  • java8 Stream Pipelines 浅析
  • JavaScript 基础知识 - 入门篇(一)
  • java取消线程实例
  • Objective-C 中关联引用的概念
  • Python代码面试必读 - Data Structures and Algorithms in Python
  • react-core-image-upload 一款轻量级图片上传裁剪插件
  • REST架构的思考
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • SegmentFault 技术周刊 Vol.27 - Git 学习宝典:程序员走江湖必备
  • vue-loader 源码解析系列之 selector
  • 仿天猫超市收藏抛物线动画工具库
  • 好的网址,关于.net 4.0 ,vs 2010
  • 解析带emoji和链接的聊天系统消息
  • 前端工程化(Gulp、Webpack)-webpack
  • 区块链技术特点之去中心化特性
  • 使用 Docker 部署 Spring Boot项目
  • 通过获取异步加载JS文件进度实现一个canvas环形loading图
  • 云大使推广中的常见热门问题
  • [地铁译]使用SSD缓存应用数据——Moneta项目: 低成本优化的下一代EVCache ...
  • PostgreSQL 快速给指定表每个字段创建索引 - 1
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • $().each和$.each的区别
  • (07)Hive——窗口函数详解
  • (1)SpringCloud 整合Python
  • (没学懂,待填坑)【动态规划】数位动态规划
  • (全部习题答案)研究生英语读写教程基础级教师用书PDF|| 研究生英语读写教程提高级教师用书PDF
  • (十一)JAVA springboot ssm b2b2c多用户商城系统源码:服务网关Zuul高级篇
  • (五)IO流之ByteArrayInput/OutputStream
  • (一)搭建springboot+vue前后端分离项目--前端vue搭建
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m
  • .NET 8.0 发布到 IIS
  • .NET delegate 委托 、 Event 事件,接口回调
  • .net 开发怎么实现前后端分离_前后端分离:分离式开发和一体式发布
  • .Net 中Partitioner static与dynamic的性能对比
  • .net反编译工具
  • .NET建议使用的大小写命名原则
  • .net开发时的诡异问题,button的onclick事件无效