Pytorch:结合自动和手动方法

时间:2018-06-02 02:00:26

标签: python neural-network deep-learning pytorch backpropagation

我正在测试一个两步架构,它由一个可以用任何标准深度学习架构实现的传统第一部分和第二部分组成,第二部分必须在Pytorch图的声明之外手动编码(同时仍然使用numpy - 像火炬功能)。

我的问题可以简化为编码具有两个隐藏层的前馈神经网络,其中第一个在Pytorch图中实现,第二个在Pytorch图之外手动实现。

架构:

Input
-> Linear(28 * 28, 120) w/ Pytorch 
-> ReLU w/ Pytorch 
-> Linear(120, 84) w/ Pytorch 
-> ReLU w/ Pytorch 
-> Linear(84, 10) w/o Pytorch 
-> Output

问题:我的实现方法达到了非常低的~74%,而标准的完全Pytorch实现达到了~95%。造成这种差异的原因是什么?

我相信我的问题在于手动传回增量,虽然数学看起来正确,所以我一直在寻找解决方案。

关于MNIST的架构和培训的

实施

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 120)
        self.fc2 = nn.Linear(120, 84)

    def forward(self, x):
        x = x.view(-1, 28 * 28)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return x

net = Net()

criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)

# Initialize weights just as Pytorch does by default:
m = torch.distributions.uniform.Uniform(torch.tensor([-np.sqrt(1.0/84)]),
                                        torch.tensor([np.sqrt(1.0/84)]))
W = m.sample((84, 10)).reshape((84, 10))

# based on https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
for epoch in range(2):  # loop over the dataset multiple times

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

        # make one-hot encoding of labels
        targets = oneHot(labels)

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        pytorch_outputs = net(inputs)
        pytorch_outputs = torch.autograd.Variable(pytorch_outputs,
                                                  requires_grad=True)

        manual_outputs = torch.mm(pytorch_outputs, W)

        delta_out = manual_outputs - targets.view(-1,10)  # = error_out 
        dEdW3 = torch.mm(torch.t(pytorch_outputs), delta_out)
        W -= 0.01 * dEdW3  # gradient descent

        delta_h = torch.autograd.Variable(
                                  torch.t(torch.mm(W, torch.t(delta_out))))

        loss = criterion(pytorch_outputs, delta_h)
        loss.backward()
        optimizer.step()

完整代码:

import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))])

trainset = torchvision.datasets.MNIST(root='./data', train=True,
                                     download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=1,
                                          shuffle=True, num_workers=1)

testset = torchvision.datasets.MNIST(root='./data', train=False,
                                     download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=1,
                                         shuffle=False, num_workers=1)

classes = ('0', '1', '2', '3',
           '4', '5', '6', '7', '8', '9')

def oneHot(a):
    b = torch.zeros(10)
    b[a] = 1
    return b

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 120)
        self.fc2 = nn.Linear(120, 84)

    def forward(self, x):
        x = x.view(-1, 28 * 28)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        return x

net = Net()

criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)

# Initialize weights just as Pytorch does by default:
m = torch.distributions.uniform.Uniform(torch.tensor([-np.sqrt(1.0/84)]),
                                        torch.tensor([np.sqrt(1.0/84)]))
W = m.sample((84, 10)).reshape((84, 10))

# based on https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
for epoch in range(2):  # loop over the dataset multiple times

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

        # make one-hot encoding of labels
        targets = oneHot(labels)

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        pytorch_outputs = net(inputs)
        pytorch_outputs = torch.autograd.Variable(pytorch_outputs,
                                                  requires_grad=True)

        manual_outputs = torch.mm(pytorch_outputs, W)

        delta_out = manual_outputs - targets.view(-1,10)  # = error_out 
        dEdW3 = torch.mm(torch.t(pytorch_outputs), delta_out)
        W -= 0.001*dEdW3  # gradient descent

        delta_h = torch.autograd.Variable(
                                  torch.t(torch.mm(W, torch.t(delta_out))))

        loss = criterion(pytorch_outputs, delta_h)
        loss.backward()
        optimizer.step()

correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        inputs, labels = data
        pytorch_outputs = torch.autograd.Variable(net(inputs), 
                                                      requires_grad=True)
        manual_outputs = torch.mm(pytorch_outputs, W)
        _, predicted = torch.max(manual_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))

0 个答案:

没有答案