PyTorch 初识

Screen Shot 2021-10-11 at 01.53.02.png

简介

PyTorch 是一个开源的机器学习框架,基于 Torch。2017 年 1 月,由 FAIR(Facebook 人工智能研究院)基于 Torch 推出。底层和 Torch 一样的框架,但是使用 Python 重写了很多东西,对 Python 非常友好的深度学习框架,不仅能够支持 GPU 加速,还能提供动态神经网络的支持。随着 Caffe2 的合并,PyTorch 目前基本是科研实现的第一选择。

安装

我比较喜欢 virtualenv,所以本文采用 virtualenv 来配置安装

/usr/local/opt/python@3.7/bin/python3

首先基于你要运行的 python3 本帮创建新的环境

virtualenv --python=/usr/local/opt/python@3.7/bin/python3 env

创建成功后,尝试运行active

source env/bin/activate

如果成功的话,应该能看到 (env) 的提示符

选择你需要安装的版本进行安装,具体版本列表请从这里选择

https://pytorch.org/get-started/locally/

我们这里使用 Mac 本地无GPU版本,通过 pip 安装

pip3 install torch torchvision torchaudio

如果你安装比较慢,可以选择离你近的源,如国内的清华大学提供的服务

pip install pip -U
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

大概几秒就能安装完成。

让我们来测试下看看吧, 打开你的终端,尝试输入看看

>>> import torch
>>> print(torch.__version__)
1.9.1
>>>

正确输出版本号,说明本机已经成功安装好 PyTorch了。

通过终端输入调试比较麻烦,功能也比较单独,幸好有 Jupyter 的存在

pip install jupyterlab

安装成功,执行

jupyter-lab

启动并自动打开浏览器,新建一个 Python3 的 Notebook 就可以干活了

Screen Shot 2021-10-11 at 00.50.48.png

为了避免麻烦,我们提前安装一些需要用到的包

pip install matplotlib seaborn pandas scikit-learn hyperopt lightgbm xgboost gensim nltk pillow networkx 

来尝试跑个官网中的 Hello World 的例子: MNIST

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

# Download training data from open datasets.
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# Download test data from open datasets.
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("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break


# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__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)

        # Compute prediction error
        pred = model(X)
        loss = loss_fn(pred, y)

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

        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!")

保存 Model,重新加载

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


model = NeuralNetwork()
model.load_state_dict(torch.load("mnist.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}"')

References



评论 (0)

Sign in to comment