【发布时间】: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