【问题标题】:Adjust input shape for my pytorch problem为我的 pytorch 问题调整输入形状
【发布时间】:2020-03-09 12:22:33
【问题描述】:

我正在尝试创建一个神经网络来输入形状为 249561, 80, 1 的输入,并且 y 标签是 (249561, 2)

def __init__(self):
    super(Net1, self).__init__()
    self.conv1 = nn.Conv1d(80, 16, kernel_size=1)

    self.conv2_drop = nn.Dropout()
    self.fc1 = nn.Linear(1,256)
    self.fc2 = nn.Linear(256, 64)
    self.fc3 = nn.Linear(64,32)
    self.fc4 = nn.Linear(32,2)

def forward(self, x):
    print(type(x))
    x = F.relu(F.max_pool1d(self.conv1(x), 1))
    print(x.shape)
    x.reshape(-1)
    e1 = F.relu(self.fc1(x))
    x = F.dropout(e1, training=self.training)
    x = F.relu(self.fc2(x))
    x = F.dropout(x, training=self.training)
    x = F.relu(self.fc3(x))
    x = F.dropout(x, training=self.training)
    x = self.fc4(x)

    return x

我的训练循环看起来像这样

losses = [];
batch_size = 16
for epoch in range(10):
      permutation = torch.randperm(x2.size()[0])
      for i in range(0,len(x2), batch_size):
        indices = permutation[i:i+batch_size]
        batch_x, batch_y = x2[indices], onehot_encoded[indices]
        #images = Variable(images.float())
        #labels = Variable(labels)

        # Forward + Backward + Optimize
        optimizer.zero_grad()
        outputs = model(batch_x)
        loss = criterion(outputs, batch_y)
        loss.backward()
        optimizer.step()

我有一批 16 个,我输入了一个形状为 [16, 80, 1].我得到以下错误的张量。 RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss2d_forward。我怀疑这是输出层的问题,但它返回一个形状为 2 的张量,与我的标签相同。输出x大小torch.Size([16, 16, 2])

【问题讨论】:

    标签: python arrays neural-network pytorch


    【解决方案1】:

    您为什么不使用nn.Conv1d(同时替换nn.Conv2d——您还需要更改dropout)而不是更改输入?

    如果你真的想改变输入,你可以添加:

    batch_x = batch_x[..., None]
    

    之后

    batch_x, batch_y = x2[indices], onehot_encoded[indices]
    

    【讨论】:

    • 谢谢!我收到以下错误给定输入大小:(16x1x1)。计算的输出大小:(16x1x0)。输出尺寸太小
    • 好吧,我不知道我的回答对你有没有帮助,所以我不确定我的下一个答案是否也会有所帮助
    猜你喜欢
    • 2021-06-03
    • 2018-05-02
    • 2020-08-21
    • 2020-10-03
    • 2021-01-10
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多