一、我的环境:
● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接: https://pan.baidu.com/s/1SEfd8mvWt7BpzmWOeaIRkQ 提取码: gdie
二、主要代码实现
1、main.py
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import torch.utils.data
from model import *
from handle import *
# 一、数据处理 headle.py
# 1、加载数据
path = './data/'
headle = Handle(path)
total_data = headle.handle()
# 2、划分数据集
train_size = int(0.8 * len(total_data)) # 80%用来做训练数据
test_size = len(total_data) - train_size # 20%用来做测试数据
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size]) # 按比例随机划分数据
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
# 二、网络构建 model().__init__ model.forward()
# 三、模型训练 model.train()
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = Network_bn().to(device)
# 1、设置模型参数
loss_fn = nn.CrossEntropyLoss() # 损失函数
learn_rate = 1e-4 # 学习率
opt = torch.optim.SGD(model.parameters(), lr=learn_rate)
# 2、训练函数 model.train1()
# 3、测试函数 model.test1()
# 4、模型训练
epochs = 20
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = model.train1(train_dl, model, loss_fn, opt, device)
model.eval()
epoch_test_acc, epoch_test_loss = model.test(test_dl, model, loss_fn, device)
train_loss.append(epoch_train_loss)
train_