● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
● 数据来源:链接:https://pan.baidu.com/s/1w96D-BvrmlNtBMOX3OimdQ 提取码:b3d2
# -*- 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:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))
print('Done')
# 保存模型
torch.save(model.state_dict(), './model/model.pkl')
# 四、模型评估
import matplotlib.pyplot as plt
# 隐藏警告
import warnings
epoch_range = range(epochs)
warnings.filterwarnings("ignore") # 忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 # 分辨率
plt.figure(figsize=(20, 5))
plt.subplot(1, 2, 1)
plt.plot(epoch_range, train_acc, label='Training Accuracy')
plt.plot(epoch_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epoch_range, train_loss, label='Training Loss')
plt.plot(epoch_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
# -*- coding: utf-8 -*-
import torchvision.transforms as transforms
from torchvision import transforms, datasets
class Handle(object):
def __init__(self):
pass
def handle(self, path):
train_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]
)
])
total_data = datasets.ImageFolder(path, transform=train_transforms)
return total_data
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
class Network_bn(nn.Module):
def __init__(self):
super(Network_bn, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(12)
self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0)
self.bn2 = nn.BatchNorm2d(12)
self.pool = nn.MaxPool2d(2, 2)
self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
self.bn4 = nn.BatchNorm2d(24)
self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
self.bn5 = nn.BatchNorm2d(24)
self.fc1 = nn.Linear(24 * 50 * 50, 2)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = self.pool(x)
x = F.relu(self.bn4(self.conv4(x)))
x = F.relu(self.bn5(self.conv5(x)))
x = self.pool(x)
x = x.view(-1, 24 * 50 * 50)
x = self.fc1(x)
return x
def train1(self, model, dataloader, loss_fn, optimizer, device):
train_acc, train_loss = 0, 0
for X, y in dataloader:
X, y = X.to(device), y.to(device)
# 前向传播
pred = model(X)
# 求loss
loss = loss_fn(pred, y)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
size = len(dataloader.dataset)
num_batches = len(dataloader)
train_loss /= num_batches
train_acc /= size
return train_acc, train_loss
def test1(self, model, dataloader, loss_fn, device):
size = len(dataloader.dataset) # 测试集的大小,一共10000张图片
num_batches = len(dataloader) # 批次数目,313(10000/32=312.5,向上取整)
test_loss, test_acc = 0, 0
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
def prodict_one_image(self, img_path, model, transfom, classes):
test_img = Image.open(img_path).convert('RGB')
plt.imshow(test_img)
plt.show()
test_img = transfom(test_img)
img = test_img.unsqueeze(0) # 模型的预测需要4维,增加一个维度
model.eval() # 取消归一化以及dropout等操作
output = model(img)
pred = torch.max(output, 1)
index = pred[1].item()
pred_class = classes[index]
return pred_class
# -*- coding: utf-8 -*-
import torch
import torchvision.transforms as transforms
from model import *
# 加载模型
model = Network_bn()
model.load_state_dict(torch.load('./model/model.pkl', map_location=torch.device('cpu')))
# 预测结果
train_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]
)
])
classes = ['Monkeypox', 'Others']
result1 = model.prodict_one_image(img_path='./data/Monkeypox/M01_01_05.jpg', model=model, transfom=train_transforms, classes=classes)
print(result1)
result2 = model.prodict_one_image(img_path='./data/Monkeypox/M01_01_13.jpg', model=model, transfom=train_transforms, classes=classes)
print(result2)
result3 = model.prodict_one_image(img_path='./data/Others/NM01_01_07.jpg', model=model, transfom=train_transforms, classes=classes)
print(result3)
result4 = model.prodict_one_image(img_path='./data/Others/NM03_01_00.jpg', model=model, transfom=train_transforms, classes=classes)
print(result4)
由于在本地跑20个epoch太慢了,所以就在带GPU的服务器上跑的,在dorcker里面下载了对应的依赖包
刚开始一直出现下面的错误
RuntimeError: CUDA error: no kernel image is available for execution on the device
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below mi
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
网上查说是cuda版本和torch的版本不匹配,我的cuda是11.6 要适配torch 1.12.0
尝试了一些方式查看,进入python bash
>>> import torch
>>> print(torch.__version__) # 打印结果1.12.1+cu102,但是从pytorch官网上看应该要是cu116才对
>>> torch.cuda.is_available() # 返回是True
>>> torch.randn(3, 5) # 构建一个tensor,看cuda能不能用
>>> t = torch.cuda() # 打印上面的CUDA error: no kernel image is available for execution on the device错误
卸载torch, pip uninstall torch
把pytorch官网的命令重新跑一遍,pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116
再 python bash
>>> import torch
>>> print(torch.__version__) # 打印结果1.12.1+cu116
。。。
后续命令均正常执行
跑模型,问题得到解决