Python打卡第38天

import numpy as np

import torch

import torch.nn as nn

import torch.optim as optim

from torch.utils.data import DataLoader, Dataset

from torchvision import datasets, transforms

import matplotlib.pyplot as plt

设置随机种子确保结果可复现

torch.manual_seed(42)

定义数据预处理

transform = transforms.Compose([

transforms.ToTensor(), # 将图像转换为Tensor

transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 归一化处理

])

加载数据集

train_dataset = datasets.CIFAR10(

root='./data',

train=True,

download=True,

transform=transform

)

test_dataset = datasets.CIFAR10(

root='./data',

train=False,

transform=transform

)

类别名称

class_names = ('plane', 'car', 'bird', 'cat', 'deer',

'dog', 'frog', 'horse', 'ship', 'truck')

可视化函数

def imshow(img, title=None):

"""显示反归一化后的图像"""

img = img * 0.5 + 0.5 # 反归一化 [-1,1] -> [0,1]

np_img = img.numpy()

plt.figure(figsize=(4, 4))

plt.imshow(np.transpose(np_img, (1, 2, 0))) # CHW -> HWC

if title:

plt.title(title)

plt.axis('off')

plt.show()

随机选择并显示样本

sample_idx = torch.randint(0, len(train_dataset), (1,)).item()

image, label = train_dataset[sample_idx]

print(f"Label: {label} ({class_names[label]})")

imshow(image, f"Label: {class_names[label]}")

相关推荐
我材不敲代码17 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得020 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长20 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_1927798720 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u01092727120 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊20 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm77721 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew21 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd65221 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369611 天前
用Python生成艺术:分形与算法绘图
jvm·数据库·python