pytorch官方文档示例代码报错KeyError: tensor(5)分析

先写解决办法好习惯
把报错的一行

plt.title(labels_map[label])

改成

plt.title(labels_map[label.item()])

问题、报错分析:
最近复制了pytorch官方文档的一段代码做实验

# 这段代码在Tutorials>Datasers&Dataloaders
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt


training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor()
)

test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor()
)
labels_map = {
    0: "T-Shirt",
    1: "Trouser",
    2: "Pullover",
    3: "Dress",
    4: "Coat",
    5: "Sandal",
    6: "Shirt",
    7: "Sneaker",
    8: "Bag",
    9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
    sample_idx = torch.randint(len(training_data), size=(1,)).item()
    img, label = training_data[sample_idx]
    figure.add_subplot(rows, cols, i)
    plt.title(labels_map[label])
    plt.axis("off")
    plt.imshow(img.squeeze(), cmap="gray")
plt.show()

发现一直报这样的错误:


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-35-336d271805e0> in <module>
     38     img, label = training_data[sample_idx]
     39     figure.add_subplot(rows, cols, i)
---> 40     plt.title(labels_map[label])
     41     plt.axis("off")
     42     plt.imshow(img.squeeze(), cmap="gray")

KeyError: tensor(5)

错误在于labels_map是一个数组,数组索引用的是int型数,而label打印出来是诸如sensor(0)之类的张量,所以会报错

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值