在PyTorch中,儲存資料的單位稱為tensor。Tensor相當於NumPy的array,兩者之間的差別在於tensor可以在GPU上運算,而array不行。
這裡示範透過不同方式建立tensor:
import torch
import numpy as np
# 從list轉換成tensor
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
print(x_data)
# 從 NumPy array轉換成tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(x_np)
tensor可以儲存不同維度的資料型態,如果讀者們對於線性代數有一點印象,就知道向量(vector)或矩陣(matrix)可以進行運算並表達不同形式的資料。例如:圖片、語音、影像等,都是多維度的資料。要分析這些維度的資料,就可以透過tensor將這些多維度資料轉換成可以運算的型態,然後再進行訓練和分析。
程式碼如下:
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}"')
以上是透過PyTorch 框架訓練並評估神經網絡模型來分類 Fashion-MNIST dataset的範例。明天會針對此程式碼的詳細內容做介紹。
作為一個剛進入職場的新鮮人,昨天簽了一張賣身契哈哈(實習轉正合約),一想到接下來要去當兵,可能再唸個研究所,剩下的時間基本上就被工作填滿😱,我每天出門上班的時間基本上都差不多,連騎車時哪些紅綠燈一定會過哪些一定會停下來都一模一樣,感覺很不可思議超級玄。