TypeError: a float is required for math operations

Hello,

l have a pytorch variable :

preds[4,4]
Out[305]: 
Variable containing:
-96.7809
[torch.cuda.FloatTensor of size 1 (GPU 0)]

l want to do the following :

 import math
 x=preds[4,4]
 y=maths.exp(x)
 z= y / (y+1)

However when l do :

y=maths.exp(x)

l get the following error :

   math.exp(preds[4,4])
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 ?

Thanks

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