weixin_44841652
安好家的小朋友
2020-03-31 15:26

请求大神帮帮我,加载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条回答

为你推荐