1. 程式人生 > >Pytorch學習筆記(二)

Pytorch學習筆記(二)

(3)批訓練包裝器DataLoader
Pytorch 中提供了一種幫你整理你的資料結構的好東西, 叫做 DataLoader, 我們能用它來包裝自己的資料, 進行批訓練.

import torch
import torch.utils.data as Data

BATCH_SIZE = 5

x = torch.linspace(1, 10, 10)
y = torch.linspace(10, 1, 10)

torch_dataset = Data.TensorDataset(data_tensor=x, target_tensor=y)
loader = Data.DataLoader(
    dataset=torch_dataset,
    batch_size=BATCH_SIZE,
    shuffle=True,
    num_workers=2
) for epoch in range(3): for step, (batch_x, batch_y) in enumerate(loader): print("Epoch: ", epoch, " | Step: ", step, " | batchx: ", batch_x.numpy(), " | batchy: ", batch_y.numpy())

執行結果如下:

Epoch:  0  | Step:  0  | batchx:  [ 6.  5.  1.  9.  3.]  | batchy:  [  5.   6.  10.   2.   8.]
Epoch: 0 | Step: 1 | batchx: [ 10. 2. 7. 8. 4.] | batchy: [ 1. 9. 4. 3. 7.] Epoch: 1 | Step: 0 | batchx: [ 6. 5. 4. 7. 9.] | batchy: [ 5. 6. 7. 4. 2.] Epoch: 1 | Step: 1 | batchx: [ 1. 8. 3. 10. 2.] | batchy: [ 10. 3. 8. 1. 9.] Epoch: 2 | Step: 0 | batchx: [ 5. 6. 7. 9. 3.] | batchy: [ 6. 5. 4. 2. 8.]
Epoch: 2 | Step: 1 | batchx: [ 10. 4. 8. 1. 2.] | batchy: [ 1. 7. 3. 10. 9.]

(4)使用ConvNet訓練cifar-10資料集

# -*- coding:utf-8 -*-
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as Data
import matplotlib.pyplot as plt
import numpy as np
import time

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))]
)

trainset = torchvision.datasets.CIFAR10(
    root='./data',
    train=True,
    transform=transform,
    download=True,
)
trainloader = Data.DataLoader(
    dataset=trainset,
    batch_size= 4,
    shuffle=True,
    num_workers=4
)

testset = torchvision.datasets.CIFAR10(
    root='./data',
    train=False,
    transform=transform,
    download=True,
)
testloader = Data.DataLoader(
    dataset=testset,
    batch_size=4,
    shuffle=False,
    num_workers=4
)

def imshow(img):
    img = img / 2 + 0.5
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))

dataiter = iter(trainloader)
images, labels = dataiter.next()
print(images.size())
imshow(torchvision.utils.make_grid(images))
plt.show()


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


def printnorm(self, input, output):
    print('Inside ' + self.__class__.__name__ + ' forward')
    print('')
    print('input: ', type(input))
    print('input[0]: ', type(input[0]))
    print('output: ', type(output))
    print('')
    print('input size:', input[0].size())
    print('output size:', output.data.size())
    print('output norm:', output.data.norm())

net = Net().cuda()
# net.conv2.register_forward_hook(printnorm)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

start_time = time.time()
for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # wrap them in Variable
        inputs, labels = Variable(inputs).cuda(), Variable(labels).cuda()

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.data[0]
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
end_time = time.time()
print("Spend time:", end_time - start_time)

這裡寫圖片描述

訓練結果如下:

Files already downloaded and verified
Files already downloaded and verified
torch.Size([4, 3, 32, 32])
[1,  2000] loss: 2.204
[1,  4000] loss: 1.822
[1,  6000] loss: 1.705
[1,  8000] loss: 1.591
[1, 10000] loss: 1.524
[1, 12000] loss: 1.450
[2,  2000] loss: 1.402
[2,  4000] loss: 1.353
[2,  6000] loss: 1.344
[2,  8000] loss: 1.338
[2, 10000] loss: 1.286
[2, 12000] loss: 1.276
Finished Training
Spend time: 53.437838077545166

(5)模型的儲存與獲取:
有時候訓練網路需要大量的時間,所以訓練好網路之後需要將它儲存下來方便下次的使用,在Pytorch中有兩種儲存網路的方式,其中一種既儲存了網路的結構,還儲存了網路訓練好的引數;另外一種方式只儲存了網路訓練好的引數,所以在下一次載入該網路引數的時候需要先對網路的結構進行定義。程式碼如下所示:

# -*- coding:utf-8 -*-
import torch
from torch.autograd import Variable
import torch.nn as nn

torch.manual_seed(1)    # reproducible

# 假資料
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)  # x data (tensor), shape=(100, 1)
y = x.pow(2) + 0.2*torch.rand(x.size())  # noisy y data (tensor), shape=(100, 1)
x, y = Variable(x, requires_grad=False), Variable(y, requires_grad=False)


def save():
    # 建網路
    net1 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )
    optimizer = torch.optim.SGD(net1.parameters(), lr=0.5)
    loss_func = torch.nn.MSELoss()

    # 訓練
    for t in range(100):
        prediction = net1(x)
        loss = loss_func(prediction, y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    torch.save(net1, 'net.pkl')  # 儲存整個網路
    torch.save(net1.state_dict(), 'net_params.pkl')   # 只儲存網路中的引數 (速度快, 佔記憶體少)


def restore_net():
    # restore entire net1 to net2
    net2 = torch.load('net.pkl')
    prediction = net2(x)


def restore_params():
    # 新建 net3
    net3 = torch.nn.Sequential(
        torch.nn.Linear(1, 10),
        torch.nn.ReLU(),
        torch.nn.Linear(10, 1)
    )

    # 將儲存的引數複製到 net3
    net3.load_state_dict(torch.load('net_params.pkl'))
    prediction = net3(x)