数据集下载地址:
链接:https://pan.baidu.com/s/1l1AnBgkAAEhh0vI5_loWKw
提取码:2xq4
创建数据集:https://cloud.tencent.com/developer/article/1686281
读取数据集:https://cloud.tencent.com/developer/article/1686162
进行训练:https://cloud.tencent.com/developer/article/1686203
保存模型并继续进行训练:https://cloud.tencent.com/developer/article/1686210
加载保存的模型并测试:https://cloud.tencent.com/developer/article/1686223
划分验证集并边训练边验证:https://cloud.tencent.com/developer/article/1686224
使用学习率衰减策略并边训练边测试:https://cloud.tencent.com/developer/article/1686225
利用tensorboard可视化训练和测试过程:https://cloud.tencent.com/developer/article/1686238
从命令行接收参数:https://cloud.tencent.com/developer/article/1686240
使用top1和top5准确率来衡量模型:https://cloud.tencent.com/developer/article/1686244
使用预训练的resnet18模型:https://cloud.tencent.com/developer/article/1686248
计算数据集的平均值和方差:https://cloud.tencent.com/developer/article/1686271
读取数据集的第二种方式:https://cloud.tencent.com/developer/article/1686278
epoch、batchsize、step之间的关系:https://cloud.tencent.com/developer/article/1686123
首先我们上传一些图片到image文件夹中:
然后我们画出这些图片看看是什么样子:
import cv2
import matplotlib.pyplot as plt
import glob
# 使用matplotlib展示多张图片
def matplotlib_multi_pic1():
i=0
for img in glob.glob('/content/drive/My Drive/colab notebooks/image/*.jpg'):
img_name=img.split("/")[-1]
img = cv2.imread(img)
title=img_name
#行,列,索引
plt.subplot(3,3,i+1)
plt.imshow(img)
plt.title(title,fontsize=8)
plt.xticks([])
plt.yticks([])
i+=1
plt.show()
matplotlib_multi_pic1()
接着在test文件夹中新建一个test_from_image.py。
import torchvision
import sys
import torch
import torch.nn as nn
from PIL import Image
sys.path.append("/content/drive/My Drive/colab notebooks")
import glob
import numpy as np
import torchvision.transforms as transforms
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model=torchvision.models.resnet18(pretrained=False)
model.fc = nn.Linear(model.fc.in_features,2,bias=False)
model.to(device)
model.eval()
save_path="/content/drive/My Drive/colab notebooks/output/resnet18_best.t7"
checkpoint = torch.load(save_path)
model.load_state_dict(checkpoint['model'])
print("当前模型准确率为:",checkpoint["epoch_acc"])
images_path="/content/drive/My Drive/colab notebooks/image/"
transform = transforms.Compose([transforms.Resize((224,224))])
def predict():
true_labels=[]
output_labels=[]
for image in glob.glob(images_path+"/*.jpg"):
print(image)
if "cat" in image.split("/")[-1]:
tmp=0
else:
tmp=1
true_labels.append(tmp)
image=Image.open(image)
image=image.resize((224,224))
tensor=torch.from_numpy(np.asarray(image)).permute(2,0,1).float()/255.0
print(tensor.shape)
tensor=tensor.reshape((1,3,224,224))
tensor=tensor.to(device)
#print(tensor.shape)
output=model(tensor)
print(output)
_, pred = torch.max(output.data,1)
output_labels.append(pred.item())
return true_labels,output_labels
true_labels,output_labels=predict()
print("正确的标签是:")
print(true_labels)
print("预测的标签是:")
print(output_labels)
说明:这里需要注意的地方有:
结果:
下一节,可视化相应的特征图。