您的位置:

全面了解Linux PyTorch

一、安装和环境配置

1、安装PyTorch

conda install pytorch torchvision torchaudio -c pytorch

2、验证是否安装成功

import torch
print(torch.__version__)

3、安装CUDA

conda install cudatoolkit

4、创建环境

conda create --name torch-env
conda activate torch-env

5、将新环境添加到Jupyter Notebook

python -m ipykernel install --user --name torch-env --display-name "Python (torch-env)"

二、数据处理

1、加载数据集

from torchvision import datasets, transforms

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

train_dataset = datasets.MNIST('data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST('data', train=False, download=True, transform=transform)

2、数据加载器

from torch.utils.data import DataLoader

train_batch_size = 64
test_batch_size = 1000

train_loader = DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=test_batch_size, shuffle=False)

3、数据可视化

import matplotlib.pyplot as plt

images, labels = next(iter(train_loader))
fig = plt.figure(figsize=(10, 10))
for i in range(64):
    ax = fig.add_subplot(8, 8, i+1, xticks=[], yticks=[])
    ax.imshow(images[i].view(28, 28))
    ax.set_title(str(labels[i].item()))
plt.show()

三、模型训练

1、定义模型

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, kernel_size=5)
        self.conv2 = nn.Conv2d(20, 50, kernel_size=5)
        self.fc1 = nn.Linear(4*4*50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4*4*50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)

net = Net()

2、定义损失函数和优化器

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.5)

3、训练模型

for epoch in range(3):
    running_loss = 0.0
    for i, data in enumerate(train_loader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        if i % 100 == 99:    
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0
print('Finished Training')

四、模型评估

1、测试模型

correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))

2、查看每个类别的准确率

class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels).squeeze()
        for i in range(test_batch_size):
            label = labels[i]
            class_correct[label] += c[i].item()
            class_total[label] += 1

for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        i, 100 * class_correct[i] / class_total[i]))

五、模型保存和加载

1、保存模型

PATH = './mnist_net.pth'
torch.save(net.state_dict(), PATH)

2、加载模型

net = Net()
net.load_state_dict(torch.load(PATH))
以上就是Linux PyTorch的基本使用方法,包括了安装和环境配置、数据处理、模型训练、模型评估、模型保存和加载等方面。通过这篇文章,你可以初步掌握Linux PyTorch的使用方法,为进行更加复杂的深度学习实验打下基础。