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

Question:

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)) )
Asked By: Stark_Tony

||

Answers:

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

Answered By: Ayam

I had the same problem and after doing what Ayam said,

I got this result after printing images

1

and this clearly explaines why i got the error.

I managed to resolve this by using

images, label in (train_loader) 

instead of

images, label in enumerate(train_loader)

Ps When running the above code snippets, the for loop keep going on

ie when i used batch size = 4 I am getting more than 4 labels and images.

2

Answered By: Panashe Chisasa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.