List object has no attribute 'to'

username: AmrAhmed
cooked: <p>I am new to Pytorch. I am using a pre-trained model (RESNET-50). And i am trying to train this model on MS-COCO dataset using cocoapi.</p>
<p>I have loaded my dataset images and annotations in train loader.</p>
<pre><code class="lang-auto">for epoch in range (epochs):
   for images,labels in train_loader:
         print(type(images))
         print(type(labels))
         print(images.size())
         print(images.dim())
         steps+=1
         images, labels = images.to(device), labels.to(device)
</code></pre>
<p>I got the following output:</p>
<p>&lt;class ‘torch.Tensor’&gt;<br>
&lt;class ‘list’&gt;<br>
torch.Size([64, 3, 224, 224])<br>
4</p>
<p>And i got this Error: I think it is because labels is not a Tensor?<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/f/7f5d0d2ac069702fa2707263c68528aac757ae62.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/7f5d0d2ac069702fa2707263c68528aac757ae62" title="error"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/7/f/7f5d0d2ac069702fa2707263c68528aac757ae62_2_499x375.jpeg" alt="error" data-base62-sha1="iaI020TsJ2W9n107jTiKgRWy1ii" width="499" height="375" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/7/f/7f5d0d2ac069702fa2707263c68528aac757ae62_2_499x375.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/7/f/7f5d0d2ac069702fa2707263c68528aac757ae62_2_748x562.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/7/f/7f5d0d2ac069702fa2707263c68528aac757ae62_2_998x750.jpeg 2x" data-dominant-color="908F8B"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">error</span><span class="informations">1280×960 118 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Can anyone help me with this? Thanks</p>

username: charan_Vjy
cooked: <p>The issue is indeed that labels seem to be a list.<br>
<code>labels = torch.from_numpy(np.asarray(labels))</code> should fix it. Advisably, do this during preprocessing itself.</p>

username: AmrAhmed
cooked: <p>Hello,<br>
when doing:</p>
<pre><code class="lang-auto">   for images,labels in train_loader:
         labels = torch.from_numpy(np.asarray(labels))
         steps+=1
         images, labels = images.to(device), labels.to(device)
         optimizer.zero_grad()
         logps = model(images)
         loss = criterion(logps,labels)
         loss.backward()
....
</code></pre>
<p>I got the following error now<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/6/a/6ae9572d1fb855f050080d8af815c812d2dfa8f0.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/6ae9572d1fb855f050080d8af815c812d2dfa8f0" title="sec"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/6/a/6ae9572d1fb855f050080d8af815c812d2dfa8f0_2_517x291.jpeg" alt="sec" data-base62-sha1="ffMxA6VqSuW5UQacOdbstGyigO4" width="517" height="291" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/6/a/6ae9572d1fb855f050080d8af815c812d2dfa8f0_2_517x291.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/6/a/6ae9572d1fb855f050080d8af815c812d2dfa8f0_2_775x436.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/6/a/6ae9572d1fb855f050080d8af815c812d2dfa8f0_2_1034x582.jpeg 2x" data-dominant-color="ACAAA6"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">sec</span><span class="informations">1280×720 72.2 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: AmrAhmed
cooked: <p>Here is my full code.</p>
<pre><code class="lang-auto">data_dir = "../cocoapi/images"
ann_dir = "../cocoapi/annotations"
#Define transforms for the data
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])
train_transforms= transforms.Compose([transforms.RandomResizedCrop(224),
                                      transforms.RandomHorizontalFlip(),
                                      transforms.ToTensor(),
                                      normalize])
val_transforms= transforms.Compose([transforms.RandomResizedCrop(224),
                                      transforms.RandomHorizontalFlip(),
                                      transforms.ToTensor(),
                                      normalize])

#Pass transforms in here, then run the next cells to see how the transforms look
train_data = torchvision.datasets.CocoDetection(data_dir + '/train2017', ann_dir + '/instances_train2017.json', transform=train_transforms, target_transform=None, transforms=None)
val_data= torchvision.datasets.CocoDetection(data_dir + '/val2017', ann_dir + '/instances_val2017.json', transform=val_transforms, target_transform=None, transforms=None)

train_loader = torch.utils.data.DataLoader(train_data, batch_size= 64 , shuffle= True)
val_loader = torch.utils.data.DataLoader(val_data, batch_size= 64 , shuffle= True)

print('Num training images: ', len(train_data))
print('Num validation images: ', len(val_data))

</code></pre>
<p>loading annotations into memory…<br>
Done (t=12.49s)<br>
creating index…<br>
index created!<br>
loading annotations into memory…<br>
Done (t=0.43s)<br>
creating index…<br>
index created!<br>
Num training images:  118287<br>
Num validation images:  5000</p>
<pre><code class="lang-auto">model = models.resnet50(pretrained= True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

#Freeze our feature parameters
for param in model.parameters():
    param.requires_grad = False
    
classifier= nn.Sequential(
    nn.Linear(2048,512),
    nn.ReLU(),
    nn.Dropout(p=0.2),
    nn.Linear(512,80),
    nn.LogSoftmax(dim=1))
       
model.fc= classifier
criterion= nn.NLLLoss()
optimizer= optim.Adam(model.fc.parameters(), lr=0.003)
model.to(device);
</code></pre>
<p>cpu</p>
<pre><code class="lang-auto">epochs=25
steps=0
running_loss=0
print_every=5

for epoch in range (epochs):   
    for images,labels in train_loader:
        
        steps+=1
        images,labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        logps= model(images)
        loss= criterion(logps,labels)
        loss.backward()
        optimizer.step()
        running_loss+=loss.item()
        
        if step % print_every == 0:
            
            model.eval()
            val_loss=0
            accuracy=0
            
            for images,labels in val_loader:

                images,labels = images.to(device), labels.to(device)
                logps= model(images)
                loss= criterion(logps,labels)
                val_loss+=loss.item()
                
                #Calculate our accuracy
                ps=torch.exp(logps)
                top_ps, top_class = ps.topk(1, dim=1)
                equality= top_class == labels.view(*top_class.shape)
                accuracy+=torch.mean(equality.type(torch.FloatTensor))
                
            print(f"Epoch: {epoch+1}/{epochs}.."
                  f"Train Loss: {running_loss/print_every:.3f}.."
                  f"Val Loss: {val_loss/len(val_loader):.3f}.."
                  f"Val Accuracy: {accuracy/len(val_loader):.3f}")
            
            running_loss=0
            model.train()
</code></pre>
<p>And the error occur in this line <code> images,labels = images.to(device), labels.to(device)</code><br>
labels is a list, and list object has no attribute ‘to’</p>

username: charan_Vjy
cooked: <p>Try this out</p>
<pre><code class="lang-auto">labels = np.asarray(labels)
labels = torch.from_numpy(labels.astype('long'))
</code></pre>