陈同学爱吃方便面 2020-03-31 15:26 采纳率: 100%
浏览 5988
已采纳

请求大神帮帮我,加载MNIST数据集后,显示IndexError: too many indices for tensor of dimension 0

我想用线性的模型训练一下MNIST数据集,在运行到
def train(epoch):
running_loss = 0.0
for batch_idx,data in enumerate(train_loader):
语句后显示
IndexError: too many indices for tensor of dimension 0
这是为什么呢??甚至都还没到将数据放到模型中训练,应该和模型没关系,我也看了其他人的代码,在加载数据这些代码中也没找到什么问题。所以在这请教一下大神,万分感谢Orz

以下是我的代码:

import  torch
from torch.utils.data import DataLoader
from torchvision import transforms 
from torchvision import datasets
import  torch.nn.functional as F
import torch.optim as optim

batch_size = 64
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307),(0.3081))])

train_dataset = datasets.MNIST(root='./data',
                               train=True,
                               download=True,
                               transform=transform)
train_loader = DataLoader(dataset=train_dataset,
                          shuffle=True,
                          batch_size=batch_size)
test_dataset = datasets.MNIST(root='./data',
                              train=False,
                              download=True,
                              transform=transform)
test_loader = DataLoader(dataset=test_dataset,
                         shuffle=False,
                         batch_size=batch_size)

class Net(torch.nn.Module):
    def __init__(self):#构造函数
        super(Net,self).__init__()
        self.linear1 = torch.nn.Linear(784,512)
        self.linear2 = torch.nn.Linear(512,256)
        self.linear3 = torch.nn.Linear(256,128)
        self.linear4 = torch.nn.Linear(128,64)
        self.linear5 = torch.nn.Linear(64,10)

    def forward(self, x):
        x=x.view(-1,784)
        x = F.relu(self.linear1(x))
        x = F.relu(self.linear2(x))
        x = F.relu(self.linear3(x))
        x = F.relu(self.linear4(x))
        return self.linear5(x)

model = Net()#实例化模型

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(),lr=0.1,momentum=0.5)#lr为学习率

def train(epoch):
    running_loss = 0.0
    for batch_idx,data in enumerate(train_loader):
        inputs, target = data
        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
        running_loss +=loss.item()
        if batch_idx%300 == 299:
            print('[%d,%5d] loss: %.3f' %(epoch+1,batch_idx+1,running_loss/300))
            running_loss = 0.0

if __name__=='__main__':
    for epoch in range(10):
        train(epoch)

  • 写回答

2条回答 默认 最新

  • Bob_tensor 2020-04-03 16:33
    关注

    把transforms.Normalize((0.1307),(0.3081))改为transforms.Normalize((0.1307,),(0.3081,))

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥15 寻找能匹配的液晶显示屏。