pytorch learning: training

2023-12-14

1. 损失函数与反向传播

1.1 损失函数(loss function)

损失函数:判断模型训练的好坏标准,你训练了模型,总得有个指标来说明它好不好吧.jpg

import torch

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 = torch.nn.L1Loss(reduction='sum')
result = loss(inputs, targets)
print(result)
# 平方差
loss_mse = torch.nn.MSELoss()
result = loss_mse(inputs, targets)
print(result)

# 交叉熵
x = torch.tensor([0.1, 0.2, 0.3])
y = torch.tensor([1])
x = torch.reshape(x, [1, 3])
loss_cross = torch.nn.CrossEntropyLoss()
result = loss_cross(x, y)
print(result)

1.2 反向传播(backward)

反向传播:根据损失函数,反向传播计算梯度,然后更新参数,使得损失函数最小化

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

diy_transform = transforms.Compose([transforms.ToTensor()])
dataset = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=diy_transform, download=False)
dataloader = DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0, drop_last=False)
writer = SummaryWriter(log_dir="logs")


class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool1 = torch.nn.MaxPool2d(kernel_size=2)
        self.conv2 = torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool2 = torch.nn.MaxPool2d(kernel_size=2)
        self.conv3 = torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool3 = torch.nn.MaxPool2d(kernel_size=2)
        self.flattern = torch.nn.Flatten()
        self.linear1 = torch.nn.Linear(in_features=1024, out_features=64)
        self.linear2 = torch.nn.Linear(in_features=64, out_features=10)
        self.model1 = torch.nn.Sequential(torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Flatten(),
                                          torch.nn.Linear(in_features=1024, out_features=64),
                                          torch.nn.Linear(in_features=64, out_features=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.flattern(x)
        # x = self.linear1(x)
        # x = self.linear2(x)
        x = self.model1(x)
        return x


wsxk = Wsxk()
loss = nn.CrossEntropyLoss()
for data in dataloader:
    imgs, targets = data
    outputs = wsxk(imgs)
    print(outputs)
    print(targets)
    result_loss = loss(outputs, targets)
    print(result_loss)
    result_loss.backward() #反向传播

2. 优化器torch.optim

优化器:根据梯度更新参数,使得损失函数最小化

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

diy_transform = transforms.Compose([transforms.ToTensor()])
dataset = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=diy_transform, download=False)
dataloader = DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0, drop_last=False)
writer = SummaryWriter(log_dir="logs")


class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool1 = torch.nn.MaxPool2d(kernel_size=2)
        self.conv2 = torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool2 = torch.nn.MaxPool2d(kernel_size=2)
        self.conv3 = torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2, dilation=1)
        self.maxpool3 = torch.nn.MaxPool2d(kernel_size=2)
        self.flattern = torch.nn.Flatten()
        self.linear1 = torch.nn.Linear(in_features=1024, out_features=64)
        self.linear2 = torch.nn.Linear(in_features=64, out_features=10)
        self.model1 = torch.nn.Sequential(torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2, dilation=1),
                                          torch.nn.MaxPool2d(kernel_size=2),
                                          torch.nn.Flatten(),
                                          torch.nn.Linear(in_features=1024, out_features=64),
                                          torch.nn.Linear(in_features=64, out_features=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.flattern(x)
        # x = self.linear1(x)
        # x = self.linear2(x)
        x = self.model1(x)
        return x


wsxk = Wsxk()
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(wsxk.parameters(), lr=0.01)
# 训练模型 20轮
for epoch in range(20):
    running_loss = 0.0
    # 每一轮
    for data in dataloader:
        imgs, targets = data
        outputs = wsxk(imgs)
        result_loss = loss(outputs, targets)
        optim.zero_grad()
        result_loss.backward()
        optim.step()
        # print(result_loss)
        running_loss += result_loss
    print(running_loss)

3. 现有模型的使用以及修改

读作现有模型的使用与修改,写作炼丹
现有模型一般都集成在了库里,例如torchvision就集成了计算机视觉的一些现有模型,可供使用

import torch
from torch import nn
import torchvision
from torchvision import transforms
# 更改预训练模型的下载文件目录
import os
os.environ["TORCH_HOME"] = "C:/Users/11029/Documents/PythonProject/torchvision_dataset"

transform_diy = transforms.Compose([transforms.ToTensor()])
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, download=False)
# 没有经过预训练的模型
vgg16_false = torchvision.models.vgg16()
# 经过预训练的模型
vgg16_true = torchvision.models.vgg16(weights=torchvision.models.VGG16_Weights.IMAGENET1K_V1)
print(vgg16_true)

# 在现有模型下添加一层,所谓炼丹
vgg16_true.add_module("add_linear", module=nn.Linear(in_features=1000, out_features=10))
# vgg16_true.classifier.add_module("add_linear", module=nn.Linear(in_features=1000, out_features=10))
print(vgg16_true)

# 在现有模型的层数上做替换
vgg16_false.classifier[6] = nn.Linear(in_features=1000, out_features=10)
print(vgg16_false)

4. 现有模型的保存以及加载

import torch
import torchvision

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

# 保存方式2,只保持参数,不保存结构
torch.save(vgg16.state_dict(), "vgg16_method2.pth")

注意,在使用方式二保存模型时,必须确保加载时模型的定义(即类的定义能被访问到),否则会报错

import torch
import torchvision

# 使用方式1 模型结构+参数
model = torch.load("vgg16_method1.pth")
# print(model)

# 使用方式2 参数(官方推荐)
model2 = torch.load("vgg16_method2.pth")
vgg16 = torchvision.models.vgg16()
vgg16.load_state_dict(model2)
print(vgg16)

5. 模型的训练与测试

5.1 version 1

import torch
import torchvision
from torch.utils.data import DataLoader
from torch import nn

# 准备数据集
transorm_diy = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, transform=transorm_diy, download=True)
test_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=transorm_diy, download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练集的长度为 {}".format(train_data_size))
print("测试集的长度为 {}".format(test_data_size))

# 加载数据集
train_dataloader = DataLoader(dataset=train_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)
test_dataloader = DataLoader(dataset=test_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)


# 搭建神经网络
class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=64*4*4, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

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


# 创建模型
wsxk = Wsxk()

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

# 优化器 随机梯度下降
learning_rate = 1e-2
optimizer = torch.optim.SGD(params=wsxk.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 记录训练论述
epoch = 10

for i in range(epoch):
    print("----------第 {} 轮训练开始----------".format(i+1))
    # 训练步骤开始
    for data in train_dataloader:
        imgs, targets = data
        outputs = wsxk(imgs)
        loss = loss_fn(outputs, targets)
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_train_step += 1
        print("训练次数: {}, loss: {}".format(total_train_step, loss.item()))

# if __name__ == "__main__":
#     wsxk = Wsxk()
#     input = torch.ones(64, 3, 32, 32)
#     output = wsxk(input)
#     print(output.shape)

5.2 version 2

在version 1的基础上进行测试,得到version 2

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

# 准备数据集
transorm_diy = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, transform=transorm_diy, download=True)
test_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=transorm_diy, download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练集的长度为 {}".format(train_data_size))
print("测试集的长度为 {}".format(test_data_size))

# 加载数据集
train_dataloader = DataLoader(dataset=train_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)
test_dataloader = DataLoader(dataset=test_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)


# 搭建神经网络
class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=64*4*4, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

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


# 创建模型
wsxk = Wsxk()

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

# 优化器 随机梯度下降
learning_rate = 1e-2
optimizer = torch.optim.SGD(params=wsxk.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 记录训练论述
epoch = 10

# 画图
writer = SummaryWriter(log_dir="logs")

for i in range(epoch):
    print("----------第 {} 轮训练开始----------".format(i+1))
    # 训练步骤开始
    for data in train_dataloader:
        imgs, targets = data
        outputs = wsxk(imgs)
        loss = loss_fn(outputs, targets)
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_train_step += 1
        if total_train_step % 100 == 0:
            print("训练次数: {}, loss: {}".format(total_train_step, loss.item()))
            writer.add_scalar("train_loss", loss.item(), total_train_step)  # 两条线,深色曲线:平滑处理 浅色曲线:真实曲线

    # 测试步骤开始
    total_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            outputs = wsxk(imgs)
            loss = loss_fn(outputs, targets)
            total_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy
    total_test_step += 1
    print("第{}次整体测试集合上的loss:{}".format(total_test_step, total_loss))
    print("第{}次整体测试集合的正确率:{}".format(total_test_step, total_accuracy/test_data_size))
    writer.add_scalar("total_test_loss", total_loss, total_test_step)
    writer.add_scalar("total_accuracy_rate", total_accuracy/test_data_size,total_test_step)

    # 保存训练一次的模型
    torch.save(wsxk, "model_save/wsxk_{}.pth".format(i))
writer.close()

# if __name__ == "__main__":
#     wsxk = Wsxk()
#     input = torch.ones(64, 3, 32, 32)
#     output = wsxk(input)
#     print(output.shape)

5.3 version 3

有些细节需要注意,有的代码会在测试步骤开始前调用eval(),在训练步骤开始前会调用train(),这两个函数的作用还是相对较少的,一般只对Dropout层和BatchNorm层有作用

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

# 准备数据集
transorm_diy = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, transform=transorm_diy, download=True)
test_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=transorm_diy, download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练集的长度为 {}".format(train_data_size))
print("测试集的长度为 {}".format(test_data_size))

# 加载数据集
train_dataloader = DataLoader(dataset=train_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)
test_dataloader = DataLoader(dataset=test_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)


# 搭建神经网络
class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=64*4*4, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

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


# 创建模型
wsxk = Wsxk()

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

# 优化器 随机梯度下降
learning_rate = 1e-2
optimizer = torch.optim.SGD(params=wsxk.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 记录训练论述
epoch = 10

# 画图
writer = SummaryWriter(log_dir="logs")

for i in range(epoch):
    print("----------第 {} 轮训练开始----------".format(i+1))
    # 训练步骤开始
    wsxk.train()
    for data in train_dataloader:
        imgs, targets = data
        outputs = wsxk(imgs)
        loss = loss_fn(outputs, targets)
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_train_step += 1
        if total_train_step % 100 == 0:
            print("训练次数: {}, loss: {}".format(total_train_step, loss.item()))
            writer.add_scalar("train_loss", loss.item(), total_train_step)  # 两条线,深色曲线:平滑处理 浅色曲线:真实曲线

    # 测试步骤开始
    wsxk.eval()
    total_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            outputs = wsxk(imgs)
            loss = loss_fn(outputs, targets)
            total_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy
    total_test_step += 1
    print("第{}次整体测试集合上的loss:{}".format(total_test_step, total_loss))
    print("第{}次整体测试集合的正确率:{}".format(total_test_step, total_accuracy/test_data_size))
    writer.add_scalar("total_test_loss", total_loss, total_test_step)
    writer.add_scalar("total_accuracy_rate", total_accuracy/test_data_size,total_test_step)

    # 保存训练一次的模型
    torch.save(wsxk, "model_save/wsxk_{}.pth".format(i))
writer.close()

# if __name__ == "__main__":
#     wsxk = Wsxk()
#     input = torch.ones(64, 3, 32, 32)
#     output = wsxk(input)
#     print(output.shape)

5.4 version 4:利用GPU加速训练: 方式一

其实刚刚的训练代码中,没有使用cuda进行加速
使用cuda进行加速的方法其实很简单,方式一:只要对模型,模型的输入和标注,损失函数进行.cuda()即可。
使用GPU进行运算,你会发现运算快了很多,肉眼可见的加速

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

# 准备数据集
transorm_diy = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, transform=transorm_diy, download=True)
test_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=transorm_diy, download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练集的长度为 {}".format(train_data_size))
print("测试集的长度为 {}".format(test_data_size))

# 加载数据集
train_dataloader = DataLoader(dataset=train_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)
test_dataloader = DataLoader(dataset=test_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)


# 搭建神经网络
class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=64*4*4, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

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


# 创建模型
wsxk = Wsxk()
if torch.cuda.is_available():
    wsxk = wsxk.cuda()  # cuda 利用GPU加速模型运算

# 损失函数
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
    loss_fn = loss_fn.cuda()  # cuda 利用GPU加速损失函数计算

# 优化器 随机梯度下降
learning_rate = 1e-2
optimizer = torch.optim.SGD(params=wsxk.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 记录训练论述
epoch = 10

# 画图
writer = SummaryWriter(log_dir="logs")

for i in range(epoch):
    print("----------第 {} 轮训练开始----------".format(i+1))
    # 训练步骤开始
    wsxk.train()
    for data in train_dataloader:
        imgs, targets = data
        # 利用cuda加速imgs,targets 喂入模型
        if torch.cuda.is_available():
            imgs = imgs.cuda()
            targets = targets.cuda()
        outputs = wsxk(imgs)
        loss = loss_fn(outputs, targets)
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_train_step += 1
        if total_train_step % 100 == 0:
            print("训练次数: {}, loss: {}".format(total_train_step, loss.item()))
            writer.add_scalar("train_loss", loss.item(), total_train_step)  # 两条线,深色曲线:平滑处理 浅色曲线:真实曲线

    # 测试步骤开始
    wsxk.eval()
    total_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            # 利用cuda加速imgs, targets 喂入模型
            if torch.cuda.is_available():
                imgs = imgs.cuda()
                targets = targets.cuda()
            outputs = wsxk(imgs)
            loss = loss_fn(outputs, targets)
            total_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy
    total_test_step += 1
    print("第{}次整体测试集合上的loss:{}".format(total_test_step, total_loss))
    print("第{}次整体测试集合的正确率:{}".format(total_test_step, total_accuracy/test_data_size))
    writer.add_scalar("total_test_loss", total_loss, total_test_step)
    writer.add_scalar("total_accuracy_rate", total_accuracy/test_data_size,total_test_step)

    # 保存训练一次的模型
    torch.save(wsxk, "model_save/wsxk_{}.pth".format(i))
writer.close()

# if __name__ == "__main__":
#     wsxk = Wsxk()
#     input = torch.ones(64, 3, 32, 32)
#     output = wsxk(input)
#     print(output.shape)

5.5 version 5:利用GPU加速训练: 方式二

第二种办法是定义一个device,然后将模型,模型的输入和标注,损失函数,都放到device上,这样就可以利用GPU加速了

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

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

# 准备数据集
transorm_diy = torchvision.transforms.ToTensor()
train_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=True, transform=transorm_diy, download=True)
test_data = torchvision.datasets.CIFAR10(root="torchvision_dataset", train=False, transform=transorm_diy, download=True)
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练集的长度为 {}".format(train_data_size))
print("测试集的长度为 {}".format(test_data_size))

# 加载数据集
train_dataloader = DataLoader(dataset=train_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)
test_dataloader = DataLoader(dataset=test_data, batch_size=64, shuffle=False, num_workers=0, drop_last=False)


# 搭建神经网络
class Wsxk(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),
            nn.MaxPool2d(kernel_size=2),
            nn.Flatten(),
            nn.Linear(in_features=64*4*4, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

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


# 创建模型
wsxk = Wsxk()
wsxk = wsxk.to(device)  # cuda 利用GPU加速模型运算

# 损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)  # cuda 利用GPU加速损失函数计算

# 优化器 随机梯度下降
learning_rate = 1e-2
optimizer = torch.optim.SGD(params=wsxk.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练次数
total_train_step = 0
# 记录测试次数
total_test_step = 0
# 记录训练论述
epoch = 10

# 画图
writer = SummaryWriter(log_dir="logs")

for i in range(epoch):
    print("----------第 {} 轮训练开始----------".format(i+1))
    # 训练步骤开始
    wsxk.train()
    for data in train_dataloader:
        imgs, targets = data
        # 利用cuda加速imgs,targets 喂入模型
        imgs = imgs.to(device)
        targets = targets.to(device)

        outputs = wsxk(imgs)
        loss = loss_fn(outputs, targets)
        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_train_step += 1
        if total_train_step % 100 == 0:
            print("训练次数: {}, loss: {}".format(total_train_step, loss.item()))
            writer.add_scalar("train_loss", loss.item(), total_train_step)  # 两条线,深色曲线:平滑处理 浅色曲线:真实曲线

    # 测试步骤开始
    wsxk.eval()
    total_loss = 0
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            # 利用cuda加速imgs, targets 喂入模型
            imgs = imgs.to(device)
            targets = targets.to(device)

            outputs = wsxk(imgs)
            loss = loss_fn(outputs, targets)
            total_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy += accuracy
    total_test_step += 1
    print("第{}次整体测试集合上的loss:{}".format(total_test_step, total_loss))
    print("第{}次整体测试集合的正确率:{}".format(total_test_step, total_accuracy/test_data_size))
    writer.add_scalar("total_test_loss", total_loss, total_test_step)
    writer.add_scalar("total_accuracy_rate", total_accuracy/test_data_size,total_test_step)

    # 保存训练一次的模型
    torch.save(wsxk, "model_save/wsxk_{}.pth".format(i))
writer.close()

# if __name__ == "__main__":
#     wsxk = Wsxk()
#     input = torch.ones(64, 3, 32, 32)
#     output = wsxk(input)
#     print(output.shape)