資料內(nèi)容:
2. 加載和預(yù)處理數(shù)據(jù)
創(chuàng)建一個Python文件,比如叫 main.py ,然后開始編寫代碼。首先,導(dǎo)入必要的庫:
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
# 設(shè)置數(shù)據(jù)轉(zhuǎn)換
transform = transforms.Compose([
transforms.ToTensor(), # 轉(zhuǎn)換圖像為Tensor
transforms.Normalize((0.5,), (0.5,)) # 標(biāo)準(zhǔn)化
])
# 下載訓(xùn)練集和測試集
train_set = torchvision.datasets.MNIST(root='./data', train=True, download=True,
transform=transform)
test_set = torchvision.datasets.MNIST(root='./data', train=False, download=True,
transform=transform)
# 加載數(shù)據(jù)
train_loader = DataLoader(train_set, batch_size=64, shuffle=True)
test_loader = DataLoader(test_set, batch_size=64, shuffle=False)