简体   繁体   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)

I seem to be having a problem with my code.我的代码似乎有问题。 The error occurs at:错误发生在:

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

I'm not sure what the issue is, and I've tried everything to fix.我不确定问题是什么,我已经尝试了一切来解决。 From my understanding, there seems to be a problem with the tensor dimension.据我了解,张量维度似乎有问题。 I'm not sure what else to do.我不确定还能做什么。 Can anyone give me any suggestions or solutions on how to fix this problem?谁能给我有关如何解决此问题的任何建议或解决方案? Thank you in advance.先感谢您。

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)))

I should also mention that i'm using the latest versions.我还应该提到我正在使用最新版本。

You are calling .squeeze() on the model's output, which removes all singular dimensions (dimensions that have size 1).您正在模型的 output 上调用.squeeze() ,它会删除所有奇异尺寸(尺寸为 1 的尺寸)。 Your model's output has size [batch_size, 1] , so .squeeze() removes the second dimension entirely, resulting in size [batch_size] .您的模型的 output 的大小为[batch_size, 1] ,因此.squeeze()完全删除第二个维度,从而产生大小[batch_size] After, you're trying to take the maximum value across dimension 1, but the only dimension you have is the 0th dimension.之后,您尝试在维度 1 上取最大值,但您拥有的唯一维度是第 0 维度。

You don't need to take the maximum value in this case, since you have only one class as the output, and with the sigmoid at the end of your model you get values between [0, 1].在这种情况下,您不需要取最大值,因为您只有一个 class 作为 output,并且在 Z20F35E630DAF44DBFA4C3F68F5391DZ8 之间使用 sigmoid。 Since your are doing a binary classification that single class acts as two, namely either it's 0 or it's 1. So it can be seen as the probability that it is the class 1. Then you just need to set use a threshold of 0.5, meaning when the probability is over 0.5 it's class 1 and if the probability is under 0.5 it's the class 0. That's exactly what rounding does, therefore you can use torch.round .由于您正在进行二进制分类,单个 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())

On a side note, you are calling net(value) multiple times with the same value, and that means that its output is calculated multiple times as well, because it needs to go through the entire network again.附带说明一下,您使用相同的值多次调用net(value) ,这意味着它的 output 也被计算多次,因为它需要再次通过整个网络 go 。 That is unnecessary and you should just save the output in a variable.这是不必要的,您应该将 output 保存在变量中。 With this small network it isn't noticeable, but with larger networks that will take a lot of unnecessary time to recalculate the output.对于这个小型网络,它并不明显,但对于较大的网络,将花费大量不必要的时间来重新计算 output。

暂无
暂无

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

相关问题 IndexError:尺寸超出范围 - PyTorch 尺寸预计在 [-1, 0] 范围内,但得到 1 - IndexError: Dimension out of range - PyTorch dimension expected to be in range of [-1, 0], but got 1 IndexError:维度超出范围(预期在 [-1, 0] 范围内,但得到 1) - IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) IndexError:维度超出范围(预计在 [-2, 1] 范围内,但得到 3) - IndexError: Dimension out of range (expected to be in range of [-2, 1], but got 3) IndexError:尺寸超出范围(预计在 [-1, 0] 范围内,但得到 -2)与 torch_geometry - IndexError: Dimension out of range (expected to be in range of [-1, 0], but got -2) with torch_geometry RuntimeError: dimension out of range(预期在 [-1, 0] 范围内,但得到 1) - RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) 维度超出范围(预计在 [-4, 3] 范围内,但得到 64) - Dimension out of range (expected to be in range of [-4, 3], but got 64) pytoch RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1 - pytoch RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1 文件“/model.py”,第 33 行,向前 x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) - File "/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) 获取 IndexError:列表索引超出范围错误 - Getting IndexError: list index out of range error 正在获取错误:IndexError:列表索引超出范围' - Getting error : IndexError: list index out of range'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM