TypeError: a float is required for math operations


l have a pytorch variable :

Variable containing:
[torch.cuda.FloatTensor of size 1 (GPU 0)]

l want to do the following :

 import math
 z= y / (y+1)

However when l do :


l get the following error :

TypeError: a float is required

How can l transform a torch variable to a float in order to be able to do these operations ?
or is there any trick to do that in pytorch ?


The Python math module doesn’t work on torch objects. You could get the Python float out of your variable with x.data[0]. However you probably just want to use torch.exp instead of math.exp (torch.exp works on Tensors and Variables). You could also just use x.exp() for the same result, if you prefer that syntax. Generally you want to find the PyTorch function for any mathematical operations you want to perform.

I think it is because the data is in form of Tensor. Meanwhile you doing processing with python math library. My solution is you must convert it to numpy first or you just using Tensor operation in pytorch Tensor Operation . If you want to just calculate using python function you can cast it as numpy array. It is so simple, you can just doing preds.data.numpy() . I also found that your tensor is in GPU so don’t forget to copy it to GPU, so you can use preds.data.cpu().numpy(). Here is the example in figure for clearer.image

More on…Python mathematical operations