【问题标题】:PyTorch input/output data sizesPyTorch 输入/输出数据大小
【发布时间】:2021-07-04 10:16:19
【问题描述】:

我是第一次尝试 PyTorch,但遇到了几个问题。我在下面分享了我的一些代码,有两个问题。

Q1:我的输出尺寸应该是多少?每个输入应导致一个输出,等于 6 个可能的输出标签 (1-6) 之一。输出大小应该是 1 还是 6?

Q2:我的准确度计算出了点问题,我认为这与 Q1 相关。 predicted 最终大小为 4 x 4411,其中 4 是我的批量大小(所以我认为这是正确的),但 4411 是我的特征/输入大小,这几乎肯定是错误的。我希望它是 6(可能的输出标签的数量)。 labels 是 4x6,我认为是正确的。如果我改变昏暗,我将最大值从 1 变为 2,那么它会得到正确的 4x6 大小,但从逻辑上讲,它没有任何意义,因为它会返回输入的所有特征值的最大索引。

我认为我遗漏了一些关于 pytorch 处理我的数据的关键信息。我感觉如此接近......关于如何解决这个问题的任何想法?谢谢!

    def __init__(self, input_size, output_size, hidden_dim, n_layers):
        super(Net, self).__init__()
        self.input_size  = input_size
        self.output_size = output_size
        self.hidden_dim  = hidden_dim
        self.n_layers    = n_layers

        self.rnn = torch.nn.RNN(input_size, hidden_dim, n_layers, batch_first=True)
        # Q1: What should my output_size be?
        self.fc = torch.nn.Linear(hidden_dim, output_size)

    def forward(self, x):
        batch_size = x.size(0)
        hidden = self.init_hidden(batch_size)
        out, hidden = self.rnn(x, hidden)
        out = self.fc(out)
        return out, hidden

    def init_hidden(self, batch_size):
        return torch.zeros(self.n_layers, batch_size, self.hidden_dim)
if __name__ == '__main__':
   # ... code removed that just creates the Dataloaders, and initialises some size variables

    net = Net(input_size=dataset.input_size, output_size=6, hidden_dim=24, n_layers=1)
    net.to(device)
    criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(net.parameters(), lr=lr)

    for epoch in range(1, epochs+1):
        total = 0
        correct = 0
        for inputs, labels in dataloaders['train']:
            optimizer.zero_grad()
            inputs, labels = inputs.to(device), labels.to(device)
            output, hidden = net(inputs)
            loss = criterion(output, labels) # error
            loss.backward()
            optimizer.step()

            # Q2: Something is wrong here
            _, predicted = torch.max(output.data, 1)
            total += inputs.size(0)
            correct += (predicted == labels).sum().item()
            print(predicted == labels)
        accuracy = 100 * correct / total```

【问题讨论】:

    标签: python machine-learning pytorch


    【解决方案1】:
    1. Pytorch 的 CrossEntropyLoss 期望 output 大小为 (n)(具有 n 个类中每个类的分数),label 是正确类索引的整数。
    2. 您的基于 rnn 的模型正在输出形状为 [batch, input_size, 6] 的张量,因为它是一个 rnn 并生成与输入长度相同的序列(序列的每个元素有 6 个分数)。如果您希望每个序列(而不是序列的每个元素)有一个类标签预测,则需要将其折叠为形状为 [batch, 6] 的张量。

    【讨论】:

    • 如何将输出折叠到[batch, 6]?我认为这是我需要做的,但我不知道如何将这些 input_size 值减少为一个(每个输入)。
    • 我不确定label 的正确结构,感谢您的指正!我修好了。
    • @moinudin 您可以创建 6 个“姐妹”线性层,将每个标签的 input_size 值作为输入并输出一个值,然后连接它们的输出。
    • 我想我明白了,除了我不确定你会如何连接他们的输出?我现在试试看。
    • @moinudin torch.cat
    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2018-09-24
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2012-08-11
    • 2020-06-20
    相关资源
    最近更新 更多