How to fix following error 'torch.FloatTensor' object has no attribute 'to'

My code is:

for i, (data, label) in data_gen:
data = data.to(device)
label = label.to(device)
outputs = model_ft(data)
_, preds = torch.max(outputs, 1)
for t, p in zip(label.view(-1), preds.view(-1)):
print(t, p)
confusion_matrix[t.long(), p.long()] += 1

Error message is
‘torch.FloatTensor’ object has no attribute ‘to’

Which line does give you this error?

As I understand it should be in

data = data.to(device)
label = label.to(device)

And this error means data and label already are tensors in GPU and you cloning them again into GPU using .to() method.

I trying to make confusion matrix for this code and gave me this error. Shall I remove data.to(device) ?

video_pred = [np.argmax(x[0]) for x in output]

video_labels = [x[1] for x in output]

print('Accuracy {:.02f}% ({})'.format(
    float(np.sum(np.array(video_pred) == np.array(video_labels))) / len(video_pred) * 100.0,
    len(video_pred)))       

#Accuracy per Class
for i in range(num_class):

    indicies_correct = np.where(np.array(video_pred) == np.array(video_labels))
    
    class_total = np.sum(np.array(video_labels) == i)

    class_correct = np.sum(np.array(video_pred)[indicies_correct ] == i)
    
    print('Class {}: Accuracy {:.02f}%'.format(i, class_correct / class_total * 100))

    
confusion_matrix = torch.zeros(num_class, num_class)

data_gen = enumerate(data_loader)
#with torch.no_grad():

for i, (data, label) in data_gen:
    data = data
    label = label
    outputs = model_ft(data)
    _, preds = torch.max(outputs, 1)
    for t, p in zip(label.view(-1), preds.view(-1)):
        print(t, p)
        confusion_matrix[t.long(), p.long()] += 1

print(confusion_matrix)

print(confusion_matrix.diag()/confusion_matrix.sum(1))

It would be great to test your code without using to method.
I still do not know which line causes this problem. Actually it should not bother you to convert your tensors to GPU because you are getting your items from Dataset class and they are by default on CPU. Or you have some codes somewhere which overrides these rules.

1 Like

@Nikronic I don’t think the tensor in question is already on GPU, since it is of type torch.FloatTensor and not torch.cuda.FloatTensor.

It would be helpful to print the full stacktrace, so we can at least know what line throws the error!

1 Like

Yes, you right! I just forgot about cuda.

1 Like

.to() was introduces in PyTorch 0.4.0 if I’m not mistaken.
If you’re using an older version, you might want to update to the latest release.
You can find the instructions here.

1 Like

Yes you are right I am using pytorch 0.3.0
If I update my pytorch, my current project may stop working or may create new errors. Is this so?

Yes, many things changed with 0.4.0 and 1.0.0 as well. I would create a new virtualenv, make a copy of the code (or commit everything before making changes), and just deal with the errors as they come when running your code…