【实验笔记】pytorch-cifar10-models

目录

1 准备阶段

1.1 环境配置

1.2 数据集cifar10

2 深度模型

2.1 模型的加载与保存

2.2 报错 & 解决办法

1 准备阶段

1.1 环境配置

【Pycharm】CUDA & Pytorch 运行 stylegan2-CSDN博客

1.2 数据集cifar10

数据集:60000个样本,每个样本都是一张32*32像素的RGB图像(彩色图像),每个RGB图像又必定分为3个通道(R通道、G通道、B通道)。这60000个样本被分成了50000个训练样本和10000个测试样本。(整个数据集被分为5个训练批次和1个测试批次,每一批10000张图片。测试批次包含10000张图片,是由每一类图片随机抽取出1000张组成的集合。剩下的50000张图片每一类的图片数量都是5000张,训练批次是由剩下的50000张图片打乱顺序,然后随机分成5份,所以可能某个训练批次中10个种类的图片数量不是对等的,会出现一个类的图片数量比另一类多的情况)
 

分类:每个样本就一定都配备了一个标签,不同类别的物体用不同的标签值。标签值分别按照0~9来区分:飞机( airplane )、汽车( automobile )、鸟( bird )、猫( cat )、鹿( deer )、狗( dog )、青蛙( frog )、马( horse )、船( ship )和卡车( truck )。

结构:

·train_x:(50000, 32, 32, 3)——训练样本
·train_y:(50000, 1)——训练样本标签
·test_x:(10000, 32, 32, 3)——测试样本
·test_y:(10000, 1)——测试样本标签

下载:官网下载链接:http://www.cs.toronto.edu/~kriz/cifar.html

可以下载这三个版本,分别是python版本、Matlab版本和C编译好的二进制版本。
在这里插入图片描述

2 深度模型

2.1 模型的加载与保存

# 下载保存
model_mobilenetv2_x0_5 = torch.hub.load("chenyaofo/pytorch-cifar-models", "cifar10_mobilenetv2_x0_5", pretrained=True, trust_repo=True)
torch.save(model_mobilenetv2_x0_5.state_dict(), 'model_mobilenetv2_x0_5_state_dict.pth')

# 加载
model = MobileNetV2(width_mult=0.5)        # 声明一个模型类
model.load_state_dict(torch.load('model_mobilenetv2_x0_5_state_dict.pth'))    # 加载参数

2.2 放到GPU计算

本来以为把环境调到conda里面就可以,实际上还要在代码里面添加“把资源放到GPU”的代码

# GPU 在文件开头添加
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Assuming that we are on a CUDA machine, this should print a CUDA device:
# print(device)

model.to(device)            # model放到GPU

inputs, labels = data[0].to(device), data[1].to(device)             # dataset放到GPU

2.3 归一化参数

    # 定义图像预处理操作
    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.4914, 0.4822, 0.4465),(0.2023, 0.1994, 0.2010))])
    batch_size = 4

2.2 报错 & 解决办法

(1)os路径导入错误

报错信息

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.

这个错误信息是由Intel的OpenMP运行时库产生的,表明你的程序中存在多个OpenMP运行时库的实例。这可能会导致性能下降或结果不正确。

解决办法1: 在文件前添加语句

import os
os.environ[“KMP_DUPLICATE_LIB_OK”]=“TRUE”

解决办法2:删除多余的文件

可以看到在环境里有两个dll文件:

把第二个放到其他地方(感觉删除也可以?不过以防万一还是备份一个吧)

(2)pytest关闭方法

由于不熟悉pytest且出现报错且不是必须要使用,本人决定关闭pytest。

文件 -> 设置 -> 工具 -> python集成工具 -> 测试 ->默认测试运行程序 -> 将pytest改成Unittest

再把右上角改一改,选成当前文件?总之不要用pytest的配置

(3)torchvision.utils.make_grid

报错信息

Traceback (most recent call last):
  File "D:\workplace\python\pytorch-cifar-models-master\models_test.py", line 37, in <module>
    plt.imshow(img_grid)  # 显示图片网格
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\_api\deprecation.py", line 459, in wrapper
    return func(*args, **kwargs)
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\pyplot.py", line 2657, in imshow
    **kwargs)
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\_api\deprecation.py", line 459, in wrapper
    return func(*args, **kwargs)
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\__init__.py", line 1414, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\axes\_axes.py", line 5487, in imshow
    im.set_data(X)
  File "D:\system\anaconda3\envs\pytorch_gpu\lib\site-packages\matplotlib\image.py", line 716, in set_data
    .format(self._A.shape))
TypeError: Invalid shape (3, 36, 138) for image data

解决办法

即torchvision.utils.make_grid的使用方法,注意需要对向量进行维度转换,转换为 PIL.Image.Image 对象,才可以显示。

# 显示图片示例
grid = torchvision.utils.make_grid(images, nrow=4, padding=2, normalize=True)
# 转换为 PIL.Image.Image 对象并显示
image_grid = Image.fromarray(grid.mul(255).permute(1, 2, 0).byte().numpy())
image_grid.show()

  • 40
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值