Pytorch神经网络分类初探
1.数据准备
环境采用之前创建的Anaconda虚拟环境pytorch,为了方便查看每一步的返回值,可以使用Jupyter Notebook来进行开发。首先把需要的包导入进来
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
torch框架的数据输入依赖两个基类:torch.utils.data.DataLoader和torch.utils.data.Dataset,Dataset 存储样本及其相应的标签,DataLoader 将 Dataset 封装为迭代器。
为了方便使用数据,我们采用Mnist数据集
%matplotlib inline
from pathlib import Path
import requests
DATA_PATH = Path("data")
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)
URL = "http://deeplearning.net/data/mnist/"
FILENAME = "mnist.pkl.gz"
if not (PATH / FILENAME).exists():
content = requests.get(URL + FILENAME).content
(PATH / FILENAME).open("wb").write(content)
等待数据下载完毕,然后将数据读入进来。
import pickle
import gzip
with gzip.open((PATH / FILENAME).as_posix(), "rb") as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding="latin-1")
读入进来的数据并不是tensor格式的,需要将其转化成Tensor格式
import torch
x_train, y_train, x_valid, y_valid = map(
torch.tensor, (x_train, y_train, x_valid, y_valid)
)
最重要的一步,将其转换成dataset和dataloader
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
train_ds = TensorDataset(x_train, y_train)
train_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)
valid_ds = TensorDataset(x_valid, y_valid)
valid_dl = DataLoader(valid_ds, batch_size=bs * 2)
这样就完成了数据准备的工作
2.定义模型
这边直接引用官网教程的模型
# Get cpu, gpu or mps device for training.
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
print(f"Using {device} device")
# Define model
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)
将打印的结果放在下面,可以查看一下
Using cuda device
NeuralNetwork(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear_relu_stack): Sequential(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): ReLU()
(2): Linear(in_features=512, out_features=512, bias=True)
(3): ReLU()
(4): Linear(in_features=512, out_features=10, bias=True)
)
)
3.定义模型损失函数和优化器
这里我们依旧使用官网教程中的直接来
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
这里的SGD是最基础的优化器,采用的是梯度递减的方式,其收敛的会比较慢,如果希望收敛快些,可以使用Adam方式。
4. 定义训练和测试函数
训练函数
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)
# Compute prediction error
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
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")
5.开始训练
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dl, model, loss_fn, optimizer)
test(valid_dl, model, loss_fn)
print("Done!")
6.模型保存
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
7.模型加载和使用模型预测
model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))
模型预测
classes = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
]
model.eval()
x, y = train_ds[2][0], train_ds[2][1]
with torch.no_grad():
x = x.to(device)
pred = model(x)
print(pred)
predicted, actual = classes[pred.argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
使用SGD优化器训练,训练5次的最高精度为76%,而使用Adam优化器第一个epoch的精度就已经达到了97%