pythonpytorch

I am getting Attribute error as 'int' object has no attribute 'to'


I am writing a python code in Kaggle notebook for Image Classification. In the training part, I am getting an error

AttributeError                            Traceback (most recent call last)
<ipython-input-22-052723d8ce9d> in <module>
      5     test_loss = 0.0
      6     for images,label in enumerate(train_loader):
----> 7         images,label = images.to(cuda),label.to(cuda)
      8         optimizer.zero_grad()
      9 

AttributeError: 'int' object has no attribute 'to'

This is the following code, (I am giving only 2 parts, pls tell if you need more)

train_loader = torch.utils.data.DataLoader(train_data,batch_size = 128,num_workers =0,shuffle =True)
test_loader = torch.utils.data.DataLoader(test_data,batch_size = 64,num_workers =0,shuffle =False)


epoch = 10

for e in range(epoch):
    train_loss = 0.0
    test_loss = 0.0
    for images,label in enumerate(train_loader):
        images,label = images.to(cuda),label.to(cuda)
        optimizer.zero_grad()

        output = model(images)
        _,predict = torch.max(output.data, 1)
        loss = criterion(output,labels)
        loss.backward()
        optimizer.step()

        train_loss += loss.item()
        train_size += label.size(0)
        train_success += (predict==label).sum().item()


        print("train_accuracy is {.2f}".format(100*(train_success/train_size)) )

Solution

  • I don't know much about the environment you're working in, but this is what goes wrong:

    for images, label in enumerate (train_loader): Puts whatever is in train_loader into label, while images is given a number.

    Try this to see what I mean, and to see what goes wrong:

    for images, label in enumerate(train_loader):
        print(images)
        return
    

    And since images is a number (int), there is no images.to() method associated with images