pytorch模型推理单张图片读取方式

import torch
from torch import nn
from PIL import Image
from torchvision import transforms, datasets
import cv2

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, padding=1, kernel_size=3)
        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, padding=1, kernel_size=3)
        self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, padding=1, kernel_size=3)
        self.conv4 = nn.Conv2d(in_channels=128, out_channels=128, padding=1, kernel_size=3)
        self.relu = nn.ReLU()
        self.flatten = nn.Flatten()
        self.linear1 = nn.Linear(128 * 7 * 7, 512)
        self.linear2 = nn.Linear(512, 6)
        self.softmax = nn.Softmax()

    def forward(self, x):
        x = self.relu(self.conv1(x))
        x = self.pool1(x)
        x = self.relu(self.conv2(x))
        x = self.pool1(x)

        x = self.relu(self.conv3(x))
        x = self.pool1(x)
        x = self.relu(self.conv4(x))

        x = self.flatten(x)
        x = self.relu(self.linear1(x))
        y = self.linear2(x)
        return y


class_names = ['GC', 'GL', 'NL', 'RC', 'RL', 'UK']  # 这个顺序很重要,要和训练时候的类名顺序一致

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

##载入模型并读取权重
model = Net()
model.load_state_dict(torch.load("./data/detect_light.pt"))
model.to(device)
model.eval()

img_path = '/home/jwd/dataset/roi455.jpg'

#==========使用PIL进行测试的代码=====================================
transform_valid = transforms.Compose([transforms.Resize((56, 56), interpolation=2),
                                      transforms.ToTensor()])
img = Image.open(img_path)
img_ = transform_valid(img).unsqueeze(0)  # 拓展维度

#==========使用opencv读取图像的测试代码,若使用opencv进行读取,将上面(1)注释掉即可==========
# img = cv2.imread(img_path)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# img = cv2.resize(img, (56, 56))
# img_ = torch.from_numpy(img).float().permute(2, 0, 1).unsqueeze(0)/255

img_ = img_.to(device)
outputs = model(img_)

# 输出概率最大的类别
_, indices = torch.max(outputs, 1)
percentage = torch.nn.functional.softmax(outputs, dim=1)[0] * 100
perc = percentage[int(indices)].item()
result = class_names[indices]
print('predicted:', result)

# 得到预测结果,并且从大到小排序
# _, indices = torch.sort(outputs, descending=True)
# 返回每个预测值的百分数
# percentage = torch.nn.functional.softmax(outputs, dim=1)[0] * 100
# print([(class_names[idx], percentage[idx].item()) for idx in indices[0][:5]])

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch模型的大小超过张显卡的容量时,可以采用以下策略来解决: 1. 模型分割:将大型模型分割为多个较小的子模型,每个子模型最适合放入张显卡进行计算。这要求模型的架构能够容易地进行拆分和重新组合,以保持整体性能。 2. 模型并行:将模型参数划分为多个部分,并在多个显卡上进行并行计算。这样可以将计算负载分散到多个显卡上,以增加可用的显存大小。在每个显卡上运行的子模型共享参数,并通过梯度聚合来更新模型参数。 3. 内存管理:优化显存的使用,例如减少中间变量和不必要的计算。可以使用in-place操作或Tensor流水线来最小化内存占用。此外,可以手动释放不再需要的Tensor以及临时存储。 4. 混合精度计算:使用低精度的计算来减少显存占用。PyTorch支持半精度浮点数(FP16)的训练和推理,可以通过缩小参数和激活数据的精度来减少显存使用量。 5. 多个显卡使用:如果张显卡的容量无法满足需要,可以考虑使用多张显卡进行计算。PyTorch通过DataParallel和DistributedDataParallel等模块支持在多个显卡上进行并行计算,并自动处理数据切片和梯度聚合。 总之,当PyTorch模型超过张显卡容量时,我们可以采用模型分割、模型并行、内存管理、混合精度计算和多个显卡使用等策略来解决这个问题。这些策略的应用取决于具体的模型和硬件配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值