PyTorch 张量(Tensor)

与TensorFlow类似,PyTorch中的基本数据类型也称为张量(Tensor),张量就是多维数组,在NumPy中用ndarray表示。

创建张量

先看一下我们熟悉的numpy数组例子:

  • 我们使用np.numpy()方法创建numpy数组
  • Type(): 数组的类型。在本例中,它是numpy.ndarray
  • shape(): 数组的形状。行x列
# 导入 numpy 
import numpy as np

# numpy 数组
array = [[1,2,3],[4,5,6]]
first_array = np.array(array) # 2x3 array
print("Array Type: {}".format(type(first_array))) # type
print("Array Shape: {}".format(np.shape(first_array))) # shape
print(first_array)

输出

Array Type: <class 'numpy.ndarray'>
Array Shape: (2, 3)
[[1 2 3]
 [4 5 6]]

接下来,让我们看一下在PyTorch中,创建Tensor的例子。

  • 首先导入pytorch库
  • torch.Tensor方法创建Tensor
  • 查看类型: 数组的类型。在这个例子中它是张量/Tensor
  • 查看形状: 数组的形状。行x列
# 导入 pytorch 库
import torch

# pytorch 数组
tensor = torch.Tensor(array)
print("Array Type: {}".format(tensor.type)) # type
print("Array Shape: {}".format(tensor.shape)) # shape
print(tensor)

输出

Array Type: <built-in method type of Tensor object at 0x00000207E345D4C8>
Array Shape: torch.Size([2, 3])
tensor([[1., 2., 3.],
        [4., 5., 6.]])

ones()方法,rand()方法

与NumPy类似,PyTorch中也有ones方法,rand方法。

  • np.ones () 等价于 torch.ones (),创建张量,并初始化为1
  • np.random.rand () 等价于 torch.rand (), 创建张量,张量中元素值为随机值
# numpy ones
print("Numpy {}\n".format(np.ones((2,3))))

# pytorch ones
print(torch.ones((2,3)))

输出

Numpy [[1. 1. 1.]
 [1. 1. 1.]]


tensor([[1., 1., 1.],
        [1., 1., 1.]])
# numpy random
print("Numpy {}\n".format(np.random.rand(2,3)))

# pytorch random
print(torch.rand(2,3))

输出

Numpy [[0.07142746 0.20832769 0.64509521]
 [0.6406617  0.33394721 0.21811742]]


tensor([[0.6723, 0.4294, 0.9746],
        [0.7391, 0.0999, 0.2413]])

NumPy ndarray 与 PyTorch Tensor 相互转换

NumPy ndarray 与 PyTorch Tensor 之间可以相互转换:

  • torch.from_numpy() ndarray 转换为 tensor
  • tensor.numpy(): 把 tensor 转换为 ndarray
# random numpy array
array = np.random.rand(2,2)
print("{} {}\n".format(type(array),array))

# from numpy to tensor
from_numpy_to_tensor = torch.from_numpy(array)
print("{}\n".format(from_numpy_to_tensor))

# from tensor to numpy
tensor = from_numpy_to_tensor
from_tensor_to_numpy = tensor.numpy()
print("{} {}\n".format(type(from_tensor_to_numpy),from_tensor_to_numpy))

输出

<class 'numpy.ndarray'> [[0.00971464 0.65419774]
 [0.72936692 0.59668125]]


tensor([[0.0097, 0.6542],
        [0.7294, 0.5967]], dtype=torch.float64)


<class 'numpy.ndarray'> [[0.00971464 0.65419774]
 [0.72936692 0.59668125]]


浙ICP备17015664号-1 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载