文章目录
张量的简要介绍
在Pytorch
中,张量(torch.Tensor
)是最基本的数据结构,其重要性可类比于Spark
中的rdd
,Numpy
中的ndarray
,Pandas
中的DataFrame
。
张量和ndarray
有很多异曲同工之处,如索引、线性代数、广播机制等。不过,张量额外提供了GPU计算 自动求梯度等功能,更加适用于深度学习。
如何创建一个张量
创建张量的方法有很多,且类似于Numpy
中创建ndarray
。下面举几个常用的创建方式:
创建一个空的张量
import torch
x = torch.empty(3, 5)
print(x)
tensor([[ 0.0000e+00, -2.5244e-29, -6.4268e-30, -8.5920e+09, 1.1210e-44],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00]])
返回填充了未初始化数据的张量。张量的形状为3*5。
创建一个0张量
x = torch.zeros(3, 5)
print(x)
tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
创建一个随机张量
x = torch.rand(5, 3)
print(x)
tensor([[0.4105, 0.4467, 0.9016],
[0.6860, 0.0143, 0.0723],
[0.2301, 0.2465, 0.8574],
[0.9940, 0.3832, 0.1964],
[0.3754, 0.0219, 0.3208]])
根据现有数据创建Tensor
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = torch.tensor(array)
print(x)
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
根据现有Tensor
创建Tensor
该方法会重用输入Tensor
的一些属性(torch.dtype、torch.device)
x = torch.tensor([1, 2, 3], dtype=torch.long)
y = x.new_ones(5, 3)
z = torch.rand_like(x, dtype=torch.float)
print(x)
print(y)
print(z)
tensor([1, 2, 3])
tensor([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
tensor([0.7695, 0.3723, 0.5159])
更多创建Tensor的方法
张量的属性
tensor.dtype
torch.dtype
属性标识了 torch.Tensor
的数据类型。PyTorch 有八种不同的数据类型:
tensor.device
x = torch.tensor([1, 2, 3])
print(x.device)
device(type='cpu')
[torch.device](https://pytorch.apachecn.org/docs/1.0/tensor_attributes.html#torch.torch.device)
属性标识了[torch.Tensor](https://pytorch.apachecn.org/docs/1.0/tensors.html#torch.Tensor)
对象在创建之后所存储在的设备名称,而在对象创建之前此属性标识了即将为此对象申请存储空间的设备名称。
[torch.device](https://pytorch.apachecn.org/docs/1.0/tensor_attributes.html#torch.torch.device)
包含了两种设备类型 ('cpu'
或者 'cuda'
) ,分别标识将Tensor对象储存于cpu内存或者gpu内存中,同时支持指定设备编号,比如多张gpu,可以通过gpu编号指定某一块gpu。 如果没有指定设备编号,则默认将对象存储于current_device()当前设备中; 举个例子, 一个[torch.Tensor](https://pytorch.apachecn.org/docs/1.0/tensors.html#torch.Tensor)
对象构造函数中的设备字段如果填写'cuda'
,那等价于填写了'cuda:X'
,其中X是函数 [torch.cuda.current_device()](https://pytorch.apachecn.org/docs/1.0/cuda.html#torch.cuda.current_device)
的返回值。
在[torch.Tensor](https://pytorch.apachecn.org/docs/1.0/tensors.html#torch.Tensor)
对象创建之后,可以通过访问[Tensor.device](https://pytorch.apachecn.org/docs/1.0/tensors.html#torch.Tensor.device)
属性实时访问当前对象所存储在的设备名称。
[torch.device](https://pytorch.apachecn.org/docs/1.0/tensor_attributes.html#torch.torch.device)
对象支持使用字符串或者字符串加设备编号这两种方式来创建:
# 通过字符串创建:
>>> torch.device('cuda:0')
device(type='cuda', index=0) # 编号为0的cuda设备
>>>