一、我的环境
● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接:https://pan.baidu.com/s/1w96D-BvrmlNtBMOX3OimdQ 提取码:b3d2
二、主要代码实现
1、main.py
# -*- coding: utf-8 -*-
import torch.utils.data
from handle import *
import torch.nn as nn
from model import *
# 一、数据加载与处理
path = './data/' # 数据地址
# 把数据处理为一定尺寸 tensor
total_data = Handle().handle(path)
# 划分训练数据和测试数据的比例
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
train_data, test_data = torch.utils.data.random_split(total_data, [train_size, test_size])
# 训练和测试数据分别划分batch
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_data, batch_size=batch_size)
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
print(y)
break
# 二、模型网络构建 model.__init(), model.forward()
# 三、模型训练
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = Network_bn().to(device=device)
# 超参数设置
loss_fn = nn.CrossEntropyLoss()
learn_rate = 1e-4
opt = torch.optim.SGD(model.parameters(), lr=learn_rate)
# 模型训练
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(model, train_dl, loss_fn, opt, device)
model.eval()
epoch_test_acc, epoch_test_loss = model.test1(model, test_dl, loss_fn, device)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
template = ('Epoch:{:2d}, Train_acc: