数据:链接:https://pan.baidu.com/s/1ZH3T22IP3S34Am1uj2UERw
提取码:jqna
复制这段内容后打开百度网盘手机App,操作更方便哦
一、自己写的网络
1、CPU运行代码
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import numpy as np
# 数据预处理
transform = transforms.Compose([
transforms.RandomResizedCrop(40), # 对图像进行随机的crop以后再resize成固定大小
transforms.RandomRotation(20), # 随机旋转角度
transforms.RandomHorizontalFlip(p=0.5), # 随机水平翻转
transforms.ToTensor()
])
# 读取数据
root = 'image'
train_dataset = datasets.ImageFolder(root + '/train', transform)
test_dataset = datasets.ImageFolder(root + '/test', transform)
# 导入数据
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=10, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=10, shuffle=True)
classes = train_dataset.classes
classes_index = train_dataset.class_to_idx
print(classes)
print(classes_index)
# 定义网络结构
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3,32,5,1,2),nn.ReLU(),nn.MaxPool2d(2,2))
self.conv2 = nn.Sequential(nn.Conv2d(32,64,5,1,2),nn.ReLU(),nn.MaxPool2d(2,2))
self.fc1 = nn.Sequential(nn.Linear(64*10*10,1000),nn.Dropout(p=0.5),nn.ReLU())
##64*7*7:表示64个7*7的特征图,1000表示全连接层神经元数
self.fc2 = nn.Sequential(nn.Linear(1000, 7), nn.Softmax(dim=1))
def forward(self, x):
# ([64, 1, 28, 28])
x = self.conv1(x) #卷积输入是四维的数据
x = self.conv2(x)
# ([64, 64, 7, 7])->(64,3136)
x = x.view(x.size()[0],-1) ##全连接输入是两维的数据
x = self.fc1(x)
x = self.fc2(x)
return x
LR = 0.0001
# 定义模型
model = Net()
# 定义代价函数
entropy_loss = nn.CrossEntropyLoss()
# 定义优化器
optimizer = optim.Adam(model.parameters(), LR)
def train():
model.train()
for i, data in enumerate(train_loader):
# 获得数据和对应的标签
inputs, labels = data
# 获得模型预测结果,(64,10)
out = model(inputs)
# 交叉熵代价函数out(batch,C),labels(batch)
loss = entropy_loss(out, labels)
# 梯度清0
optimizer.zero_grad()
# 计算梯度
loss.backward()
# 修改权值
optimizer.step()
##把准确率传入列表最后画图
testacc = []
trainacc = []
Epoch = []
def test():
model.eval()
correct = 0
for i, data in enumerate(test_loader):
# 获得数据和对应的标签
inputs, labels = data
# 获得模型预测结果
out = model(inputs)
# 获得最大值,以及最大值所在的位置
_, predicted = torch.max(out, 1)
# 预测正确的数量
correct += (predicted == labels).sum()
print("Test acc: {0}".format(correct.item() / len(test_dataset)))
testacc.append(correct.item() / len(test_dataset))
correct = 0
for i, data in enumerate(train_loader):
# 获得数据和对应的标签
inputs, labels = data
# 获得模型预测结果
out = model(inputs)
# 获得最大值,