參考官網(wǎng)教程:
https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html
打開(kāi)文件嗡髓,并寫(xiě)入如下代碼澜躺,保持為first.py:
#包含頭文件
import torch
from torch import nn #神經(jīng)網(wǎng)絡(luò)相關(guān)
from torch.utils.data import DataLoader #數(shù)據(jù)載入
from torchvision import datasets #自帶數(shù)據(jù)集
from torchvision.transforms import ToTensor #tensor數(shù)據(jù)轉(zhuǎn)換工具
# Download training data from open datasets.
#訓(xùn)練數(shù)據(jù)集
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
# Download test data from open datasets.
#測(cè)試數(shù)據(jù)集
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
batch_size = 64
# Create data loaders.
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
# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu" #判斷是否使用gpu
print(f"Using {device} device")
# Define model
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten() #展開(kāi)成1維向量
self.linear_relu_stack = nn.Sequential( #串聯(lián)網(wǎng)絡(luò)的定義
nn.Linear(28*28, 512), #線(xiàn)性層
nn.ReLU(), #非線(xiàn)性層
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10)
)
def forward(self, x): #正向估計(jì)函數(shù)
x = self.flatten(x) #數(shù)據(jù)展開(kāi)
logits = self.linear_relu_stack(x) #網(wǎng)絡(luò)計(jì)算
return logits
model = NeuralNetwork().to(device)
print(model) #強(qiáng)大的print 函數(shù)顯示模型細(xì)節(jié)
loss_fn = nn.CrossEntropyLoss() #損失函數(shù)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) #梯度函數(shù)
def train(dataloader, model, loss_fn, optimizer): #模型訓(xùn)練
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device) #載入GPU 或CPU
# Compute prediction error
pred = model(X) #正向計(jì)算
loss = loss_fn(pred, y) #計(jì)算cost
# Backpropagation
optimizer.zero_grad() #計(jì)算梯度
loss.backward() #計(jì)算梯度
optimizer.step() #真正訓(xùn)練
if batch % 100 == 0:
loss, current = loss.item(), batch * 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()
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():
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
運(yùn)行:
python3 first.py
顯示如下表示運(yùn)行成功。
Test Error:
Accuracy: 64.6%, Avg loss: 1.073880Done!
Saved PyTorch Model State to model.pth
Predicted: "Ankle boot", Actual: "Ankle boot"