DAY 39 图像数据与显存
知识点回顾
- 图像数据的格式:灰度和彩色数据
- 模型的定义
- 显存占用的4种地方
- 模型参数+梯度参数
- 优化器参数
- 数据批量所占显存
- 神经元输出中间状态
- batchisize和训练的关系
作业:今日代码较少,理解内容即可
# 打印一张彩色图像,用cifar-10数据集
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
# 设置随机种子确保结果可复现
torch.manual_seed(42)
# 定义数据预处理步骤
transform = transforms.Compose([
transforms.ToTensor(), # 转换为张量并归一化到[0,1]
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 标准化处理
])
# 加载CIFAR-10训练集
trainset = torchvision.datasets.CIFAR10(
root='./data',
train=True,
download=True,
transform=transform
)
# 创建数据加载器
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=4,
shuffle=True
)
# CIFAR-10的10个类别
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
# 随机选择一张图片
sample_idx = torch.randint(0, len(trainset), size=(1,)).item()
image, label = trainset[sample_idx]
# 打印图片形状
print(f"图像形状: {image.shape}") # 输出: torch.Size([3, 32, 32])
print(f"图像类别: {classes[label]}")
# 定义图像显示函数(适用于CIFAR-10彩色图像)
def imshow(img):
img = img / 2 + 0.5 # 反标准化处理,将图像范围从[-1,1]转回[0,1]
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0))) # 调整维度顺序:(通道,高,宽) → (高,宽,通道)
plt.axis('off') # 关闭坐标轴显示
plt.show()
# 显示图像
imshow(image)

class MLP(nn.Module):
def __init__(self, input_size=3072, hidden_size=128, num_classes=10):
super(MLP, self).__init__()
# 展平层:将3×32×32的彩色图像转为一维向量
# 输入尺寸计算:3通道 × 32高 × 32宽 = 3072
self.flatten = nn.Flatten()
# 全连接层
self.fc1 = nn.Linear(input_size, hidden_size) # 第一层
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes) # 输出层
def forward(self, x):
x = self.flatten(x) # 展平:[batch, 3, 32, 32] → [batch, 3072]
x = self.fc1(x) # 线性变换:[batch, 3072] → [batch, 128]
x = self.relu(x) # 激活函数
x = self.fc2(x) # 输出层:[batch, 128] → [batch, 10]
return x
# 初始化模型
model = MLP()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device) # 将模型移至GPU(如果可用)
from torchsummary import summary # 导入torchsummary库
print("\n模型结构信息:")
summary(model, input_size=(3, 32, 32)) # CIFAR-10 彩色图像(3×32×32)
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten() # nn.Flatten()会将每个样本的图像展平为 784 维向量,但保留 batch 维度。
self.layer1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(128, 10)
def forward(self, x):
x = self.flatten(x) # 输入:[batch_size, 1, 28, 28] → [batch_size, 784]
x = self.layer1(x) # [batch_size, 784] → [batch_size, 128]
x = self.relu(x)
x = self.layer2(x) # [batch_size, 128] → [batch_size, 10]
return x
from torch.utils.data import DataLoader
# 定义训练集的数据加载器,并指定batch_size
train_loader = DataLoader(
dataset=train_dataset, # 加载的数据集
batch_size=64, # 每次加载64张图像
shuffle=True # 训练时打乱数据顺序
)
# 定义测试集的数据加载器(通常batch_size更大,减少测试时间)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=1000,
shuffle=False
)