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

I am running someone’s code:

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:

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

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:

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.

1 Like

not sure what to do

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 from torchvision and run it on the dataset to make sure your code is working.

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.