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

**URL:** <https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469>\
**Category:** vision\
**Created:** [October 6, 2020, 5:30pm UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469 "2020-10-06T17:30:58Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mona\_Jalal](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mona_jalal/32/25715_2.png) [@Mona\_Jalal](https://discuss.pytorch.org/u/Mona_Jalal)\
**Post date:** [October 6, 2020, 5:30pm UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469/1 "2020-10-06T17:30:58Z")

</div>

I am running someone’s code:

```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 < 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))

```

And I am getting this error:

```auto
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-54-c0d2605b8aa6> in <module>
     21 images, landmarks = next(iter(train_loader))
     22 
---> 23 images = images.cuda()
     24 landmarks = landmarks.view(landmarks.size(0),-1).cuda()
     25 

AttributeError: 'str' object has no attribute 'cuda'

```

---

<div class="post-metadata">

**Author:** ![neem-41](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/neem-41/32/27048_2.png) [@neem-41](https://discuss.pytorch.org/u/neem-41)\
**Post date:** [October 6, 2020, 8:41pm UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469/2 "2020-10-06T20:41:22Z")

</div>

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:

```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

```

Then it would follow to what `landmarks` is as you most likely need to change that to tensor as well.

---

<div class="post-metadata">

**Author:** ![Mona\_Jalal](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mona_jalal/32/25715_2.png) [@Mona\_Jalal](https://discuss.pytorch.org/u/Mona_Jalal)\
**Post date:** [October 6, 2020, 9:26pm UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469/4 "2020-10-06T21:26:04Z")

</div>

not sure what to do

 ![images](https://discuss.pytorch.org/uploads/default/original/3X/8/f/8f5a6bcde820ce6c4bea7c03ea46f8a94b9e7710.png)

---

<div class="post-metadata">

**Author:** ![neem-41](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/neem-41/32/27048_2.png) [@neem-41](https://discuss.pytorch.org/u/neem-41)\
**Post date:** [October 7, 2020, 8:32pm UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469/5 "2020-10-07T20:32:01Z")

</div>

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.

Are you using a custom dataset?  
If you just want to test if your code is working properly, you can always use one of the [datasets](https://pytorch.org/docs/stable/torchvision/datasets.html#mnist) from torchvision and run it on the dataset to make sure your code is working.

---

<div class="post-metadata">

**Author:** ![Shehana\_Iqbal](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/shehana_iqbal/32/31769_2.png) [@Shehana\_Iqbal](https://discuss.pytorch.org/u/Shehana_Iqbal)\
**Post date:** [November 25, 2021, 5:29am UTC](https://discuss.pytorch.org/t/attributeerror-str-object-has-no-attribute-cuda-for-images-images-cuda/98469/6 "2021-11-25T05:29:11Z")

</div>

Please check if your ‘\_\_ getitem \_\_()’ function from the torch.utils.data.Dataset class returns a dictionary. ( Something similar to what’s given below.)

{  
‘images’ : \_\_\_\_ ,  
‘landmarks’ : \_\_\_\_,  
}

if that is the keys, instead of images = images.cuda(), use  
images = dict.get(‘images’) where dict refers to the dictionary returned at each iteration.
