resnet的model的output,有正有负,怎么得出各种类的概率 及 tensor大小查看-索引——softmax——tensor最大位置torch.argmax

仅作为记录,大佬请跳过。

神经网络的output有正有负的解决

感谢师兄的提示,在output后用softmax

print(outputs)
print(outputs.shape)

import torch.nn as nn
m=nn.Softmax(dim=1)
outputs_softmax=m(outputs)
print('outputs_softmax:',outputs_softmax)
print('outputs_softmax[0][1]',outputs_softmax[0][1])

在这里插入图片描述

tensor大小查看

.shape

在这里插入图片描述

tensor索引

在这里插入图片描述

*********************

tensor的nn.softmax示例

可参考博主文章:传送门

torch.argmax

torch.argmax(outputs_softmax,dim=1)
在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
# 导入所需的库 import torch from model import resnet152 from PIL import Image from torchvision import transforms import matplotlib.pyplot as plt import json # 判断是否有GPU可用,若有则使用GPU,否则使用CPU device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义数据预处理的步骤,包括图片的resize、中心裁剪、转换为张量、以及标准化 data_transform = transforms.Compose( [transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])] ) # 打开图片并显示 img = Image.open("./huanglongbing.JPG") plt.imshow(img) # 对图片进行预处理,并增加一维作为batch_size img = data_transform(img) img = torch.unsqueeze(img, dim=0) # 读取class_indices.json文件,获取别标签 try: json_file = open('./class_indices.json', 'r') class_indict = json.load(json_file) except Exception as e: print(e) exit(-1) # 加载预训练好的模型,以及其对应的权重文件 model = resnet152(num_classes=38) model_weight_path = "./resNet152.pth" model.load_state_dict(torch.load(model_weight_path, map_location=device)) model.eval() # 在不进行梯度计算的情况下,使用模型进行预测 with torch.no_grad(): output = torch.squeeze(model(img)) predict = torch.softmax(output, dim=0) # 对输出进行softmax处理 predict_cla = torch.argmax(predict).numpy() # 获取预测的别 # 输出预测结果以及对应的概率,并显示图片 print(class_indict[str(predict_cla)], predict[predict_cla].numpy()) plt.show()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值