AttributeError: 'str' object has no attribute 'cuda' for images = images.cuda()

Mona_Jalal: <p>I am running someone’s code:</p>
<pre><code class="lang-auto">torch.autograd.set_detect_anomaly(True)
network = Network()
network.cuda()    

criterion = nn.MSELoss()
optimizer = optim.Adam(network.parameters(), lr=0.0001)

loss_min = np.inf
num_epochs = 10

start_time = time.time()
for epoch in range(1,num_epochs+1):
    
    loss_train = 0
    loss_valid = 0
    running_loss = 0
    
    network.train()
    for step in range(1,len(train_loader)+1):
    
        images, landmarks = next(iter(train_loader))
        
        images = images.cuda()
        landmarks = landmarks.view(landmarks.size(0),-1).cuda() 
        
        predictions = network(images)
        
        # clear all the gradients before calculating them
        optimizer.zero_grad()
        
        # find the loss for the current step
        loss_train_step = criterion(predictions, landmarks)
        
        # calculate the gradients
        loss_train_step.backward()
        
        # update the parameters
        optimizer.step()
        
        loss_train += loss_train_step.item()
        running_loss = loss_train/step
        
        print_overwrite(step, len(train_loader), running_loss, 'train')
        
    network.eval() 
    with torch.no_grad():
        
        for step in range(1,len(valid_loader)+1):
            
            images, landmarks = next(iter(valid_loader))
        
            images = images.cuda()
            landmarks = landmarks.view(landmarks.size(0),-1).cuda()
        
            predictions = network(images)

            # find the loss for the current step
            loss_valid_step = criterion(predictions, landmarks)

            loss_valid += loss_valid_step.item()
            running_loss = loss_valid/step

            print_overwrite(step, len(valid_loader), running_loss, 'valid')
    
    loss_train /= len(train_loader)
    loss_valid /= len(valid_loader)
    
    print('\n--------------------------------------------------')
    print('Epoch: {}  Train Loss: {:.4f}  Valid Loss: {:.4f}'.format(epoch, loss_train, loss_valid))
    print('--------------------------------------------------')
    
    if loss_valid &lt; loss_min:
        loss_min = loss_valid
        torch.save(network.state_dict(), '/content/face_landmarks.pth') 
        print("\nMinimum Validation Loss of {:.4f} at epoch {}/{}".format(loss_min, epoch, num_epochs))
        print('Model Saved\n')
     
print('Training Complete')
print("Total Elapsed Time : {} s".format(time.time()-start_time))
</code></pre>
<p>And I am getting this error:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
&lt;ipython-input-54-c0d2605b8aa6&gt; in &lt;module&gt;
     21         images, landmarks = next(iter(train_loader))
     22 
---&gt; 23         images = images.cuda()
     24         landmarks = landmarks.view(landmarks.size(0),-1).cuda()
     25 

AttributeError: 'str' object has no attribute 'cuda'
</code></pre>

neem-41: <p>It looks like images is a String. Is it the name of images? I believe that you need a tensor to use cuda (not a 100% on this). If images is the name of images you can do the following:</p>
<pre><code class="lang-python">from PIL import Image
from torchvision.transforms import ToTensor

toTensor = ToTensor() # Helps change the image into Tensor

images, landmarks = next(iter(valid_loader))
images = toTensor(Image.open(images)) #Load the image first then turn it into tensor
images = images.cuda() #Put the tensor in cuda
</code></pre>
<p>Then it would follow to what <code>landmarks</code> is as you most likely need to change that to tensor as well.</p>

Mona_Jalal: <p>not sure what to do<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710.png" data-download-href="https://discuss.pytorch.org/uploads/default/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710" title="images"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710_2_690x420.png" alt="images" data-base62-sha1="ksa0hILkJMITO0gF7Xdr2hD5R8A" width="690" height="420" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710_2_690x420.png, https://discuss.pytorch.org/uploads/default/optimized/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710_2_1035x630.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710_2_1380x840.png 2x" data-dominant-color="F2F4F3"><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">images</span><span class="informations">2382×1452 275 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>

neem-41: <p>So it looks like image is just the string “image”. This is not going to work because I am guessing that is not the name of the images you have. My suggestion is to take a look at what your dataset is and make sure it gives out actual image as output. Because right now it seems that your dataset is giving the string “image” as one of the output.</p>
<p>Are you using a custom dataset?<br>
If you just want to test if your code is working properly, you can always use one of the <a href="https://pytorch.org/docs/stable/torchvision/datasets.html#mnist" rel="noopener nofollow ugc">datasets</a> from torchvision and run it on the dataset to make sure your code is working.</p>

Shehana_Iqbal: <p>Please check if your ‘__ getitem __()’ function from the torch.utils.data.Dataset class returns a dictionary. ( Something similar to what’s given below.)</p>
<p>{<br>
‘images’ : ____ ,<br>
‘landmarks’ : ____,<br>
}</p>
<p>if that is the keys, instead of images = images.cuda(), use<br>
images = dict.get(‘images’) where dict refers to the dictionary returned at each iteration.</p>