张量(tensor)比Numpy的ndarray多一些重要功能。张量表示一个数组组成的数组。
- (1)GPU很好地支持加速计算,而Numpy仅支持CPU计算。
- (2)张量类支持自动微分。
1. 数据操作的实现
首先需要导入torch:
import torch
1.1 创建张量
有四种方式可以创建张量。
- 创建随机张量:rand(), randn(), empty()
- 创建指定类型张量:zeros(), ones(), arange()+reshape()
- 利用列表创建张量:torch.tensor([ ])
- 基于已知tensor创建tensor:torch.randn_like()
(1)创建随机张量
- randn
利用torch.randn(x,y)创建随机张量。
torch.randn(2,3)
tensor([[ 0.0422, 0.8539, 0.6049],
[ 0.1894, -0.2011, 0.9607]])
- rand
利用torch.rand(x,y)创建随机张量。
torch.rand(5,3)
tensor([[0.3854, 0.9028, 0.6086],
[0.5852, 0.8518, 0.0370],
[0.0108, 0.4854, 0.4645],
[0.1960, 0.2920, 0.4442],
[0.3127, 0.3314, 0.8453]])
- empty
torch.empty(5,3
tensor([[9.0919e-39, 8.4490e-39, 9.6429e-39],
[8.4490e-39, 9.6429e-39, 9.2755e-39],
[1.0286e-38, 9.0919e-39, 8.9082e-39],
[9.2755e-39, 8.4490e-39, 1.0194e-38],
[9.0919e-39, 8.4490e-39, 9.9184e-39]])
(2)创建指定类型张量
- arange + reshape
利用torch.arrange(n)创建大小为n的从0到N-1的一维张量。在使用reshape()函数改变张量结构。
x = torch.arange(12)
print(x)
X = x.reshape(3,4)
print(X)
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
- zeros(), ones()
创建指定结构的全为0或者全为1的张量。
torch.zeros