簡體   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