1. PyTorch vs Numpy

  • Pytorch Tensor vs Numpy(流行的数值计算库)

Conversion Code

NumPy Array ☞ PyTorch Tensor

torch.from_numpy(ndarray)

PyTorch Tensor ☞ NumPy Array

torch.Tensor.numpy()

import torch
import numpy as np

# numpy to tensor
array_n2t = np.arange(1.0, 8.0)
tensor_n2t = torch.from_numpy(array_n2t)

# tensor to numpy
# 默认数据类型为dtype=float32
tensor_t2n = torch.ones(7)
# 若不修改,则默认使用dtype=float32
array_t2n = tensor_t2n.numpy()

array_n2t,tensor_n2t,tensor_t2n, array_t2n
(array([1., 2., 3., 4., 5., 6., 7.]),
 tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64),
 tensor([1., 1., 1., 1., 1., 1., 1.]),
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
  • 注:默认,Numpy数组使用数据类型float64创建,若将其转换为Pytorch张量,将保持相同的数据类型;

  • 但许多Pytorch计算默认使用float32,可使用如下代码转换:
    Array (float64) ☞ Tensor(float64) ☞ Tensor(float32);

tensor = torch.from_numpy(array).type(torch.float32)
import torch
import numpy as np

# numpy to tensor
array_n2t = np.arange(1.0, 8.0)
tensor_n2t = torch.from_numpy(array_n2t)

# change array,keep tensor
array_n2t = array_n2t + 1

# tensor to numpy
tensor_t2n = torch.ones(7)
array_t2n = tensor_t2n.numpy()

# change tensor keep array
tensor_t2n = tensor_t2n + 1

array_n2t,tensor_n2t,array_t2n,tensor_t2n
(array([2., 3., 4., 5., 6., 7., 8.]),
 tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64),
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32),
 tensor([2., 2., 2., 2., 2., 2., 2.]))