P37微调 parcharm运行

 本文如有问题还请指正,自己也是很多东西还不知道,可能有些东西是瞎调出来的并不正确

看完微调后,心潮澎湃,自己能站在巨人的肩膀上。之前自己用alexnet训练的500轮了也只有68的正确率,这次用微调第一轮就有74,十分开心。

训练模型代码

#准备数据集
import torch
import torchvision.transforms
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from PIL import Image

#判断gpu是否可用
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
#创建模型
#导入resnet模型,pretrained=True以自动下载预训练的模型参数
pretrained_net = torchvision.models.resnet18(pretrained=True)
finetune_net = torchvision.models.resnet18(pretrained=True)
#最后数字为模型的输出分类数
finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 3)

nn.init.xavier_uniform_(finetune_net.fc.weight)

bao = finetune_net.to(device)

#resnet18里进行了这样的transform,我们也这样使用
normalize = torchvision.transforms.Normalize(
    [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

train_transform = torchvision.transforms.Compose([
    torchvision.transforms.RandomResizedCrop(224),
    torchvision.transforms.RandomHorizontalFlip(),
    torchvision.transforms.ToTensor(),
    normalize])

test_transform = torchvision.transforms.Compose([
    torchvision.transforms.Resize(256),
    torchvision.transforms.CenterCrop(224),
    torchvision.transforms.ToTensor(),
    normalize])
#准备数据
train_data = datasets.ImageFolder(root=r"E:\2022autumn\123\data\train",transform=train_transform)
test_data = datasets.ImageFolder(root=r"E:\2022autumn\123\data\test",transform=test_transform)

#length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集的长度为:{}".format(train_data_size))
print("测试数据集的长度为:{}".format(test_data_size))

#利用dataloader来加载数据集
train_dataloader = torch.utils.data.DataLoader(train_data,batch_size=32,shuffle=True)
test_dataloader = torch.utils.data.DataLoader(test_data,batch_size=32,shuffle=True)

#损失函数0
loss_fun = nn.CrossEntropyLoss()
loss_fun = loss_fun.to(device)
#优化器
learning_rate = 0.001
optimizer = torch.optim.SGD(bao.parameters(),lr=learning_rate)


#设置训练网络的一些参数
#训练次数
total_train_step = 0
#测试次数
total_test_step = 0
#训练轮次
epoch =500
#添加tensorboard
writer = SummaryWriter("./logs")
#最大正确率
max_accuary = 0
maxi = 0

for i in range(epoch):
    print("-----第{}轮训练开始----".format(i+1))
    #保存模型标签
    max_flag = 0
    #开始训练
    bao.train()#可写可不写,看官方文档
    for data in train_dataloader:#加个tqdm可以显示进度条
        imgs,targets = data
        imgs = imgs.to(device)
        targets = targets.to(device)
        outputs = bao(imgs)
        loss = loss_fun(outputs,targets)
        #优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 ==0:
            print("训练次数:{},loss:{}".format(total_train_step, loss.item()))#加个item(),输出时为数字,不会有个tensor
            writer.add_scalar("train_loss",loss.item(),total_train_step)

    #测试步骤开始
    bao.eval()#可写可不写
    total_test_loss = 0
    total_accuracy = 0

    with torch.no_grad():
        for data in test_dataloader:
            imgs,targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = bao(imgs)
            loss = loss_fun(outputs,targets)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy

    if (total_accuracy.item() / test_data_size) > max_accuary:
        max_accuary = (total_accuracy.item() / test_data_size)
        maxi = i
        max_flag = 1
    writer.add_scalar("test_loss", total_test_loss, total_test_step)
    writer.add_scalar("test_accuary", total_accuracy.item() / test_data_size, total_test_step)
    print("整体测试集上的loss:{}".format(total_test_loss))
    print("整体测试集上的正确率:{}".format(total_accuracy.item() / test_data_size))
    print("最大正确率:{},最大正确率轮次{}".format(max_accuary, maxi+1))
    total_test_step += 1

    #保存模型
    if max_flag:
        torch.save(bao,"bao{}.pth".format(i+1))
        print("模型已保存")
writer.close()

最终结果训练到了93正确率

本地验证效果

import torch
import torchvision.transforms
from PIL import Image
from torch import nn

img_path = "./imgs/蓝月亮.jpg"
image =Image.open(img_path)
print(image)

#png 图片有4个通道,还有一个透明通道,要转化为三个
image = image.convert('RGB')
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((224,224)),
                                            torchvision.transforms.ToTensor()])

image = transform(image)
print(image.shape)

#加载模型
#创建模型
# #导入resnet模型,pretrained=True以自动下载预训练的模型参数
# pretrained_net = torchvision.models.resnet18(pretrained=True)
# finetune_net = torchvision.models.resnet18(pretrained=True)
# #最后数字为模型的输出分类数
# finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 3)
#
# nn.init.xavier_uniform_(finetune_net.fc.weight)

#保存模型的名字
model1 = torch.load("./0.93resnet18.pth",map_location=torch.device('cpu'))
image = torch.reshape(image,(1,3,224,224))
model1.eval()
with torch.no_grad():
    output = model1(image)
print(output)
print(output.argmax(1))
taget = ["易拉罐","塑料瓶","啤酒瓶"]
print(taget[output.argmax(1).item()])

最后自己拍了几个图片放进去都还不错

P37微调 parcharm运行_第1张图片P37微调 parcharm运行_第2张图片

P37微调 parcharm运行_第3张图片

你可能感兴趣的:(动手学习深度学习,深度学习,pytorch,python)