深度学习一条龙-研0入门

一、anaconda

1、安装

1、详细步骤见其他文章。

2、添加“D:\ProgramData\anaconda3\Scripts”到Path,这样就可以在CMD里使用conda命令了

3、pycharm中添加conda虚拟环境

2、conda命令

创建虚拟环境

conda create --name 名字 python=3.9

删除虚拟环境

conda env remove --name 环境名

激活虚拟环境

conda activate 环境名

查看所有环境

conda env list

查看依赖列表

conda list

退出虚拟环境

conda deactivate

安装依赖

conda install 依赖=版本

删除下载源/初始化

conda config --remove-key channels

查看下载源

conda config --show channels

pytorch-gpu版

1、正常情况确定版本顺序(从先到后):python ——> pytorch ——> cuda —— > cudnn

查看对应pytorch对应表【环境搭建】Python、PyTorch与cuda的版本对应表_pytorch cuda版本对应关系-CSDN博客

2、不在乎pytorch版本: python ——> cuda —— > cudnn ——> pytorch

直接修改pip install torch --index-url cuda版本即可

例如:conda install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

(红色文字处,即为对应cuda版本)

1、创建虚拟环境

conda create --name 虚拟环境名字xxx python=对应版本

2、激活虚拟环境

conda activate xxx

3、安装pytorch-gpu

在线安装。可通过修改--index-url 最后的cu118指定cuda版本。例如cu128,指定cuda12.8版本。

conda install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

或者

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

4、安装cuda/cudnn

查看GPU支持版本

1、win+R进入终端窗口

2、输入nvidia-smi查看cuda支持版本(此处为最高支持版本,实际安装版本可低于该版本)

方法一:虚拟环境安装(推荐)

查询conda能安装的cuda版本

(如果查询不到所需的cuda版本,需要手动下cudatoolkit依赖,然后pip install 依赖)

conda search cudatoolkit

 安装cuda

conda install cudatoolkit=11.8 -c nvidia

 安装cudnn

conda install cudnn==(指定的版本,见对应表)

方法二:全局安装

cuda官网: CUDA Toolkit Archive | NVIDIA Developer

1、下载cuda安装包

2、打开cuda安装包 

选择安装目录——自定义安装——只勾选cuda——全点下一步——完成


cudnn官网: cuDNN Archive | NVIDIA Developer

1、下载cudnn压缩包/安装包

2、将 cudnn内容复制到cuda文件夹里

cudnn内容

复制到cuda安装目录

NVIDIA GeForce RTX 5070ti 实测可行版本

pytorch = 2.7.0+cu128

cuda = 12.8.1

cudnn = 9.8.0

xformers =  0.0.30

时间:2025.5.22

Pytorch相关知识

包含模块

PyTorch 核心

torchaudio 处理音频

torchtext 处理文字

torchvision 处理视觉图片

TorchElastic TorchServe PyTorch on XLA Devices

加载数据

pytorch每个模块包含各自的数据集,以下内容以 torchvision 模块为例

参数:

root:下载地址

train:是否为训练集

download:是否下载数据

import torchvision
​
torchvision.datasets.xxxx()
例如:
train_set = torchvision.datasets.CIFAR10(root="./dataset", train=True,download=True)
test_set = torchvision.datasets.CIFAR10(root="./dataset", train=False,download=True)

dataloader

对数据集合进行分批

参数:

dataset:数据集对象,

batch_size:每批次的数量,

shuffle:是否随机选取,

num_workers:线程数量,0代表主线程

drop_last:无法满足batch_size 时是否丢弃数据

from torch.utils.data import DataLoader
​
test_data = torchvision.datasets.CIFAR1e("./dataset", train=False,transform=torchvision.transforms. ToTensor())
​
test_loader = DataLoader(dataset=test_data, batch_size=4, shuffle=True,num_workers=0,drop_last=False)
​
for data in test_loader:
    imgs, targets = data
    print( imgs.shape) // [4,32,32,3] 每一批有四个tensor对象
    print(targets)
​

tensorboard

用于显示图像

安装

pip/conda install tensorboard

查看图像

命令行

tensorboard --logdir="文件地址" --port=端口号

使用

from torch.util.tensorboard import SummaryWriter
​
writer = SummaryWriter("log地址")
​
1、writer.add_scaler("标题",y轴,x轴)
2、writer.add_image("标题",y轴,x轴)
​
writer.close()

transform

导入

from torchvision import transforms

ToTensor

将图片对象转化为Tensor对象

from PIL import Image
from torchvision import transforms
#绝对路径c: \users \Zhiyao\Desktop\learn_torch\dataset\train\ants_image \0013035.jpg
#耜对路径dataset/train/ants_image/0013035.jpg
img_path = "dataset/train/ants_image/0013035.jpg"
​
#获取图片
img = Image.open( img_path)
​
​
tensor_trans = transforms.ToTensor( )
tensor_img = tensor_trans(img)
​

Normalize

归一化

计算公式:input = ( input - mean ) / std

from torchvision import transforms
# 参数一:均值    参数二:方差
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = trans_norm( img_tensor)
​

Resize

缩放图片

from torchvision import transforms
trans_resize = transforms.Resize(( 512,512))
img_resize = trans_resize(img)
print( img_resize)

Compose

组合式操作,有先后顺序之分

#获取图片
img = Image.open( img_path)
tensor_trans = transforms.ToTensor( )
trans_resize_2 = transforms.Resize( 512)
​
#操作组合
trans_compose = transforms.compose( [trans_resize_2,trans_totensor])
img_resize_2 = trans_compose( img )

RandomCrop

随机裁剪,默认正方形

#RandomCrop
trans_random = transforms.Randomcrop( 裁剪大小 512)

tensor

创建tensor对象

torch.tensor([1,2,3])

reshape

改变尺寸

torch.reshape(tensorObj,[w,h])

Conv2d

二维卷积

in_channels:输入通道数,彩色为3

out_channels:卷积核数量,一般为1

kernel_size:卷积核大小,一般为3

stride:步长

padding:边缘填充,默认0,一般为1

group:卷积核组数,int

bias:是否偏置true,boolean

padding_mode: 填充的数字,str

conv2d=torch.nn.functional.Conv2d(in_channels,out_channels,...)
output=conv2d(输入,卷积核,步长)

Convranspose2d

转置卷积:扩大输入input的shape

padding:减小shape

原理:

输入:[1,2] 卷积核:[0,1] 输出:[ 1x0 1x1 2x0 2x1 ]

[3,4] [1,0] [1x1 1x0 ... ]

nn.Convranspose2d(in_channel, out_channel, kernel_size=2, bias=False,padding = 1)

MaxPool2d

最大池化

kernel_size :池化核大小

stride :步长

dilation: 空洞卷积

ceil_mode:是ceil还是floor,boolean类型

​
self.maxpool1 = nn.MaxPool2d(kernel_size=3, ceil_mode=False)
output = self.maxpool1(input)

ReLU

relu函数

input:输入值

inplace:true替换原值,false返回output

relu=nn.ReLU()
output=relu(input,inplace)

Flatten

展平成一行

start_dim:开始维度,默认为1,一般为0

end_dim:结束维度

torch.Flatten(start_dim,end_dim)

flatten

展平成一行

tensorObj.flatten()

Linear

全连接

torch.linear(起始通道数,目标通道数)

Upsample

上采样,将小数据变大数据,例如48x48 -> 96x96

scale_factor:放大倍数

mode: 填充方法

nn.Upsample(scale_factor=2.0,mode=bilinear)

cat

合并特征图(大小需相同,将通道数相加)

torch.cat([metrix1,metrix2])

Sequential

组合操作

#Example of using seqHential
model = nn.Sequential(
    nn.Conv2d(1,20,5),
    nn.ReLU() ,
    nn.Conv2d(20,64,5),
    nn.ReLU()
)
#Example of using Sequential with OrderedDict
model = nn.Sequential(0rderedDict([
    ( ' conv1 ' , nn.Conv2d(1,20,5)),
    ( 'relu1', nn.ReLu()),
    ( ' conv2 ' , nn.Conv2d(20,64,5)),
    ( 'relu2 ' , nn.ReLU())
]))
​

Module

基础神经网络模型抽象类

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 32, kernel_size=5, padding=2)
    def forward(self, x):
        x=self.conv1(x)
​        return x

损失函数

L1Loss

计算公式

input=[1,2,3]

output=[1,2,4]

lossSum= ( 1-1 ) + ( 2 - 2 ) + ( 5 - 3 )

lossMean=lossSum / 3

参数

reduction:sum / mean(默认)

loss = L1Loss(reduction= ' sum ' )
result = loss(inputs, targets)

MSELoss

平方差损失

input=[1,2,3]

output=[1,2,4]

lossSum= ( 1-1 ) ² + ( 2 - 2 ) ² + ( 5 - 3 ) ²

loss = MSELoss()
result = loss(inputs, targets)

backward

反向传播,计算梯度

result_loss = loss(outputs, targets)
result_loss.backward()
 

item

获取值

result_loss = loss(outputs, targets)
loss = result_loss.item()
​

优化器

net = Net()

#创建优化器
optim = torch.optim.SGD(net.parameters(), lr=0.01)

#反向传播,得到梯度gard
result_loss.backward()

optim.step()
​

step

更新权重参数,需要在loss.backward()后使用

#更新权重参数
optim.step()

使用/修改现有模型

以VGG16举例

# pretrained=True代表已经训练好的模型
vgg16_true = torchvision.models.vgg16(pretrained=True)
​
#添加一层
vgg16_true.add_module('keyName',nn.linear())
​
#在某一层添加
vgg16_true.classifier.add_module( ' add_linear ' , nn.Linear(1000,10))
​
#修改某一层
vgg16_true.classifier[6] = nn.Linear(4096,10)
 

模型保存

方式一:保存模型

torch.save(model,'xxxx.pth')
方式二:保存参数(推荐)
torch.save(mdel.state_dict(),"xxxx.pth")

模型加载

方式一:

model=torch.load(path)
方式二:
vgg = nn.models.vgg16(pretrained = false)
vgg.load_state_dict(torch.load(path))

使用GPU

model = Model()
​
model = model.cuda()
或者
  device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    print("当前GPU是否可用: {}".format(torch.cuda.is_available()))
    print("当前设备: {}".format(device))
    model = Model()
    model = model.to(device)

同时训练/测试输入需要变为

   for img,laber in train_data_loader:
            img,laber = img.to(device),laber.to(device)
            input_d = model(img)

GPU问题与解决

问题一:RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor

解决:将dataset数据转换为GPU类型

                        imgs = imgs.to("cude") / imgs = imgs.cuda()

问题二:RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument target in method wrapper_CUDA_nll_loss_forward)

解决:同上,原因为同时存在了cpu和gpu类型的数据,冲突了

           解决方法同上,仔细检查数据类型

复用模型参数

以下使用resnet模型复用举例

def get net (devices ) :
    finetune_net = nn.sequential()
    #复用卷积层权重w
    finetune_net.features = torchvision.models.resnet34(pretrained=True)
    #修改全连接层
    finetune net.output_new = nn.sequential(
        nn.Linear ( 1000,256),
        nn.ReLU ( ) ,
        nn.Linear ( 256,120),
    )
    finetune_net = finetune_net.to( devices [ 0])
    for param in finetune_net.features.parameters()
        #卷积层权重w不进行梯度修改
        param.requires_grad = False
    return finetune_net

数据增广

RandomHorizontalFlip

随机水平翻转

torchvision.transforms.RandomHorizontalFlip()

RandomVerticalFlip

随机上下翻转

torchvision.transforms.RandomVerticalFlip()

RandomResizedcrop

随机剪裁

shape_aug = torchvision.transforms.RandomResizedcrop(
    #输出200x200
    (200,200) , 
    #范围
    scale=(0.1, 1) , 
    #高宽比
    ratio=(0.5,2) )
apply ( img, shape_aug)

ColorJitter

随机亮度、色调、亮度、饱和度

 torchvision.transforms.ColorJitter(
    # 亮度上下随机改变0.5
    brightness=0.5,
    contrast=0, 
    saturation=0, 
    #  色调上下随机改变0.5
    hue=0 ) 

labelimg

用于对目标检查数据集进行标注的工具(画框)

Github:https://github.com/HumanSignal/labelImg

安装

第一步的labelimg是名字,随便取

conda create --name labelimg python=3.7

conda activate labelimg

pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple

(此处可能会报错,见问题与解决)

启动

labelimg

前提:conda activate labelimg

使用

labelimg的一些简单使用

界面介绍

使用步骤

步骤一:选择文件夹

步骤二:设置保存路径

步骤三:选择数据格式

                                                        

步骤四:画框

取一个标签名

步骤五:保存

ctrl+s

问题与解决

问题1

解决方法

每个方法都可以尝试一下, 最稳妥的是方法三,但是需要大约6.6G

方法一:

conda install -c conda-forge pycocotools

方法二:

conda install libpython m2w64-toolchain -c msys2

方法三:

其实他的报错信息里已经提示了—— error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

打开网址 https://visualstudio.microsoft.com/visual-cpp-build-tools/ 下载

勾选桌面应用,右侧选择前两项即可

重启电脑

yolo

yolo V5

项目结构

                          

准备

下载yolov5项目:

git clone https://gitee.com/monkeycc/yolov5.git

下载预训练模型,存放在yolov5-master文件夹下

(挑一个自己喜欢的,推荐yolov5s.pt)

https://github.com/ultralytics/yolov5?tab=readme-ov-file

下载数据集,存放在yolov5-master同级目录下

( 其他数据集网站也可以,注意选择 yolo 格式 / yolov5格式)

https://public.roboflow.com/

检测detect.py

使用官网下载的基础模型yolov5s.pt

  • 检测结果存放在 /yolov5-master/runs/detect/expXXX
python detect.py --source ./data/images/  --weights yolov5s.pt  --conf 0.4
​
其他使用:
python detect.py --source 0# webcam
                        file.jpg # image
                        file.mp4# video
                        path/# directory
                        path/* .jpg # glob
                        rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp             
                        streamrtmp:/ /192.168.1.105/live/test # rtmp stream
                        http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8# http stream
​

使用train.py训练后的模型best.pt

  •  train.py训练后的模型保存在 /yolov5-master/runs/train/expXXXX/weights
  • 检测结果存放在 /yolov5-master/runs/detect/expXXX
python detect.py --source ../data/valid/images/  --weights ./runs/train/exp/weights/best.pt  --conf 0.4

训练train.py

--batch-size 默认16

  • 如果电脑配置一般,batch-size过大可能会导致电脑卡死蓝屏
  • batch-size过低会导致训练速度很慢,例如:batch-size=4,117MB的数据集要训练3-4个小时
  •  train.py训练后的信息保存在 /yolov5-master/runs/train/expXXXX 下
python train.py --data 数据集配置文件地址 --cfg yolo配置文件地址 --weights 训练模型地址 --batch-size 大小
​

 举例

python train.py --data ../data/data.yaml --cfg models/yolov5s.yaml --weights '' --batch-size 64

自定义数据集配置文件

若数据集文件夹data下无data.yaml配置文件,则参考以下内容创建一个配置文件

( 网上下载的yoloV5格式数据集自带配置文件yaml )

train: 训练数据集地址:文件夹/配置文件.txt

val: 验证数据集地址:文件夹/配置文件.txt

nc: 标签数

names: [标签名]

示例:

        train: ../data/train/images

        val: ../data/valid/images

        nc: 2

        names: ['mask ', 'no-mask']

问题与解决

问题一:RuntimeError: Couldn‘t load custom C++ ops. This can happen if your PyTorch and torchvision versions

解决方法:Pytorch和torchvision版本不对应,查看版本对应表格,Pytorch或torchvision二选一修改版本,参考网址:PyToch和Torchvision版本对应及快速安装_怎么确定要安装pytorch和torchvision版本-CSDN博客

问题二:requirements: Ultralytics requirement ['gitpython'] not found

解决方法:conda install gitpython / pip install gitpython 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值