torch.ones()
生成全部是一的张量
>>> import torch
>>> torch.ones(3,3,2)
tensor([[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]]])
torch.zeros()
生成全部是0的张量
>>> torch.zeros(100)
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0.])
torch.empty()
构造未初始化的张量
>>> torch.empty(2,3,4)
tensor([[[9.9184e-39, 9.0000e-39, 1.0561e-38, 1.0653e-38],
[4.1327e-39, 8.9082e-39, 9.8265e-39, 9.4592e-39],
[1.0561e-38, 1.0653e-38, 1.0469e-38, 9.5510e-39]],
[[9.1837e-39, 1.0561e-38, 1.0469e-38, 9.0000e-39],
[1.0653e-38, 1.0194e-38, 1.0561e-38, 1.0469e-38],
[9.9184e-39, 1.1020e-38, 9.1837e-39, 9.0918e-39]]])
>>>
torch.rand()
构造随机初始化的张量
>>> torch.rand(5, 3)
tensor([[0.0592, 0.5023, 0.6270],
[0.6409, 0.6227, 0.2077],
[0.6330, 0.4515, 0.3797],
[0.5724, 0.4539, 0.1530],
[0.3049, 0.4987, 0.5290]])
torch.tensor()
直接从数据构造张量:
>>> torch.tensor([5.5, 3])
tensor([5.5000, 3.0000])
基于现有张量创建张量。这些方法将重用输入张量的属性,例如dtype
例如:
>>> x = x.new_ones(5, 3, dtype=torch.double)
>>> x
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
>>> x = torch.randn_like(x, dtype=torch.float)
>>> x
tensor([[ 0.7901, 0.8974, -1.0603],
[ 0.1610, -1.0740, -0.3888],
[-0.5199, -0.2940, 0.7985],
[-0.2714, -0.8324, -0.0605],
[-1.8033, -2.4175, -1.0226]])