加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
14-1-4测试保存模型.py 2.44 KB
一键复制 编辑 原始数据 按行查看 历史
tqychy 提交于 2022-11-18 12:12 . finish
import torch
import torch.nn as nn
import torchvision.datasets as dsets
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
from torch.autograd import Variable
import warnings
from PIL import Image
warnings.filterwarnings('ignore')
import os,sys
path = os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0] + os.path.sep
rootpath = path[:-10]
#print("validation path:" ,root)
# MNIST Dataset
test_dataset = dsets.MNIST(root='./data/',
train=False,
transform=transforms.ToTensor(),
download=False)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=100,
shuffle=True)
# CNN Model (2 conv layer)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2))
self.fc = nn.Linear(7*7*32, 10)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
cnnmodel = CNN()
cnnmodel = torch.load( rootpath + 'src/step3/cnnModel.pkl')
#/********** Begin *********/
# 将模型转为测试模式
cnnmodel.eval()
correct = 0
total = 0
i = 0
for images, labels in test_loader:
images = Variable(images)
#对images 应用cnn模型,将结果赋值给 outputs
outputs = cnnmodel(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
i += 1
# 为了节约时间, 我们测试时只测试前10个
if i> 10 :
break
#按格式输出正确率correct/total 的百分比
#/********** End *********/
#"cnnmodel.eval()","cnnmodel(images)","TestAccuracyofthemodelonthe200testimages:"
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化