-
大小: 8KB文件类型: .py金币: 1下载: 0 次发布日期: 2023-07-19
- 语言: Python
- 标签: vgg16 pytorchvgg16
资源简介
pytorch1.5实现的vgg16分类。在真实数据集测试成功
pytorch1.5实现的vgg16分类。在真实数据集测试成功
pytorch1.5实现的vgg16分类。在真实数据集测试成功
代码片段和文件信息
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import torch
import numpy as np
from torch import nn
from torch import optim
from torch.autograd import Variable
from torchvision import datasetstransformsmodels
import seaborn as sb
from collections import OrderedDict
class classifier():
def __init__(self):
# 设置数据目录
self.train_dir = ‘smoke_clas/train‘
self.valid_dir = ‘smoke_clas/valid‘
self.test_dir = ‘smoke_clas/test‘
#使用dataloader数据,验证模型的准确率
def accuracy_valid(self modeldataloader):
correct = 0
total = 0
model.cuda() # 将模型放入GPU计算,能极大加快运算速度
with torch.no_grad(): # 使用验证集时关闭梯度计算
for data in dataloader:
imageslabels = data
imageslabels = images.to(‘cuda‘)labels.to(‘cuda‘)
outputs = model(images)
_ predicted = torch.max(outputs.data1)
# torch.max返回输出结果中,按dim=1行排列的每一行最大数据及他的索引,丢弃数据,保留索引
total += labels.size(0)
correct += (predicted == labels).sum().item()
#将预测及标签两相同大小张量逐一比较各相同元素的个数
print(‘the accuracy is {:.4f}‘.format(correct/total))
def accuracy_test(self modeldataloader):
correct = 0
total = 0
model.cuda() # 将模型放入GPU计算,能极大加快运算速度
with torch.no_grad(): # 使用验证集时关闭梯度计算
for data in dataloader:
imageslabels = data
imageslabels = images.to(‘cuda‘)labels.to(‘cuda‘)
print(‘label:‘labels)
outputs = model(images)
probs= []
classes = []
#print(outputs.data)
a = outputs[0] # 返回TOPK函数截取的排名前列的结果列表a
b = outputs[1].tolist() #返回TOPK函数截取的排名前列的概率索引列表b
print(‘----------------‘)
print(‘a:‘a[0])
print(‘b:‘b[0])
for i in a:
print(torch.exp(i).tolist())
probs.append(torch.exp(i).tolist()) #将结果转化为实际概率
for n in b:
classes.append(str(n+1)) # 将索引转化为实际编号
print(classes)
print(probs)
_ predicted = torch.max(outputs.data1)
print(‘label:‘labels)
print(‘predicted:‘predicted)
#print(predicted)
def deep_learning(self modeltrainloaderepochsprint_everycriterionoptimizerdevicevalidloader):
epochs = epochs #设置学习次数
print_every = print_every
steps = 0
model.to(device)
for e in range(epochs):
running_loss = 0
for ii (inputslabels) in enumerate(trainloader):
steps += 1
#inputs表示输入的数据,labels表示每个数据对应的真实分类标签
inputslabels = inputs.to(device)lab
- 上一篇:计算机视觉素材.part1.rar
- 下一篇:PYTHON自然语言处理_超高清pdf
评论
共有 条评论