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()
相关推荐
Wzx1980122 分钟前
自研开发的前后端项目部署流程
vue.js·python
凌~风5 分钟前
014-计算机操作系统实验报告之C 程序的编写!
c语言·开发语言·实验报告
西红市杰出青年11 分钟前
crawl4ai------AsyncPlaywrightCrawlerStrategy使用教程
开发语言·python·架构·正则表达式·pandas
星河耀银海11 分钟前
C++基础数据类型与变量管理:内存安全与高效代码的基石
java·开发语言·c++
写代码的【黑咖啡】14 分钟前
Python 中的 sqlite3 模块:轻量级数据库的完美搭档
数据库·python·sqlite
Logan Lie14 分钟前
Go语言接口(interface)深度详解
开发语言·数据库·golang
半路_出家ren15 分钟前
20.基于Selenium实现界面自动化控制
运维·python·selenium·测试工具·网络安全·自动化·chromedriver
计算机毕业设计指导15 分钟前
恶意网址检测系统
python·web安全·网络安全·系统安全
西部风情17 分钟前
稳定性质量系列-系统稳定性建设实践
java·开发语言
一招定胜负18 分钟前
模板匹配与银行卡号识别(预告)
python·opencv·计算机视觉