Pytorch深度学习框架入门

news2024/11/23 12:53:39

1.pytorch加载数据

唤醒指定的python运行环境的命令:

conda activate 环境的名称
from torch.utils.data import Dataset #Dataset数据处理的包
from PIL import Image
import os

#定义数据处理的类
class MyData(Dataset):
    
    #数据地址处理方法
    def __init__(self,root_dir,label_dir):
        self.root_dir = root_dir #读取数据文件的根地址
        self.label_dir = label_dir #读取数据文件的字地址
        self.path = os.path.join(self.root_dir,self.label_dir)# 将根地址和子地址进行拼接
        self.img_path = os.listdir(self.path) #将图片的地址提取出来,并一个个存入到列表中去

    
    #提取每一个图片的信息
    def __getitem__(self, idx):
        img_name = self.img_path[idx] #根据序号从列表中找到相应的图片地址
        img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)# 将根地址与图片地址进行拼接
        img = Image.open(img_item_path) #将地址转换为图片的形式
        label = self.label_dir# 读取标签的地址
        return img,label #返回图片和标签

    #计算数据集的长度
    def __len__(self):
        return len(self.img_path)

root_dir = "dataset/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset = MyData(root_dir,ants_label_dir)
bees_dataset = MyData(root_dir,bees_label_dir)
train_dataset = ants_dataset + bees_dataset

2.TensorBoard的使用

from torch.utils.tensorboard import SummaryWriter
from PIL import  Image
import numpy as np

writer = SummaryWriter("logs")
image_path = "dataset/train/ants/0013035.jpg"
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)
# writer.add_image("test",img_array,1,dataformats='HWC')
# y = x
for i in range(100):
    writer.add_scalar("y=2x",3*i,i)
writer.close()

启动日志的相关命令

tensorboard --logdir=logs --port=6007

3. transfrom的使用

下面图片是transform的图解:

"""
transform的讲解
"""
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms


#python的用法 -》 tensor数据类型
#通过 transform.Totensor去看两个问题
# 1、transform该如何去使用(python)
# 2、为什么我们需要tensor数据类型

# 绝对路径:"F:\learn_pytorch\p9_transform.py"
# 相对路径:"dataset/train/ants/0013035.jpg"
#为什么不选择使用绝对路径,因为在window系统下,\会被认为是转移字符

img_path = "dataset/train/ants/0013035.jpg"# 读取图片的相对地址
img_path_abs = "F:\learn_pytorch\p9_transform.py"# 读取图片的绝对地址
img = Image.open(img_path)# 打开图片
#print(img)

writer = SummaryWriter("logs") # 创建TensorBoard对象

# 1、transform该如何去使用(python)
tensor_trans = transforms.ToTensor()# 创建一个tensor_trans的图片类型转换工具的对象
tensor_img = tensor_trans(img)# 将img转化成tensor的形式
#print(tensor_img)

writer.add_image("Tensor_img",tensor_img)# 利用TensorBoard展示数据

4.常见的transform

 Python中__call__的用法

class Person:
    def __call__(self,name):
        print("__call__"+"Hello"+name)
    def hello(self,name):
        print("hello"+name)

person = Person()

person("张三")

person.hello("lisi")

Totensor()的使用

#Totensor()的使用
trans_Totensor = transforms.ToTensor()
img_tensor = trans_Totensor(img)
writer.add_image('ToTensor',img_tensor)

Normalize()的使用

print(img_tensor[0][0][0])
trans_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])

Resize()的使用

#Resize()
print(img.size)
trans_size = transforms.Resize((512,512))
# img PIL -> resize ->img_resize PIL
img_resize = trans_size(img)
# img_resize PIL -> totensor ->img_resize tensor
img_resize = trans_Totensor(img_resize)
writer.add_image('Resize',img_resize,0)
print(img_resize)

Compose()的使用

#Compose() -resize -2
trans_resize_2 = transforms.Resize(512)
# PIL -> PIL -> tensor
trans_compose = transforms.Compose([trans_resize_2,trans_Totensor])
img_resize_2 = trans_compose(img)
writer.add_image('Compose',img_resize_2)
RandomCrop()的使用
#RandomCrop()
trans_random = transforms.RandomCrop((500,20))

trans_compose_2 = transforms.Compose([trans_random,trans_Totensor])

for i in range(10):
    img_crop = trans_compose_2(img)
    writer.add_image('RandomCrop',img_crop,i)

 4.torchvision中数据集的使用

进入pytorch的官网

依次进入到Docs->torchvision->dataset

 相关代码:

import torchvision
from torch.utils.tensorboard import SummaryWriter

dataset_transform = torchvision.transforms.Compose([
    torchvision.transforms.ToTensor()
])
train_set = torchvision.datasets.(root="./dataset1",train=True,download=True,transform=dataset_transform)#构建训练集
test_set = torchvision.datasets.CIFAR10(root="./dataset1",train=False,download=True,transform=dataset_transform)#构建测试集

'''
print(test_set[0])
print(test_set.classes)
img,target = test_set[0]
print(img)
print(target)
img.show()
'''
# print(test_set[0])
writer = SummaryWriter('p10')
# writer.add_image()
for i in range(10):
    img,target = test_set[i]
    writer.add_image('test_set',img,i)
writer.close()

5.dataloader的使用

 


import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

test_data = torchvision.datasets.CIFAR10(root="./dataset1",train=True,transform=torchvision.transforms.ToTensor(),download=True)

test_loader = DataLoader(dataset=test_data,batch_size=64,shuffle=False,num_workers=0,drop_last=False)

#测试数据集里面的第一章图片及target
img,target = test_data[0]
print(img.shape)
print(target)

writer = SummaryWriter('dataloader')
for epoch in range(2):#进行两轮
    step = 0
    for data in test_loader:
        imgs,targets = data
        writer.add_images(f"Epoch{epoch}",imgs,step)
        step = step + 1
        # print(imgs.shape)
        # print(target)
print("读取结束")
writer.close()

 6.神经网络的基本骨架-nn.Mouble的使用

 

import torch
from torch import nn


class Tudui(nn.Module):

    def __init__(self) -> None:
        super().__init__()

    def forward(self,input):
        output = input + 1
        return output

tutui = Tudui()
x = torch.tensor(1.0)
output = tutui(x)
print(output)

 7.卷积操作


需要重点学会的是:Conv2d

 

 

import torch
import torch.nn.functional as F
#输入
input = torch.tensor([[1,2,0,3,1],
                      [0,1,2,3,1],
                      [1,2,1,0,0],
                      [5,2,3,1,1],
                      [2,1,0,1,1]])
#卷积核
kernel = torch.tensor([[1,2,1],
                       [0,1,0],
                       [2,1,0]])

input = torch.reshape(input,(1,1,5,5))
kernel = torch.reshape(kernel,(1,1,3,3))

print(input.shape)
print(kernel.shape)

output1= F.conv2d(input,kernel,stride=1)
print(output1)
output2 = F.conv2d(input,kernel,stride=2)
print(output2)
output3 = F.conv2d(input,kernel,stride=1,padding=1)
print(output3)

 8.神经网络-卷积层

 


import torch
import torchvision

#加载测试集
from torch import nn
from torch.nn import Conv2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10(root="./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)

dataloader = DataLoader(dataset,batch_size=64,num_workers=0)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = Conv2d(in_channels=3,out_channels=6,kernel_size=3,stride=1,padding=0)

    def forward(self,x):
        x = self.conv1(x)
        return x
tudui = Tudui()
print(tudui)

writer = SummaryWriter('./logs')
step = 0
for data in dataloader:
    imgs,targets = data
    ouput = tudui(imgs)
    print(imgs.shape)
    print(ouput.shape)
    writer.add_images("input",imgs,step)
    ouput = torch.reshape(ouput, (-1, 3, 30, 30))  # ->[xxx,3,30,30],3是通道数减少,使得xxx的batchsize变大
    writer.add_images("ouput",ouput,step)
    step = step + 1
print("over")

  9.神经网络-最大池化的使用

 

 

 

import torch
from torch import nn
from torch.nn import MaxPool2d

input = torch.tensor([[1,2,0,3,1],
                      [0,1,2,3,1],
                      [1,2,1,0,0],
                      [5,2,3,1,1],
                      [2,1,0,1,1]],dtype=torch.float)

input = torch.reshape(input,(-1,1,5,5))

class Tudui(nn.Module) :
    def __init__(self):
        super(Tudui, self).__init__()
        self.maxpool = MaxPool2d(kernel_size=3,ceil_mode=False)



    def forward(self,input):
        output = self.maxpool(input)
        return output
tudui = Tudui()
output = tudui(input)
print(output)

 最大池化的作用:就是压缩。

import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10(root="./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)

dataloader = DataLoader(dataset,batch_size=64,shuffle=True)
'''
input = torch.tensor([[1,2,0,3,1],
                      [0,1,2,3,1],
                      [1,2,1,0,0],
                      [5,2,3,1,1],
                      [2,1,0,1,1]],dtype=torch.float)

input = torch.reshape(input,(-1,1,5,5))
'''
class Tudui(nn.Module) :
    def __init__(self):
        super(Tudui, self).__init__()
        self.maxpool = MaxPool2d(kernel_size=3,ceil_mode=False)



    def forward(self,input):
        output = self.maxpool(input)
        return output

tudui = Tudui()
writer = SummaryWriter("logs")
step = 0
for data in dataloader:
    imgs,target = data
    writer.add_images("imgs",imgs,step)
    print(imgs.shape)
    output = tudui(imgs)
    writer.add_images("maxpool",output,step)
    print(output.shape)
    step = step + 1

writer.close()
print("over")

# tudui = Tudui()
# output = tudui(input)
# print(output)

10.神经网络-非线性激活

'''
ReLU
'''
import torch
from torch import nn
from torch.nn import ReLU

input = torch.tensor([[1,-0.5],
                     [-1,3]])

input = torch.reshape(input,(-1,1,2,2))

print(input.shape)


class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.relu1 = ReLU()

    def forward(self,input):
        output = self.relu1(input)

        return output

tudui = Tudui()
output = tudui(input)
print(output)



'''
Sigmoid
'''
import torch
import torchvision.datasets
from torch import nn
from torch.nn import ReLU, Sigmoid
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

input = torch.tensor([[1,-0.5],
                     [-1,3]])

input = torch.reshape(input,(-1,1,2,2))

print(input.shape)

dataset = torchvision.datasets.CIFAR10(root="./dataset",train=False,download=True,
                                       transform=torchvision.transforms.ToTensor())
dataloader = DataLoader(dataset,batch_size=64)
class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.relu1 = ReLU()
        self.sigmoid1 = Sigmoid()

    def forward(self,input):
        output = self.sigmoid1(input)

        return output

tudui = Tudui()

writer = SummaryWriter("logs")
step = 0
for data in dataloader:
    imgs,targets = data
    print(imgs.shape)
    writer.add_images("imgs",imgs,step)
    output = tudui(imgs)
    print(output.shape)
    writer.add_images("Sigmod",output,step)

writer.close()



11.神经网络-线性层及其它层的介绍 

"""
vgg16
"""
import torch
import torchvision.datasets
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
                                       download=True)

dataloader = DataLoader(dataset,batch_size=64)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.linear1 = Linear(196608,10)

    def forward(self,input):
        output = self.linear1(input)
        return output

tudui = Tudui()

#writer = SummaryWriter("logs")
#step = 0

for data in dataloader:
    imgs,tragets = data
    print(imgs.shape)
    #writer.add_images("imgs",imgs,step)
    #output = torch.reshape(imgs,(1,1,1,-1))
    output = torch.flatten(imgs)
    print(output.shape)
    output = tudui(output)
    print(output.shape)
    #writer.add_images("linear",output,step)
    #step += 1

#writer.close()


12.神经网络-搭建小实战和Sequential的使用

 CIFAR 10 model结构

 

import torch
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.tensorboard import SummaryWriter


class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = Conv2d(3,32,5,padding=2)
        self.maxpool1 = MaxPool2d(2)
        self.conv2 = Conv2d(32,32,5,padding=2)
        self.maxpool2 = MaxPool2d(2)
        self.conv3 = Conv2d(32,64,5,padding=2)
        self.maxpool3 = MaxPool2d(2)
        self.flatten = Flatten()
        self.Linear1 = Linear(1024,64)
        self.Linear2 = Linear(64,10)

        self.model1 = Sequential(
            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)
        )
    def forward(self,x):
        # x = self.conv1(x)
        # x = self.maxpool1(x)
        # x = self.conv2(x)
        # x = self.maxpool2(x)
        # x = self.conv3(x)
        # x = self.maxpool3(x)
        # x = self.flatten(x)
        # x = self.Linear1(x)
        # x = self.Linear2(x)
        x = self.model1(x)
        return x

tudui = Tudui()
input = torch.ones((64,3,32,32))
output = tudui(input)
print(output)


writer = SummaryWriter("logs_seq")
writer.add_graph(tudui,input)
writer.close()

13.损失函数

 

'''
nn.loss
'''

import torch
from torch.nn import L1Loss

inputs = torch.tensor([1,2,3],dtype=torch.float32)
targets = torch.tensor([1,2,5],dtype=torch.float32)

inputs = torch.reshape(inputs,(1,1,1,3))
targets = torch.reshape(targets,(1,1,1,3))

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

print(result)

'''
nn.MSEloss
'''

import torch
from torch.nn import L1Loss
from torch import nn

inputs = torch.tensor([1,2,3],dtype=torch.float32)
targets = torch.tensor([1,2,5],dtype=torch.float32)

inputs = torch.reshape(inputs,(1,1,1,3))
targets = torch.reshape(targets,(1,1,1,3))

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

loss_mse = nn.MSELoss()
result_mse = loss_mse(inputs,targets)

print(result)
print(result_mse)

'''
nn.CrossEntropyLoss
'''

import torch
from torch.nn import L1Loss
from torch import nn

inputs = torch.tensor([1,2,3],dtype=torch.float32)
targets = torch.tensor([1,2,5],dtype=torch.float32)

inputs = torch.reshape(inputs,(1,1,1,3))
targets = torch.reshape(targets,(1,1,1,3))

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

loss_mse = nn.MSELoss()
result_mse = loss_mse(inputs,targets)

print(result)
print(result_mse)

x = torch.tensor([0.1,0.2,0.3])
y = torch.tensor([1])
x = torch.reshape(x,(1,3))
loss_cross = nn.CrossEntropyLoss()
result_cross = loss_cross(x,y)
print(result_cross)

import torchvision
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("./data",train=False,transform=torchvision.transforms.ToTensor(),
                                       download=True)
dataloader = DataLoader(dataset,batch_size = 1)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = Conv2d(3,32,5,padding=2)
        self.maxpool1 = MaxPool2d(2)
        self.conv2 = Conv2d(32,32,5,padding=2)
        self.maxpool2 = MaxPool2d(2)
        self.conv3 = Conv2d(32,64,5,padding=2)
        self.maxpool3 = MaxPool2d(2)
        self.flatten = Flatten()
        self.Linear1 = Linear(1024,64)
        self.Linear2 = Linear(64,10)

        self.model1 = Sequential(
            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)
        )
    def forward(self,x):
        # x = self.conv1(x)
        # x = self.maxpool1(x)
        # x = self.conv2(x)
        # x = self.maxpool2(x)
        # x = self.conv3(x)
        # x = self.maxpool3(x)
        # x = self.flatten(x)
        # x = self.Linear1(x)
        # x = self.Linear2(x)
        x = self.model1(x)
        return x
loss = nn.CrossEntropyLoss()
tudui = Tudui()
for data in dataloader:
    imgs,targets = data
    outputs = tudui(imgs)
    result_loss = loss(outputs,targets)
    result_loss.backward()
    print("ok")
    print(result_loss)
    print(outputs)
    print(targets)

14.优化器

import torch
import torchvision
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("./data",train=False,transform=torchvision.transforms.ToTensor(),
                                       download=True)
dataloader = DataLoader(dataset,batch_size = 1)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = Conv2d(3,32,5,padding=2)
        self.maxpool1 = MaxPool2d(2)
        self.conv2 = Conv2d(32,32,5,padding=2)
        self.maxpool2 = MaxPool2d(2)
        self.conv3 = Conv2d(32,64,5,padding=2)
        self.maxpool3 = MaxPool2d(2)
        self.flatten = Flatten()
        self.Linear1 = Linear(1024,64)
        self.Linear2 = Linear(64,10)

        self.model1 = Sequential(
            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)
        )
    def forward(self,x):
        # x = self.conv1(x)
        # x = self.maxpool1(x)
        # x = self.conv2(x)
        # x = self.maxpool2(x)
        # x = self.conv3(x)
        # x = self.maxpool3(x)
        # x = self.flatten(x)
        # x = self.Linear1(x)
        # x = self.Linear2(x)
        x = self.model1(x)
        return x
loss = nn.CrossEntropyLoss()
tudui = Tudui()
optim = torch.optim.SGD(tudui.parameters(),lr = 0.01,)
for epoch in range(20):
    running_loss = 0.0
    for data in dataloader:
        imgs,targets = data
        outputs = tudui(imgs)
        result_loss = loss(outputs,targets)# 计算损失
        optim.zero_grad()# 梯度清零
        result_loss.backward()# 反向传播,求出每个参数的梯度
        optim.step() #对权重进行更新
        running_loss = running_loss + result_loss
    print(running_loss)

15.现有模型的使用和修改

import torchvision

# train_data = torchvision.datasets.ImageNet("./dataset",split='train',download=True,
#                                            transform=torchvision.transforms.ToTensor())
from torch import nn

vgg16_false = torchvision.models.vgg16(pretrained=False)
vgg16_true = torchvision.models.vgg16(pretrained=True)
print("ok")
print(vgg16_true)


train_data = torchvision.datasets.CIFAR10('./data',train=True,transform=torchvision.transforms.ToTensor(),
                                          download=True)
# 修改vgg16网络模型的结构
vgg16_true.classifier.add_module('add_liner',nn.Linear(1000,10))
print(vgg16_true)
print(vgg16_false)
vgg16_false.classifier[6] = nn.Linear(4096,10)
print(vgg16_false)

16.网络模型的保存与读取

 

自己定义模型

from torch import nn


class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.conv1 = nn.Conv2d(3,64,kernel_size=3)

    def forward(self,x):
        x = self.conv1(x)
        return x

保存模型

import torch
import torchvision

vgg16 = torchvision.models.vgg16(pretrained=False) #加载vgg16初始的模型

#保存方式1
torch.save(vgg16,"vgg16_method1.pth")
import torch
import torchvision
from torch import nn
from Tudui import Tudui
# vgg16 = torchvision.models.vgg16(pretrained=False) #加载vgg16初始的模型
#
# #保存方式1 模型的结构+模型的参数
# torch.save(vgg16,"vgg16_method1.pth")
#
# #保存方式2 模型的参数(官方的推荐)保存为字典的形式
# torch.save(vgg16.state_dict(),"vgg16_method2.pth")

#陷阱

# class Tudui(nn.Module):
#     def __init__(self):
#         super(Tudui, self).__init__()
#         self.conv1 = nn.Conv2d(3,64,kernel_size=3)
#
#     def forward(self,x):
#         x = self.conv1(x)
#         return x
tudui = Tudui()

torch.save(tudui,"tudui_method1.pth")
print("over")

加载模型

import torch
import torchvision

vgg16 = torchvision.models.vgg16(pretrained=False) #加载vgg16初始的模型

#保存方式1
torch.save(vgg16,"vgg16_method1.pth")
"""
加载模型
"""
import torch
#保存方式1的加载模型的方法
import torchvision

# model = torch.load("vgg16_method1.pth")
#print(model)

#方式2的加载模型的方法
# # model = torch.load("vgg16_method2.pth")
# print(model)



vgg16 = torchvision.models.vgg16(pretrained=False)
vgg16.load_state_dict((torch.load("vgg16_method2.pth")))
# print(vgg16)
#陷阱
model = torch.load("tudui_method1.pth")
print(model)

17.完整的模型训练的套路

 定义网络模型Model.py

#搭建神经网络
from torch import nn


class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        #使用序列化的方法更新神经网络的各个层
        self.model = nn.Sequential(
            nn.Conv2d(3,32,kernel_size=5,stride=1,padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(32,32,kernel_size=5,stride=1,padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(32,64,kernel_size=5,stride=1,padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn. Linear(64*4*4,64),
            nn.Linear(64,10)
        )

#定义前向传播
    def forward(self,x):
        x = self.model(x)
        return x

完整的模型训练套路train.py

"""
完整的模型训练的套路
"""

#准备数据集
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from Model import Tudui

train_data = torchvision.datasets.CIFAR10("./data",
                                          train=True,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./data",
                                          train=False,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)

#查看训练集和测试集有多少张
#length 长度
train_data_size = len(train_data) #训练集的长度
test_data_size = len(test_data) #测试集的长度
print(f"训练集的长度为{train_data_size}\n")
print(f"测试集的长度为{test_data_size}\n")

# 利用DataLoader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)

#主函数
if __name__ == '__main__':
    # 创建网络模型
    tudui = Tudui()

    #小测试
    input = torch.ones((64,3,32,32))
    output = tudui(input)
    print(output.shape)
    """
    torch.Size([64, 10])
    64是代表64张照片
    10是代表10个类别,每张图片10各类别上分别的概率
    """

    # 损失函数
    loss_fn = nn.CrossEntropyLoss()

    #学习速率
    #1e-2=1x10^(-2)
    learning_rate = 1e-2

    # 优化器
    optimizer = torch.optim.SGD(tudui.parameters(),lr = learning_rate,)

    #设置训练网络的一些参数
    total_train_step = 0 #记录训练的次数
    total_test_step = 0 #记录测试的次数
    #训练的次数
    epoch = 10
    #添加tensorboard
    writer = SummaryWriter("logs_train")

    for i  in range(epoch):
        print(f"------第{i+1}轮训练开始------")

        # 训练步骤开始
        tudui.train()
        for data in train_dataloader:
            imgs,targets = data
            outputs = tudui(imgs)
            loss = loss_fn(outputs,targets)

            #优化器的调优
            optimizer.zero_grad()# 梯度清零
            loss.backward()# 反向传播
            optimizer.step()# 更新优化参数

            total_train_step = total_train_step + 1 #训练次数加1
            if total_train_step % 100 == 0:# 每个一百次输出一次训练的结果
                print(f"训练次数:{total_train_step},Loss:{loss.item()}") #记录每次训练的损失结果,item()主要就是把loss转化为真实的数,其实转化不转化都行的
                writer.add_scalar("train_loss",loss.item(),total_train_step)

        #测试步骤开始
        tudui.eval()
        total_test_loss = 0
        total_accuracy = 0
        with torch.no_grad():#防止调优,测试时不需要进行调优
            for data in test_dataloader:
                imgs , targets = data
                outputs = tudui(imgs)
                loss = loss_fn(outputs,targets)
                total_test_loss = total_test_loss + loss

                #计算整体的正确率
                accuracy = (outputs.argmax(1) == targets).sum()
                total_accuracy = total_accuracy + accuracy
            print(f"整体测试集上的正确率{total_accuracy/test_data_size}")
            print(f"整体测试集上的Loss:{total_test_loss}")
            writer.add_scalar("test_loss",total_test_loss,total_test_step)
            writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
            total_test_step = total_test_step + 1

        #保存模型
        torch.save(tudui,f"tudui_{i}.ph")
        #torch.save(tudui.state_dict(),f"tudui_{i}.ph")
        print("模型已保存")

    writer.close()

18.利用GPU进行训练

"""
完整的模型训练的套路
"""

#准备数据集
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time

from Model import Tudui

train_data = torchvision.datasets.CIFAR10("./data",
                                          train=True,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./data",
                                          train=False,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)

#查看训练集和测试集有多少张
#length 长度
train_data_size = len(train_data) #训练集的长度
test_data_size = len(test_data) #测试集的长度
print(f"训练集的长度为{train_data_size}\n")
print(f"测试集的长度为{test_data_size}\n")

# 利用DataLoader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)

#主函数
if __name__ == '__main__':
    # 创建网络模型
    tudui = Tudui()
    if torch.cuda.is_available():
        tudui = tudui.cuda()

    #小测试

    input = torch.ones((64,3,32,32))
    device = torch.device('cuda:0') #将tensor.cpu类型的数据转化为tensor.gpu类型的数据
    input = input.to(device)
    output = tudui(input)
    print(output.shape)
    """
    torch.Size([64, 10])
    64是代表64张照片
    10是代表10个类别,每张图片10各类别上分别的概率
    """

    # 损失函数
    loss_fn = nn.CrossEntropyLoss()
    if torch.cuda.is_available():
        loss_fn = loss_fn.cuda()

    #学习速率
    #1e-2=1x10^(-2)
    learning_rate = 1e-2

    # 优化器
    optimizer = torch.optim.SGD(tudui.parameters(),lr = learning_rate,)

    #设置训练网络的一些参数
    total_train_step = 0 #记录训练的次数
    total_test_step = 0 #记录测试的次数
    #训练的次数
    epoch = 10
    #添加tensorboard
    writer = SummaryWriter("logs_train")

    start_time = time.time() #开始训练的时间
    for i  in range(epoch):
        print(f"------第{i+1}轮训练开始------")

        # 训练步骤开始
        tudui.train()
        for data in train_dataloader:
            imgs,targets = data
            if torch.cuda.is_available():
                imgs = imgs.cuda()
                targets = targets.cuda()
            outputs = tudui(imgs)
            loss = loss_fn(outputs,targets)

            #优化器的调优
            optimizer.zero_grad()# 梯度清零
            loss.backward()# 反向传播
            optimizer.step()# 更新优化参数

            total_train_step = total_train_step + 1 #训练次数加1
            if total_train_step % 100 == 0:# 每个一百次输出一次训练的结果
                end_time = time.time() #结束时间
                print(end_time - start_time) #计算100次训练的间隔的时间
                print(f"训练次数:{total_train_step},Loss:{loss.item()}") #记录每次训练的损失结果,item()主要就是把loss转化为真实的数,其实转化不转化都行的
                writer.add_scalar("train_loss",loss.item(),total_train_step)

        #测试步骤开始
        tudui.eval()
        total_test_loss = 0
        total_accuracy = 0
        with torch.no_grad():#防止调优,测试时不需要进行调优
            for data in test_dataloader:
                imgs , targets = data
                if torch.cuda.is_available():
                    imgs = imgs.cuda()
                    targets = targets.cuda()
                outputs = tudui(imgs)
                loss = loss_fn(outputs,targets)
                total_test_loss = total_test_loss + loss

                #计算整体的正确率
                accuracy = (outputs.argmax(1) == targets).sum()
                total_accuracy = total_accuracy + accuracy
            print(f"整体测试集上的正确率{total_accuracy/test_data_size}")
            print(f"整体测试集上的Loss:{total_test_loss}")
            writer.add_scalar("test_loss",total_test_loss,total_test_step)
            writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
            total_test_step = total_test_step + 1

        #保存模型
        torch.save(tudui,f"tudui_{i}.ph")
        #torch.save(tudui.state_dict(),f"tudui_{i}.ph")
        print("模型已保存")

    writer.close()

"""
完整的模型训练的套路
"""

#准备数据集
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time

from Model import Tudui

#定义训练的设备
# device = torch.device("cuda:0")
device =  torch.device("cuda" if torch.cuda.is_available() else "cpu")

train_data = torchvision.datasets.CIFAR10("./data",
                                          train=True,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./data",
                                          train=False,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)

#查看训练集和测试集有多少张
#length 长度
train_data_size = len(train_data) #训练集的长度
test_data_size = len(test_data) #测试集的长度
print(f"训练集的长度为{train_data_size}\n")
print(f"测试集的长度为{test_data_size}\n")

# 利用DataLoader 来加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)

#主函数
if __name__ == '__main__':
    # 创建网络模型
    tudui = Tudui()
    tudui = tudui.to(device)


    #小测试

    input = torch.ones((64,3,32,32))
    input = input.to(device)
    output = tudui(input)
    print(output.shape)
    """
    torch.Size([64, 10])
    64是代表64张照片
    10是代表10个类别,每张图片10各类别上分别的概率
    """

    # 损失函数
    loss_fn = nn.CrossEntropyLoss()
    loss_fn = loss_fn.to(device)

    #学习速率
    #1e-2=1x10^(-2)
    learning_rate = 1e-2

    # 优化器
    optimizer = torch.optim.SGD(tudui.parameters(),lr = learning_rate,)

    #设置训练网络的一些参数
    total_train_step = 0 #记录训练的次数
    total_test_step = 0 #记录测试的次数
    #训练的次数
    epoch = 10
    #添加tensorboard
    writer = SummaryWriter("logs_train")

    start_time = time.time() #开始训练的时间
    for i  in range(epoch):
        print(f"------第{i+1}轮训练开始------")

        # 训练步骤开始
        tudui.train()
        for data in train_dataloader:
            imgs,targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = tudui(imgs)
            loss = loss_fn(outputs,targets)

            #优化器的调优
            optimizer.zero_grad()# 梯度清零
            loss.backward()# 反向传播
            optimizer.step()# 更新优化参数

            total_train_step = total_train_step + 1 #训练次数加1
            if total_train_step % 100 == 0:# 每个一百次输出一次训练的结果
                end_time = time.time() #结束时间
                print(end_time - start_time) #计算100次训练的间隔的时间
                print(f"训练次数:{total_train_step},Loss:{loss.item()}") #记录每次训练的损失结果,item()主要就是把loss转化为真实的数,其实转化不转化都行的
                writer.add_scalar("train_loss",loss.item(),total_train_step)

        #测试步骤开始
        tudui.eval()
        total_test_loss = 0
        total_accuracy = 0
        with torch.no_grad():#防止调优,测试时不需要进行调优
            for data in test_dataloader:
                imgs , targets = data
                imgs = imgs.to(device)
                targets = targets.to(device)
                outputs = tudui(imgs)
                loss = loss_fn(outputs,targets)
                total_test_loss = total_test_loss + loss

                #计算整体的正确率
                accuracy = (outputs.argmax(1) == targets).sum()
                total_accuracy = total_accuracy + accuracy
            print(f"整体测试集上的正确率{total_accuracy/test_data_size}")
            print(f"整体测试集上的Loss:{total_test_loss}")
            writer.add_scalar("test_loss",total_test_loss,total_test_step)
            writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
            total_test_step = total_test_step + 1

        #保存模型
        torch.save(tudui,f"tudui_{i}.ph")
        #torch.save(tudui.state_dict(),f"tudui_{i}.ph")
        print("模型已保存")

    writer.close()

如果没有GPU怎么办呢?

没有GPU的话,我们可以使用谷歌提供colab,可能访问这个网站的话需要进行科学上网

 19.完整的模型验证套路

利用已经训练好的模型,然后给它提供测试

# -*- coding: utf-8 -*-
# 作者:小土堆
# 公众号:土堆碎念
import torch
import torchvision
from PIL import Image
from torch import nn

image_path = "../imgs/airplane.png"
image = Image.open(image_path)
print(image)
image = image.convert('RGB')
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
                                            torchvision.transforms.ToTensor()])

image = transform(image)
print(image.shape)

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64*4*4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x

model = torch.load("tudui_29_gpu.pth", map_location=torch.device('cpu'))
print(model)
image = torch.reshape(image, (1, 3, 32, 32))
model.eval()
with torch.no_grad():
    output = model(image)
print(output)

print(output.argmax(1))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/825226.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

从《信息技术服务数据中心业务连续性等级评价准则》看数据备份

​​​​​​​ 5月23日,国家标准化管理委员会与国家市场监督管理总局发布了《信息技术服务数据中心业务连续性等级评价准则》,旨在适应各行各业逐步深入的数字化转型,提升全社会对数据中心服务中断风险的重视。 信息技术服务数据中心业务连续…

KL15 是什么?ACC,crank,on等

KL含义 KL is the abbreviation for klemme which is the German term for connector / connection.KL是“ klemme”的缩写,这是德语中连接器或连接的术语。 KL30 ,通常表示电瓶的正极。positive KL31,通常表示电瓶的负极。negative KL15, 通…

【NLP概念源和流】 04-过度到RNN(第 4/20 部分)

接上文 【NLP概念源和流】 03-基于计数的嵌入,GloVe(第 3/20 部分) 一、说明 词嵌入使许多NLP任务有了显著的改进。它对单词原理图的理解以及将不同长度的文本表示为固定向量的能力使其在许多复杂的NLP任务中非常受欢迎。大多数机器学习算法可以直接应用于分类和回归任务的…

go初识iris框架(三) - 路由功能处理方式

继了解get,post后 package mainimport "github.com/kataras/iris/v12"func main(){app : iris.New()//app.Handle(请求方式,url,请求方法)app.Handle("GET","/userinfo",func(ctx iris.Context){path : ctx.Path()app.Logger().Info(path) //获…

MTS性能监控你知道多少

前言 说到MySQL的MTS,相信很多同学都不陌生,从5.6开始基于schema的并行回放,到5.7的LOGICAL_CLOCK支持基于事务的并行回放,这些内容都有文章讲解,在本篇文章不再赘述。今天要讲的是,你知道如何查看并行回放…

最新AI系统ChatGPT网站源码/支持GPT4.0/GPT联网功能/支持ai绘画/mj以图生图/支持思维导图生成

使用Nestjs和Vue3框架技术,持续集成AI能力到系统! 同步mj图片重新生成指令 同步 Vary 指令 单张图片对比加强 Vary(Strong) | Vary(Subtle) 同步 Zoom 指令 单张图片无限缩放 Zoom out 2x | Zoom out 1.5x 新增GPT联网提问功能、签到功能 一、功能演示 …

基于springboot生鲜物流系统-计算机毕设 附源码13339

springboot生鲜物流系统 摘要 生鲜产品易于腐烂、难贮存、不易长时间运输,生产者所面临的市场风险很大,很多生鲜产品无法实现“货畅其流”和“物尽其值”,适宜的生鲜产品物流体系就显得尤为重要。本文将广东省生鲜产品物流体系的构建作为一个…

删除链表中等于给定值 val 的所有节点

203. 移除链表元素 - 力扣(LeetCode) 给出链表 1->2->3->3->4->5->3, 和 val 3, 你需要返回删除3之后的链表:1->2->4->5。 分析思路:这道题的思路,与之前删除链表中重复的结点相似。 因…

腾讯云从业者认证考试考点——云网络产品

文章目录 腾讯云网络产品功能网络产品概述负载均衡(Cloud Load Balancer)私有网络(Virtual Private Cloud,VPC)专线接入弹性网卡(多网卡热插拔服务)NAT网关(NAT Gateway)…

了解 spring MVC + 使用spring MVC - springboot

前言 本篇介绍什么是spring MVC ,如何使用spring MVC,了解如何连接客户端与后端,如何从前端获取各种参数;如有错误,请在评论区指正,让我们一起交流,共同进步! 文章目录 前言1. 什么…

RD算法(四)登堂入室 —— 成像完成

SAR成像专栏目录_lightninghenry的博客-CSDN博客https://lightning.blog.csdn.net/article/details/122393577?spm=1001.2014.3001.5502先放RD算法最终的成像结果: 经简单的地距投影后为(地距投影的内容在后面的几何校正章节中讲解): 温哥华这地形还真像是一张怪兽的巨嘴呀…

商城-学习整理-基础-商品服务API-三级分类(五)

目录 一、启动之前创建的环境1、启动虚拟机2、启动mysql3、启动redis4、启动nacos5、导入三级分类测试数据 二、开发商品服务三级分类列表1、后台模块1)书写商品三级分类表后台业务逻辑 2、前端模块1)启动renren-fast前后端项目2)在系统管理-…

js逆向 - X-Zse-96分析(JsRPC实战)

本文仅供学习交流,只提供关键思路不会给出完整代码,严禁用于非法用途,若有侵权请联系我删除! 目标网站:aHR0cHM6Ly93d3cuemhpaHUuY29tLw 目标接口:aHR0cHM6Ly93d3cuemhpaHUuY29tL2FwaS92NC9zZWFyY2hfdjM …

卸载 Postman!一款 IDEA 神级插件,更便捷、高效...

Restful Fast Request 是 IDEA 版 Postman,它是一个强大的 restful api 工具包插件,可以根据已有的方法帮助您快速生成 url 和 params。 Restful Fast Request API 调试工具 API 管理工具 API 搜索工具。 它有一个漂亮的界面来完成请求、检查服务器…

Django智能养殖场管理系统

目 录 摘要 1 绪论 1.1研究背景与意义 1.2研究内容 1.3论文结构与章节安排 2 智能养殖场管理系统分析 2.1 可行性分析 2.2 系统业务流程分析 2.3 系统功能分析 2.3.1 功能性分析 2.3.2 非功能性分析 2.4 系统用例分析 2.5本章小结 3 智能养殖场管理系统总体设计 …

数据分析 VS 数据可视化:决战时刻

数据分析和数据可视化是数据科学领域中两个重要的组成部分,很多人不明白两者之间的关系,会误认为是一个东西,其实不然。本文就带大家简单了解一下它们的区别与联系吧! 数据分析是指通过收集、处理和解释数据来获取有关特定问题或…

深度学习入门 ---- 张量(Tensor)

文章目录 张量张量在深度学习领域的定义张量的基本属性使用PyTorch安装PyTorch查看安装版本 创建张量常用函数四种创建张量的方式和区别 四则运算 张量 张量在深度学习领域的定义 张量(tensor)是多维数组,目的是把向量、矩阵推向更高的维度。…

Docker中CMD和ENTRYPOINT的区别

目录 一.CMD二.ENTRYPOINT三.总结 一.CMD CMD指令为启动的容器指定默认要运行的程序,程序运行结束,容器也就结束。CMD 指令指定的程序可被 docker run 命令行参数中指定要运行的程序所覆盖。类似于 RUN 指令,用于运行程序,但二者…

Java:JDK8之后新的时间(推荐使用) LocalDate、LocalTime、LocalDataTime 的相关API

更新后的时间分类 LocalDate 的相关API //0、获取本地日期对象 LocalDate ld LocalDate.now();//年月日 system.out.println(ld) ;//1、获取日期对象中的信息 int year ld.getYear();//年 int month ld.getMonthValue(); //月(1-12) int day ld.getDayOfMonth();//日 int d…

不用下软件,三维模型就可以实现在线浏览了!

对三维有一些了解的朋友都知道,目前很多三维模型网站基本都是以2D形式展示的,用户只能通过截取不同角度的视图来查看模型。如果用户想要实现模型动态预览,只能下载其模型文件,并在对应的三维软件中打开。现在,不需要下…