一、我的环境
● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接:https://pan.baidu.com/s/1gA3TXAWpil9l39wJMjwuRA 提取码:zj37
二、主要代码实现
1、main.py
# -*- coding: utf-8 -*-
import torch.utils.data
from torchvision import datasets, transforms
from model import *
# 一、加载数据并处理
train_data_path = './data/train/'
test_data_path = './data/test/'
# 加载文件夹中的数据
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.RandomHorizontalFlip(), # 随机水平翻转
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])
test_transforms = transforms.Compose([
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
train_dataset = datasets.ImageFolder(train_data_path, transform=train_transforms)
test_dataset = datasets.ImageFolder(test_data_path, transform=test_transforms)
# 将数据进行批次处理
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)
# 二、构建模型网络 model.__init__, model.forward()
# 三、模型训练
# 实例化模型
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device:'.format(device))
model = Network_fn().to(device)
# 设置参数
def adjust_learning_rate(optimizer, epoch,