首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Pytorch中获取一个错误: IndexError:维度超出范围(预期在[-1,0]范围内,但得到1)

在Pytorch中获取一个错误: IndexError:维度超出范围(预期在[-1,0]范围内,但得到1)
EN

Stack Overflow用户
提问于 2020-05-19 14:39:12
回答 1查看 723关注 0票数 1

我的代码好像有问题。错误发生在:

代码语言:javascript
复制
x, predicted = torch.max(net(value).data.squeeze(), 1)

我不知道是什么问题,我已经尽力去解决了。据我理解,张量维度似乎有问题。我不知道还能做什么。有人能给我一些关于如何解决这个问题的建议或解决方案吗?提前谢谢你。

代码语言:javascript
复制
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)))

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-19 22:48:59

您正在对模型的输出调用.squeeze(),它删除了所有奇异维度(尺寸为1的维度)。您的模型输出的大小为batch_size,1,因此.squeeze()完全删除了第二个维度,从而导致了batch_size大小。之后,您将尝试获取维度1的最大值,但唯一的维度是第0维度。

在这种情况下,你不需要取最大值,因为你只有一个类作为输出,而在模型结束时,乙状结肠得到0,1之间的值。由于你在做一个二进制分类,单个类的作用是两个,要么是0,要么是1。所以它可以被看作是1类的概率。然后你只需要设置一个阈值0.5,当概率超过0.5,它是1级,如果概率小于0.5,它就是0类。这正是舍入的作用,因此您可以使用torch.round

代码语言:javascript
复制
output = net(value)
predicted = torch.round(output.squeeze())

另外,您要使用相同的值多次调用net(value),这意味着它的输出也要多次计算,因为它需要再次遍历整个网络。这是不必要的,您应该将输出保存在一个变量中。对于这个小网络,它并不明显,但是对于较大的网络,需要花费大量不必要的时间来重新计算输出。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61893786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档