Sometimes, we need to convert a python float data to pytorch tensor. In this tutorial, we will use some examples to show you how to convert.
Preliminary
Look at example code below:
import torch f = 0.2 x = torch.cos(f) print(x)
Run this code, we will see:
TypeError: cos(): argument ‘input’ (position 1) must be Tensor, not float
It means the python float data f is not a pytorch tensor. However, torch.cos() need a tensor input.
In order to fix this error, we need to convert python float data to pytorch tensor.
How to convert python float to pytorch tensor?
We can use torch.as_tensor() to convert.
For example:
import torch f = 0.2 f = torch.as_tensor(f) x = torch.cos(f) print(x)
Run this code, we will see:
tensor(0.9801)
Morever, if you want to f support gradient, you can do as follows:
f = torch.as_tensor(f) f = torch.nn.Parameter(f, requires_grad=True) x = torch.cos(f) print(x)
Here we use torch.nn.Parameter() to creat a parameter, then we can see:
tensor(0.9801, grad_fn=<CosBackward>)
Understand torch.nn.parameter.Parameter() with Examples – PyTorch Tutorial