Pytorch简单模型无法改善

时间:2019-09-21 22:57:54

标签: python machine-learning neural-network pytorch

我正在制作一个简单的PyTorch神经网络,以近似x = [0,2pi]上的正弦函数。这是一个简单的体系结构,可与其他深度学习库一起使用,以测试是否了解如何使用它。当未经训练时,神经网络始终会产生一条水平直线,而当经过训练时,它会在y = 0处产生一条直线。通常,它在y =(该函数的均值)时始终会产生一条直线。这使我相信它的前向支撑部分有问题,因为边界在训练时不应该只是一条直线。这是网络的代码:

class Net(nn.Module):
    def __init__(self):
      super(Net, self).__init__()
      self.model = nn.Sequential(
      nn.Linear(1, 20),
      nn.Sigmoid(),
      nn.Linear(20, 50),
      nn.Sigmoid(),
      nn.Linear(50, 50),
      nn.Sigmoid(),
      nn.Linear(50, 1)
      )

    def forward(self, x):
        x = self.model(x)
        return x

这是训练循环

def train(net, trainloader, valloader, learningrate, n_epochs):
    net = net.train()
    loss = nn.MSELoss()
    optimizer = torch.optim.SGD(net.parameters(), lr = learningrate)

    for epoch in range(n_epochs):

        for X, y in trainloader:
            X = X.reshape(-1, 1)
            y = y.view(-1, 1)
            optimizer.zero_grad()

            outputs = net(X)

            error   = loss(outputs, y)
            error.backward()
            #net.parameters()  net.parameters() * learningrate
            optimizer.step()

        total_loss = 0
        for X, y in valloader:
            X = X.reshape(-1, 1).float()
            y = y.view(-1, 1)
            outputs = net(X)
            error   = loss(outputs, y)
            total_loss += error.data

        print('Val loss for epoch', epoch, 'is', total_loss / len(valloader) )

它称为:

net = Net()
losslist = train(net, trainloader, valloader, .0001, n_epochs = 4)

trainloader和valloader是训练和验证装载机。谁能帮我看看这有什么问题吗?我知道它不是学习率,因为它是我在其他框架中使用的学习率,我也不知道它不是使用SGD或Sigmoid激活函数的事实,尽管我怀疑错误在于某个地方的激活函数。

有人知道如何解决此问题吗?谢谢。

2 个答案:

答案 0 :(得分:1)

使用一些超参数一段时间后,修改网络并更改优化器(遵循this出色的配方),最后我将行optimizer = torch.optim.SGD(net.parameters(), lr = learningrate)更改为optimizer = torch.optim.Adam(net.parameters())({{ 3}}使用了优化程序参数),运行了100个纪元且批处理大小等于1。

使用了以下代码(仅在CPU上测试):

import torch
import torch.nn as nn
from torch.utils import data
import numpy as np
import matplotlib.pyplot as plt

# for reproducibility
torch.manual_seed(0)
np.random.seed(0)

class Dataset(data.Dataset):

    def __init__(self, init, end, n):

        self.n = n
        self.x = np.random.rand(self.n, 1) * (end - init) + init
        self.y = np.sin(self.x)

    def __len__(self):

        return self.n

    def __getitem__(self, idx):

        x = self.x[idx, np.newaxis]
        y = self.y[idx, np.newaxis]

        return torch.Tensor(x), torch.Tensor(y)


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.model = nn.Sequential(
        nn.Linear(1, 20),
        nn.Sigmoid(),
        nn.Linear(20, 50),
        nn.Sigmoid(),
        nn.Linear(50, 50),
        nn.Sigmoid(),
        nn.Linear(50, 1)
        )

    def forward(self, x):
        x = self.model(x)
        return x

def train(net, trainloader, valloader, n_epochs):

    loss = nn.MSELoss()
    # Switch the two following lines and run the code
    # optimizer = torch.optim.SGD(net.parameters(), lr = 0.0001)
    optimizer = torch.optim.Adam(net.parameters())

    for epoch in range(n_epochs):

        net.train()
        for x, y in trainloader:
            optimizer.zero_grad()
            outputs = net(x).view(-1)
            error   = loss(outputs, y)
            error.backward()
            optimizer.step()

        net.eval()
        total_loss = 0
        for x, y in valloader:
            outputs = net(x)
            error   = loss(outputs, y)
            total_loss += error.data

        print('Val loss for epoch', epoch, 'is', total_loss / len(valloader) )    

    net.eval()

    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)

    def plot_result(ax, dataloader):
        out, xx, yy = [], [], []
        for x, y in dataloader:
            out.append(net(x))
            xx.append(x)
            yy.append(y)
        out = torch.cat(out, dim=0).detach().numpy().reshape(-1)
        xx = torch.cat(xx, dim=0).numpy().reshape(-1)
        yy = torch.cat(yy, dim=0).numpy().reshape(-1)
        ax.scatter(xx, yy, facecolor='green')
        ax.scatter(xx, out, facecolor='red')
        xx = np.linspace(0.0, 3.14159*2, 1000)
        ax.plot(xx, np.sin(xx), color='green')

    plot_result(ax1, trainloader)
    plot_result(ax2, valloader)
    plt.show()


train_dataset = Dataset(0.0, 3.14159*2, 100)
val_dataset = Dataset(0.0, 3.14159*2, 30)

params = {'batch_size': 1,
          'shuffle': True,
          'num_workers': 4}

trainloader = data.DataLoader(train_dataset, **params)
valloader = data.DataLoader(val_dataset, **params)

net = Net()
losslist = train(net, trainloader, valloader, n_epochs = 100)        

Adam优化器的结果: default

SGD优化器的结果: enter image description here

答案 1 :(得分:1)

  

通常,它总是在y =(函数的平均值)处产生一条直线。

通常,这意味着NN到目前为止仅成功地训练了最后一层。正如ViniciusArruda在此处显示的那样,您需要对它进行更长的训练或进行更好的优化。

编辑:进一步解释。当仅训练了最后一层时,NN在不知道输入X的情况下有效地尝试猜测输出y。在这种情况下,可以做出的最佳猜测是均值值。这样,它可以最小化其MSE损失。