pythonstudy Day42

Dateset和Datloader类

@疏锦行

clike 复制代码
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np

# 1. 定义数据预处理(转为 Tensor)
transform = transforms.ToTensor()

# 2. 下载并加载 CIFAR-10 训练集
cifar10_dataset = torchvision.datasets.CIFAR10(
    root='./data',
    train=True,
    download=True,
    transform=transform
)

# 3. 取出一张图片和对应标签
image, label = cifar10_dataset[0]

# CIFAR-10 类别名称
classes = (
    'airplane', 'automobile', 'bird', 'cat', 'deer',
    'dog', 'frog', 'horse', 'ship', 'truck'
)

print("Label index:", label)
print("Label name:", classes[label])
print("Image shape:", image.shape)  # [3, 32, 32]

# 4. Tensor → NumPy,并调整维度以便显示
image_np = image.permute(1, 2, 0).numpy()

# 5. 显示图片
plt.imshow(image_np)
plt.title(classes[label])
plt.axis('off')
plt.show()
相关推荐
2401_851272996 分钟前
自定义内存检测工具
开发语言·c++·算法
章鱼丸-17 分钟前
DAY31 文件的拆分和写法
开发语言·python
左左右右左右摇晃24 分钟前
Java并发——synchronized锁
java·开发语言
☆56627 分钟前
C++中的命令模式
开发语言·c++·算法
唐叔在学习30 分钟前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
2501_9454235431 分钟前
使用Fabric自动化你的部署流程
jvm·数据库·python
wenlonglanying32 分钟前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
2401_8463416533 分钟前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
未知鱼43 分钟前
Python安全开发之子域名扫描器(含详细注释)
网络·python·安全·web安全·网络安全
2401_831824961 小时前
编写一个Python脚本自动下载壁纸
jvm·数据库·python