繁体   English   中英

在 Pytorch 中出现错误:IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

[英]Getting an Error in Pytorch: IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

我的代码似乎有问题。 错误发生在:

x, predicted = torch.max(net(value).data.squeeze(), 1)

我不确定问题是什么,我已经尝试了一切来解决。 据我了解,张量维度似乎有问题。 我不确定还能做什么。 谁能给我有关如何解决此问题的任何建议或解决方案? 先感谢您。

class Network(nn.Module): #Class for the neural network
def __init__(self):
    super(Network, self).__init__()
    self.layer1 = nn.Linear(6, 10) #First number in the number of inputs(784 since 28x28 is 784.) Second number indicates the number of inputs for the hidden layer(can be any number).
    self.hidden = nn.Softmax() #Activation Function
    self.layer2 = nn.Linear(10, 1) #First number is the hidden layer number(same as first layer), second number is the number of outputs.
    self.layer3 = nn.Sigmoid()

def forward(self, x): #Feed-forward part of the neural network. We will will feed the input through every layer of our network.
    y = self.layer1(x)
    y = self.hidden(y)
    y = self.layer2(y)
    y = self.layer3(y)
    return y #Returns the result

net = Network()
loss_function = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)

for x in range(1): #Amount of epochs over the dataset
for index, value in enumerate(new_train_loader):
    print(value)#This loop loops over every image in the dataset 
    #actual = value[0]
    actual_value = value[5]
    #print(value.size())
    #print(net(value).size())
    print("ACtual", actual_value)
    net(value)
    loss = loss_function(net(value), actual_value.unsqueeze(0)) #Updating our loss function for every image
    #Backpropogation
    optimizer.zero_grad() #Sets gradients to zero.
    loss.backward() #Computes gradients
    optimizer.step() #Updates gradients
    print("Loop #: ", str(x+1), "Index #: ", str(index+1), "Loss: ", loss.item())


right = 0
total = 0
for value in new_test_loader:
actual_value = value[5]
#print(torch.max(net(value).data, 1))
print(net(value).shape)
x, predicted = torch.max(net(value).data.squeeze(), 1)
total += actual_value.size(0)
right += (predicted==actual_value).sum().item()
print("Accuracy: " + str((100*right/total)))

我还应该提到我正在使用最新版本。

您正在模型的 output 上调用.squeeze() ,它会删除所有奇异尺寸(尺寸为 1 的尺寸)。 您的模型的 output 的大小为[batch_size, 1] ,因此.squeeze()完全删除第二个维度,从而产生大小[batch_size] 之后,您尝试在维度 1 上取最大值,但您拥有的唯一维度是第 0 维度。

在这种情况下,您不需要取最大值,因为您只有一个 class 作为 output,并且在 Z20F35E630DAF44DBFA4C3F68F5391DZ8 之间使用 sigmoid。 由于您正在进行二进制分类,单个 class 充当两个,即为 0 或为 1。因此可以将其视为 class 1 的概率。然后您只需设置使用阈值 0.5,即当概率超过 0.5 时,它是 class 1,如果概率低于 0.5,它是 class 0。这正是四舍五入的作用,因此您可以使用torch.round

output = net(value)
predicted = torch.round(output.squeeze())

附带说明一下,您使用相同的值多次调用net(value) ,这意味着它的 output 也被计算多次,因为它需要再次通过整个网络 go 。 这是不必要的,您应该将 output 保存在变量中。 对于这个小型网络,它并不明显,但对于较大的网络,将花费大量不必要的时间来重新计算 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM