Advertisement

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)

全部评论 (0)

还没有任何评论哟~