本文介绍了PyTorch中的Tensor类,它相似于Numpy中的ndarray,它构成了在PyTorch中构建神经网络的基础。编程
咱们已经知道张量究竟是什么了,而且知道如何用Numpy的ndarray来表示它们,如今咱们看看如何在PyTorch中表示它们。网络
自从Facebook在2017年初将PyTorch开源以来,它已经在机器学习领域取得了使人瞩目的成绩。它可能没有像TensorFlow那样被普遍采用 --- 它的最初发布时间早于PyTorch一年,背后有Google的支持,而且当神经网络工具迎来新的潮流时,它已经将本身确立为了金牌标准。但PyTorch在研究领域受到了普遍的关注,这种关注大部分来自与Torch自己的关系,以及它的动态计算图。dom
尽管最近个人注意力都在PyTorch上,但这篇文章并非PyTorch的教程。它更多地是介绍PyTorch的Tensor类,这与Numpy的ndarray相似。机器学习
张量基础工具
让咱们来看一下PyTorch的张量基础知识,从建立张量开始(使用Tensor类):学习
import torch # Create a Torch tensor t = torch.Tensor([[1, 2, 3], [4, 5, 6]]) t tensor([[ 1., 2., 3.], [ 4., 5., 6.]])
你可使用两种方式转置一个张量:code
# Transpose t.t() # Transpose (via permute) t.permute(-1,0)
二者都会产生以下输出结果:orm
tensor([[ 1., 4.], [ 2., 5.], [ 3., 6.]])
请注意,两种方式都不会致使原始张量的改变。对象
用view从新塑造张量:blog
# Reshape via view t.view(3,2) tensor([[ 1., 2.], [ 3., 4.], [ 5., 6.]])另外一个例子:
# View again... t.view(6,1) tensor([[ 1.], [ 2.], [ 3.], [ 4.], [ 5.], [ 6.]])很明显,Numpy所遵循的数学约定延续到了PyTorch张量中(我具体指的是行和列的标记符号)。
建立一个张量并用零填充(你能够用ones()来完成相似的操做):
# Create tensor of zeros t = torch.zeros(3, 3) t tensor([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])从正态分布中随机取数并建立张量:
# Create tensor from normal distribution randoms t = torch.randn(3, 3) t tensor([[ 1.0274, -1.3727, -0.2196], [-0.7258, -2.1236, -0.8512], [ 0.0392, 1.2392, 0.5460]])
Tensor对象的形状、维度和数据类型:
# Some tensor info print('Tensor shape:', t.shape) # t.size() gives the same print('Number of dimensions:', t.dim()) print('Tensor type:', t.type()) # there are other types Tensor shape: torch.Size([3, 3]) Number of dimensions: 2 Tensor type: torch.FloatTensor除了在数学概念上,ndarray和Tensor在编程和实例化上也有类似之处。
你能够像切片ndarrays同样切片PyTorch张量,任何使用其余Python结构的人应该都熟悉这一点: