主要介绍一下 Tensor 张量创建一些常用的方式:
1. from_numpy()
从 numpy 中导入创建
import numpy
import torch
a = numpy.array([2, 3.3])
b = torch.from_numpy(a)
print(b)
print(b.type())
//输出结果
tensor([2.0000, 3.3000], dtype=torch.float64)
torch.DoubleTensor
2. tensor()
适合创建少量数据的场景
a = torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) # create two-dimensional tensor
b = torch.tensor([0, 1]) # create one-dimensional tensor
c = torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor
d = torch.tensor([]) # Create an empty tensor (of size (0,)) one-dimensional tensor
3. empty()
返回包含未初始化数据的 Tensor
a = torch.empty(2, 3)
print(a)
print(a.shape)
print(a.dim())
//输出结果
tensor([[7.3154e+34, 5.9682e-02, 7.0374e+22],
[5.7886e+22, 6.7120e+22, 6.7331e+22]])
torch.Size([2, 3])
2
4. rand/rand_like, randint,randn
rand():返回一个填充了来自区间上均匀分布的随机数 [0, 1) 的张量
rand_like():返回和输入变量一样 size 的,填充了来自区间上均匀分布的随机数 [0, 1) 的张量
randint():返回一个张量,其中填充了在low(包含)和high(不包含)之间均匀生成的随机整数。
randn():返回一个填充了均值为 0 ,方差为 1 的正态分布的随机值的张量
a = torch.rand(1, 3)
print(a)
b = torch.rand_like(a)
print(b)
c = torch.randint(2, 6, (2, 2))
print(c)
d = torch.randint(4, (2, 2))
print(d)
e = torch.randn(2, 3)
print(e)
//输出结果
tensor([[0.6459, 0.2532, 0.1440]])
tensor([[0.4444, 0.0029, 0.5269]])
tensor([[5, 3],
[3, 4]])
tensor([[1, 3],
[3, 2]])
tensor([[ 0.3961, -0.6548, 0.3599],
[-1.3824, -0.4262, 0.6252]])
5. full,ones,zeros,eye
full(size, fill_value):创建一个大小为size ,值全为fill_value的张量。张量的 dtype 与fill_value一致.
ones():返回一个用标量值1填充的张量,其形状由变量 argument 定义size。
zeros():返回一个用标量值0填充的张量,其形状由变量 argument 定义size
eye():返回一个二维张量,对角线为 1,其他地方为 0
a = torch.full((2, 3), 3.3)
print(a)
b = torch.ones(2, 3)
print(b)
c = torch.zeros(2, 3)
print(c)
d = torch.eye(3, 2)
print(d)
//输出结果
tensor([[3.3000, 3.3000, 3.3000],
[3.3000, 3.3000, 3.3000]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 0.],
[0., 1.],
[0., 0.]])
6.arange/range
arange(start, end, step):返回从 start(包含) 开始,以 step 为步长,到 end(不包含)结束的一维张量 range(start, end, step):回从 start(包含) 开始,以 step 为步长,到 end(包含)结束的一维张量(这个已经被废弃,用 arange())
a = torch.arange(1, 5, 2)
print(a)
b = torch.range(1, 5, 2)
print(b)
//输出结果
tensor([1, 3])
tensor([1., 3., 5.])
7.linspace/logspace
linspace(start, end, step):返回一个 从 start(包含)开始,到 end(包含)结束,间隔为 (end - start)/ (step - 1) 的一维的张量
logspace(start, end, step, base):返回一个以 base 为底,指数为以 (end - start)/ (step - 1)为步长的一维张量
a = torch.linspace(1, 5, 2)
print(a)
b = torch.logspace(0, 5, 2, 2)
print(b)
//输出结果
tensor([1., 5.])
tensor([ 1., 32.])
8.randperm
randperm(n):返回从 0 到 n-1 的 n 个随机整数排列的一维张量
a = torch.randperm(5)
print(a)
//输出结果
tensor([0, 4, 1, 3, 2])