How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0? How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0? python python

How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0?


How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0, preferably in a single line?

If x is your numpy array this line should do the trick:

torch.tensor(x, requires_grad=True)

Here is a full example tested with PyTorch 0.4.0:

import numpy as npimport torchx = np.array([1.3, 0.5, 1.9, 2.45])print('np.array:', x)t = torch.tensor(x, requires_grad=True)print('tensor:', t)print('requires_grad:', t.requires_grad)

This gives the following output:

np.array: [1.3  0.5  1.9  2.45]tensor: tensor([ 1.3000,  0.5000,  1.9000,  2.4500], dtype=torch.float64)requires_grad: True

Edit: dtype should be determined by the given dtype of your numpy array x.

I hope this helps.