Pytorch编程基础

文章目录


前言

记录一些pytorch的基本使用方法。


一、导入库

python 复制代码
import torch
from torch.autograd import Variable # 自动求导变量
from torch import nn, optim # 网络层与优化器
from torch.utils.data import TensorDataset, DataLoader # 数据集迭代器

二、张量

1.创建张量

python 复制代码
从列表生成:a = torch.tensor([1,2,3], dtype=int)
全1全0:torch.ones(shape),torch.zeros(shape)
整数序列[m,n):torch.arrange(m,n)
随机数[0,1):torch.rand(3,4)
随机整数[m,n):torch.randint(m,n,shape)
正态分布:torch.randn()
相同形状随机数:b = torch.rand_like(a, dtype=float)

2.属性与方法

python 复制代码
维度:a.ndim;形状:a.shape,a.size()
数值:a[0].item()
类型转换:a.float(),a.type(torch.float32)

3.numpy转换

python 复制代码
array = np.array(tensor)
tensor = torch.from_numpy(array)
tensor = torch.tensor(array)

4.维度变换

python 复制代码
b = a.view(shape) 
b = a.reshape(shape) 

5.运算操作

python 复制代码
a+b,torch.add(a,b[,out=c]), a.add_(b)
a-b,a*b,a/b, a%b,a//b,a**m
平方根:torch.sqrt(a)
矩阵乘法:torch.matmul(a, b)
转置:a.T
求和:torch.sum(a)
均值:.mean(a),中位数:.median(a)
最值:torch.max/min/argmax/argmin(a)

三、自动求导

python 复制代码
x = torch.ones(shape, requires_grad=True)
y = x * x
y.backward()
grad = x.grad

四、模型保存

python 复制代码
1、保存模型:
torch.save(model.state_dict(), 'model.pth')
2、载入模型
model.load_state_dict(torch.load('model.pth'))

五、模型定义

1.层连接

python 复制代码
# 层
nn.Linear(in_features, out_features)
nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
nn.MaxPool2d(kernel_size,stride)
nn.LSTM(input_size, hidden_size, num_layers, batch_first)
# 激活函数
self.tanh = nn.Tanh()
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1)
# 模型序列
self.fc = nn.Sequential(nn.Linear(784,128), nn.ReLU())
self.conv = nn.Sequential(nn.Conv2d(32,64,5,1,2), nn.ReLU(), nn.MaxPool2d(2,2))
self.lstm = nn.LSTM(input_size=28, hidden_size=64, num_layers=1, batch_first=True)

2.损失函数

python 复制代码
nn.MSELoss()
nn.CrossEntropyLoss()

3.优化器

python 复制代码
optim.SGD(model.parameters(), lr=0.1)
optim.Adam(model.parameters(), lr=0.001)

总结

pytorch的张量操作与numpy数组基本一致。模型保存只保存参数,加载时需要重新定义模型。采用继承类的形式来定义模型,在初始化中设置模型参数,在方法中进行前向传播,注意按层要求修改数据形状。

相关推荐
躺平的花卷5 分钟前
Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中
数据库·爬虫·python·mysql
虚拟搬运工6 分钟前
Python类及元类的创建流程
开发语言·chrome·python
5pace9 分钟前
机器学习(西瓜书)第 14 章 概率图模型
人工智能·机器学习
Linux猿12 分钟前
828华为云征文 | 云服务器Flexus X实例:部署 AgentOps,全方位监测智能体
人工智能·华为云·agent·autogen·flexus云服务器x实例·华为云服务器·agentops
Rense129 分钟前
开源RK3588 AI Module7,并与Jetson Nano生态兼容的低功耗AI模块
人工智能·开源
学步_技术30 分钟前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式
FL16238631291 小时前
[数据集][目标检测]不同颜色的安全帽检测数据集VOC+YOLO格式7574张5类别
人工智能·yolo·目标检测
QuantumYou1 小时前
计算机视觉 对比学习 串烧二
人工智能·学习·计算机视觉
阿利同学1 小时前
热成像目标检测数据集
人工智能·目标检测·机器学习·目标跟踪·数据集·热成像目标检测数据集·机器学习 深度学习
Desire.9841 小时前
Python 数学建模——灰色关联度分析
python·数学建模·灰色关联度