Pytorch常用代码总结

PyTorch

pytorch=numpy+GPU

pytorch针对于神经网络,而sklearn针对于机器学习

区别:

  1. PyTorch的接口有Python和C++,而TensorFlow接口有Python,C++,JavaScript,Swift。

张量(Tensor)相当于一个矩阵,它可以是比二维更高的(>标量、向量)。

指令

conda env export > environment.yml
conda env create -f environment.yml -n myenv
conda create -n pytorch python=3.8.3#创建环境
conda remove -n pytorch_gpu --all#删除环境
conda info -e#查看所有环境
conda list (tensor) +ctrl+f#查找conda包列表
conda activate pytorch_gpu#切换环境
python#进入Python执行状态
jupyter notebook

conda install nb_conda#安装jupyter
pip install scipy #数据集时使用,有大量数学公式

nvidia-smi #查看驱动详情

模型训练经验

参数

batch size:过小,花费时间多,同时梯度震荡严重,不利于收敛;batch size过大,不同batch的梯度方向没有任何变化,容易陷入局部极小值

模型准确率低

获取更多数据(处理缺失值和异常值)

特征工程及选择

交叉验证

减少正则化和dropout

增加模型复杂度

Tensor

https://blog.youkuaiyun.com/qq_29462849/article/details/124223906

#张量变形
output = torch.reshape(output, (-1, 3, 30, 30))
# (N, C, H, W)batch_size、channel_size、height、wieght
#转换sensor的尺寸为各种NN可以接受的格式;-1时系统算包内图片数量,图层channel通道由6转化为3显示,30行且30列
tensor = torch.randn(3,4,5)
print(imgs.shape)=====torch.Size([64,3,22,32])#一个torch包有64张图片,每张图片3个图层,图片大小为22*32
print(tensor.type())  # 数据类型
print(tensor.size())  # 张量的shape,是个元组
print(tensor.dim())   # 维度的数量

#张量命名
tensor = torch.rand(3,4,1,2,names=('C', 'N', 'H', 'W'))
tensor = tensor.align_to('N', 'C', 'H', 'W')#排序
images.select('C', index=0)


torch.ones((64, 3, 32, 32))#随机生成64个包,3个rgb的图
torch.zeros(2, 3)#初始化一个3*3的零矩阵
torch.Size([64, 10])#64个图片,10个小包

b = x.permute(1,0,2)            # 纬度交换,默认(0,1,2)
x.view(1, 2, 0)#x:torch.Size([3, 68, 266])维度修改为([68, 266, 3]),以显示图片

数据转换

tensor = tensor.cuda()
tensor = tensor.cpu()
tensor = tensor.float()

# torch.Tensor《==》np.ndarray
ndarray = tensor.cpu().numpy()
tensor = torch.from_numpy(ndarray).float()
tensor = torch.from_numpy(ndarray.copy()).float() # If ndarray has negative stride.

# Torch.tensor《==》PIL.Image
# pytorch中的张量默认采用[N, C, H, W]的顺序,并且数据范围在[0,1],需要进行转置和规范化
# torch.Tensor -> PIL.Image
image = PIL.Image.fromarray(torch.clamp(tensor*255, min=0, max=255).byte().permute(1,2,0).cpu().numpy())
image = torchvision.transforms.functional.to_pil_image(tensor)  # Equivalently way
# PIL.Image -> torch.Tensor
path = r'./figure.jpg'
tensor = torch.from_numpy(np.asarray(PIL.Image.open(path))).permute(2,0,1).float() / 255
tensor = torchvision.transforms.functional.to_tensor(PIL.Image.open(path)) # Equivalently way

# np.ndarray《==》PIL.Image的转换
image = PIL.Image.fromarray(ndarray.astype(np.uint8))
ndarray = np.asarray(PIL.Image.open(path))

read_data

read_data.py

dir(torch.cuda.is_available())#类下的方法或对象
help(torch.cuda.is_available())

#读取图片
from PIL import Image
img_path="C:\\Users\\21438\\PycharmProjects\\pythonProject\\imgs\\001.png"
img = Image.open(img_path)
img.size
img.shape# 格式
img.show()
Out[6]: (425, 384)

#读取路径
import os
dir_path = "imgs"
img_path_list = os.listdir(dir_path)
img_path_list[0]
Out[10]: '000.jpg'
#拼接路径
root_dir = "dataset/train"
label_dir = "ants"
path = os.path.join(root_dir , label_dir)

torchvision数据集

vision视觉P10_dataset_transform.py

train_set = torchvision.datasets.CIFAR10(root="./newdataset", train=True, transform=dataset_transform, download=True) #下载并划分CIFAR10图像数据集为train或者test
img, target = test_set[i]#读取

train_set= FoodDataset("./newdataset", tfm=train_tfm)

torchvision模型

model = resnet18(pretrained=False).to(device)
model.load_state_dict(torch.load("resnet18-f37072fd.pth"), strict=False)#加载网络参数

Transform

P9_transform.python

dataset_transform = torchvision.transforms.Compose([
    transforms.Resize((128, 128)),
    torchvision.transforms.ToTensor(),
    
    transforms.RandomResizedCrop((128, 128)),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.ColorJitter(brightness=0.5),
    transforms.RandomAffine(degrees=20, translate=(0.2, 0.2), scale=(0.7, 1.3)),
    torchvision.transforms.ToXXXX()])#使用工具裁剪顺序

dataloader

为网络训练提供数据排列和打包等数据形式dataloader.py

dataset洗好的牌||dataloader怎么抓牌、发牌

test_loader = DataLoader(dataset=train_set, batch_size=64, shuffle=True, num_workers=0, drop_last=True)
#对数据进行打包(抽取规则正反、多余数据省略shuffle、包内数量batch_size)

loss

损失函数目的:

  • 计算实际输出和目标之间的差距
  • 为我们的更新输出提供一定的依据(反向传播)
from torch.nn import nn

loss_mse = nn.MSEloss()#求平方和函数/
loss_cro = nn.CrossEntropyLoss()#求log和/;[N,C]C在这里可能是渠道或者类别
loss = nn.L1loss()#不求平方和
result_loss = loss(onputs, targets)#神经网络计算出的结果与目标值

在这里插入图片描述

optim

对很多算法的优化nn_optim.py

optim = torch.optim.SGD(tudui.parameters(), lr=0.01,momentum=0.9,...)#参数,lr学习速率,后面参数算法默认

for epoch in range(20):#进行20次训练
    for data in dataloader:#每次训练中有batch_size的数量
        outputs = tudui(inputs)
        result_loss = loss(outputs, targets)
        optim.zero_grad()#每个参数梯度清0(循环时对上一步(或原有)的梯度参数清零,进行下一步计算新的梯度参数)
        result_loss.backward()#通过反向传播获取每个参数的梯度(执行这段代码前每个节点的梯度参数没有存在,但没有被统计)()
        optim.step()#通过上一步的梯度参数对权重参数调优
        running_loss = running_loss + result_loss

nn

*conv

TORCH.NN->Containers->module神经网络骨架搭建nn_module.py、nn_conv2d.py

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):#神经网络类
    def __init__(self):
        super(Model, self).__init__()#初始化骨架
        self.conv1 = nn.Conv2d(1, 20, 5)#二维卷积
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))#经过卷积+非线性处理
        return F.relu(self.conv2(x))

#   其中
torch.nn.Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)#加权卷积
#in_channels输入的通道数;彩色图像通道数默认为3,三层图层rgb,通过两个卷积核输出为6(3*2)层
#kernel_size卷积核为3*3或[2,3]
#stride横向走一步、纵向走一步
#padding原始矩阵边缘填充为1格,默认填充0;
#dilation卷积核对应位距离;卷积核中间填充一个位置(官网有动图)
#groups都是1
#bias卷积后结果是否在加减一个数
#padding_mode是padding填充模式
#ceil_model是否执行floor天花板理论;为true时保留一个卷积数据

#device为CPU或GPU

Conv2d(3, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 10)
#图如下

在这里插入图片描述

ResNet网络参数修改( 因为CIFAR数据集是十个类别,所以改为自己数据集的类别数即可。)

inchannel = net.fc.in_features
net.fc = nn.Linear(inchannel, 10) 

*maxpool

logs_maxpool.py
在这里插入图片描述

卷积(变成n个图层)=》类似于一个图片分成两个图层

池化(交叉提取,省略部分信息)=》类似于马赛克(加快模型训练速度)

torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)#取最大值池化或sigmoid
#return_indices不做了解

*ELU

nn-relu.py非线性层

torch.nn.ELU(alpha=1.0, inplace=False)
#alpha算法中的a值
#inplace是否在原来位置上替换

通过公式规范值,分断函数处理参数(不同x,y的函数不同)

*linear

torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
#in_features输入尺寸
#out_features输出尺寸
#bias偏置

在这里插入图片描述

savemodel

Docs-》torchvision.models-》Classification-》VGG

# 保存方式1,模型结构+模型参数
torch.save(vgg16, "vgg16_method1.pth")

# 保存方式2,模型参数(官方推荐)以字典形式
torch.save(vgg16.state_dict(), "vgg16_method2.pth")

tensorboard

显示统计图P9_tensorboard.python

Python Console中

from torch.utils.tensorboard import SummaryWriter
writer=SummaryWriter("logsyyyyy")
for i in range(100):
    writer.add_scalar("y=x",i,i)
#这里会生成一个logsyyyyy下的events.out.tfevents.1633593993.DESKTOP-S29DI1A.2800.0
writer.close()

Terminal中

tensorboard --logdir=logs#打开log图像6006
tensorboard --logdir=logs --port=6007#切换端口

案例二:

img_array = np.array(img_PIL)#PIL->numpy.ndarray
writer.add_image("mmmm", img_array, 1, dataformats='HWC')#训练图片+shape改变

GPU

方法1步骤:train_gpu_1.py

  1. 找到网络模型.cuda(),例tudui=tudui.cuda()
  2. 找到数据(imgs训练输入、测试输入imgs、targets标注).cuda()
  3. 找到损失函数.cuda()

方法2步骤:train_gpu_2.py

  1. device.torch.device(“cuda:0”)#两个显卡的第一个
  2. 2/3/4全部例如:imgs=imgs.to(device)
#util ML2021HW1video
def get_device():
    ''' Get device (if GPU is available, use GPU) '''
    return 'cuda' if torch.cuda.is_available() else 'cpu'

jupyter

jupyter可以使用GPU

jupyter可以运行terminal(加 !)

!

基础

重要文件后缀

pth模型

csv表格

events.out.tfevents.1633593993.DESKTOP-S29DI1A.2800.0的tensorboard输出图像

重要配置目录

新项目配置:导入代码(如有选择Existing environment),直接按照默认环境执行py程序即可

设置Pycharm为PyTorch环境 Settings-》Project Interpret中添加其python.exe

Settings-》Keymap快捷键

模型训练流程

  1. 准备数据集

  2. 加载数据集

  3. 创建网络模型

  4. 损失函数、优化器

  5. 设置训练网络的一些参数(训练次数、tensorboard可视化)

  6. 多次训练

文件作用

P8_Tensorboard.py读取一张图片形成tensorboard

read_data.py读取蜜蜂和蚂蚁形成tensorboard

dataloader.py读取下载的CIFAR10数据集loader成包后形成tensorboard

nn_module.py–》跑一遍i+1的自定义无网络

nn_conv.py·–》矩阵无卷积原理

nn_conv2d.py–》只进行卷积的网络

nn_maxpool.py(池化案例)–》nn_relu.py(非线性案例)–》nn_linear.py–》(线性案例)–》nn_loss(损失函数)-》nn_loss_network.py第二个使用神经网络代码–》nn_optim优化器(第三个使用神经网络代码)

nn_seq.py通过网络图首个复现神经网络代码,引入forward管理模型

model_pretrained.py(模型修改)vgg16模型预训练并(添加)修改模型

model_save.py与model_load.py(未预训练)的模型保存与加载、优化器、

train.py+model.py使用CIFAR10的数据集和model.py网络模型训练与测试神经网络--------------最重要most important

train_cpu.py、train_gpu_1、train_gpu_2.py对GPU与CPU训练对比

test.py 使用训练好的神经网络测试图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值