由 list 生成 Tensor
a = torch.tensor([1., 2, 3, 4, 5])
b = torch.tensor([[1, 2, 3], [4, 5, 6]])
由 ndarray 生成 tensor
c = np.arange(1, 5)
d = torch.from_numpy(c)
print(c, type(c)) # [1 2 3 4] <class 'numpy.ndarray'>
print(d, type(d)) # tensor([1, 2, 3, 4]) <class 'torch.Tensor'>
生成一个单位矩阵
a = torch.eye(3, 3)
print(a)
# tensor([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
生成全是0的矩阵
b = torch.zeros(2, 3)
print(b)
# tensor([[0., 0., 0.],
# [0., 0., 0.]])
生成全是1的矩阵
c = torch.ones(3, 2)
print(c)
# tensor([[1., 1.],
# [1., 1.],
# [1., 1.]])
从1到10,均匀切分成4份
d = torch.linspace(1, 10, 4)
print(d)
# tensor([ 1., 4., 7., 10.])
生成满足均匀分布随机数
e = torch.rand(2, 3)
print(e)
# tensor([[0.3096, 0.8734, 0.0763],
# [0.3694, 0.0324, 0.0278]])
生成满足标准分布随机数,数值范围为 0~1
f = torch.randn(2, 3)
print(f)
# tensor([[ 1.4131, -0.8185, -0.4714],
# [ 0.4335, -0.5326, 1.0282]])
返回所给数据形状相同,值全为0的张量
g = torch.zeros_like(torch.rand(2, 3))
print(g)
# tensor([[0., 0., 0.],
# [0., 0., 0.]])