iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
AI/ ML & Data

菜就多練之我叫小賀逃離DS新手村系列 第 11

Day 11 枕戈待旦-我想放假了PyTorch

  • 分享至 

  • xImage
  •  

實戰演練 🔥

Fashion-MNIST

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor

# 下載訓練數據集
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# 下載測試數據集
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)

batch_size = 64

# 建立數據加載器
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

# 確認數據加載器的輸出
for X, y in test_dataloader:
    print(f"Shape of X [N, C, H, W]: {X.shape}")
    print(f"Shape of y: {y.shape} {y.dtype}")
    break

# 設定訓練設備
device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device} device")

#定義神經網路模型
class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
print(model)

#設定損失函數和優化器
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)

#定義訓練和測試函數
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        pred = model(X)
        loss = loss_fn(pred, y)

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if batch % 100 == 0:
            loss, current = loss.item(), (batch + 1) * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

#訓練和測試模型
epochs = 5
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(train_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model, loss_fn)
print("Done!")

#儲存和載入模型
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")

model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))

#使用模型進行預測
classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
    x = x.to(device)
    pred = model(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')


Code Review 🧐

1. 載入資料集

training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)
  • 透過torchvision將FashionMNIST載入到Colab,並將資料轉成tensor格式

2. 建立數據加載器

batch_size = 64

train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
  • 使用DataLoader將訓練資料和測試資料批次載入
  • 批次處理(Batch Processing): 將資料分批進行處理而不是一次處理所有資料。這麼做可以有效善用運算資源提高處理速度。

3.確認數據加載器的輸出

for X, y in test_dataloader:
    print(f"Shape of X [N, C, H, W]: {X.shape}")
    print(f"Shape of y: {y.shape} {y.dtype}")
    break

  • test_dataloader取出一個批次的資料,並印出「圖片數據」和「標籤數據」
  • X是圖片數據,形狀為[N, C, H, W]
    • N是批次大小
    • C是通道大小
    • H是圖片高度
    • W是圖片寬度
  • Y是標籤數據,顯示每個對應的圖片個數,也就是N
  • 通道(Channels): 主要跟圖片顯示有關,常見的RGB格式是由3個channels組成,不同的圖像組成方式,channel數也不同。

4.設定訓練設備

device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device} device")

  • 檢查是否有可用的 GPU 或 MPS(Metal Performance Shaders),否則使用 CPU。

5.定義神經網絡模型和前向傳播

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
print(model)

  • 神經網路(NN):

    • 定義一個平坦層(Flatten Layer),將多維度資料做維度轉換,在這裡我們將28*28的圖像資料轉換784的一維資料。
    • 定義三個全連接層(Fully Connected Layer),對輸入資料進行數據轉換,用來將輸入的特徵映射到輸出的特徵。
    • 定義兩個ReLU激活函數,主要用途是將資料做非線性轉換,負值設為0,正值保持不變。目的是減少「梯度消失問題」。
  • 前向傳播(Forward Propagation):

    • 定義數據如何透過NN中不同的layer串聯後輸出結果。

6. 設定損失函數和優化器

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
  • 設定交叉熵損失函數隨機梯度下降(SGD)優化器

7. 定義訓練和測試函數

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        pred = model(X)
        loss = loss_fn(pred, y)

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if batch % 100 == 0:
            loss, current = loss.item(), (batch + 1) * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
  • train函數:用於訓練模型。它接收數據加載器、模型、損失函數和優化器作為參數。

  • test函數:用於測試模型。它接收數據加載器、模型和損失函數作為參數。

8. 訓練和測試模型

epochs = 5
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(train_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model, loss_fn)
print("Done!")
  • 定義了訓練的迭代次數(epochs),並在每個 epoch 中調用 traintest函數來訓練和評估模型

9.儲存和載入模型

torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")

model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))
  • 將訓練好的模型參數儲存到model.pth
  • model.pth中載入模型參數

10. 使用模型進行預測

classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
    x = x.to(device)
    pred = model(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')
  • 使用訓練好的模型對測試數據中的一個樣本進行預測,並將預測結果與實際標籤進行比較。

題外話😂

再1天就可以放假🎉

再32天就有中秋連假🌕

再55天加請一天就有國慶連假🤪

再76天就有萬聖節🎃

再131天就有聖誕節⛄

再138天就跨年🎆

大家加加油💪


上一篇
Day 10 工欲善其事,必先利其器-PyTorch是我的武器
下一篇
Day 12 層層把關-模型守門員
系列文
菜就多練之我叫小賀逃離DS新手村30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言