Tensor <——> Numpy
Tensor与Numpy之间可以相互转换:
代码:
[plain] view plaincopy
- import torch
- import numpy as np
- data = np.array([[1,2,3,4,5],[6,7,8,9,10]])
- print(data)
- # numpy -> tensor
- data_tensor = torch.from_numpy(data)
- print(data_tensor)
- # tensor -> numpy
- data_numpy = data_tensor.numpy()
- print(data_numpy)
输出:
[plain] view plaincopy
- [[ 1 2 3 4 5]
- [ 6 7 8 9 10]]
- tensor([[ 1, 2, 3, 4, 5],
- [ 6, 7, 8, 9, 10]], dtype=torch.int32)
- [[ 1 2 3 4 5]
- [ 6 7 8 9 10]]
Variable -> Numpy
Variable可以直接转为Numpy:
[plain] view plaincopy
- import torch
- from torch.autograd import Variable
- # 定义一个Variable
- data = Variable(torch.Tensor([4]),requires_grad = True)
- # Variable -> Numpy
- data_numpy = data.detach().numpy()
- print('Numpy:',data_numpy)
如果把requires_grad改为False,得到的是Tensor:
[plain] view plaincopy
- data_false = Variable(data_tensor,requires_grad = False)
- print(data_false)
输出:
tensor([4.])
Numpy ->Tensor -> Variable
但是Numpy不可以直接转为Variable,所以要借助Tensor进行转换:
[plain] view plaincopy
- # Numpy --> Variable ( Numpy ->Tensor -> Variable )
- # 1. Numpy ->Tensor
- data_tensor = torch.from_numpy(data_numpy)
- print('Tensor:',data_tensor)
- # 2. Tensor -> Variable
- data_Variable = Variable(data_tensor,requires_grad = True)
- print('Variable:',data_Variable)
输出:
[plain] view plaincopy
- Numpy: [4.]
- Tensor: tensor([4.])Variable: tensor([4.], requires_grad=True)
若试图直接将Numpy转为Variable,
data_Variable = Variable(data_numpy)
,会出现如下错误: