Tensor 有多种创建方式,如基础构造函数 Tensor()
还有许多与 NumPy
类似的方法, 如 ones()
、eye()
、zeros()
、randn()
等
# 最基础的 Tensor() 函数创建方法, 参数为 Tensor 的每一维大小
a = torch.Tensor(2, 2)
b = torch.DoubleTensor(2, 2)
#使用 Python 的 list 序列化进行创建
c = torch.Tensor([[1, 2], [3, 4]])
#使用 zeros() 函数, 所有元素为 0
d = torch.zeros(2, 2)
#使用 ones() 函数, 所有元素为 1
e = torch.ones(2, 2)
#使用 eye() 函数, 对角线元素为 1, 不要求行列相同
e = torch.eye(2, 2)
#使用 randn() 函数, 生成随机数矩阵
e = torch.randn(2, 2)
#使用 arange(start, end, steps) 函数, 表示 从 start 到 end, 间隔 step 一维向量
h = torch.arange(1, 6, 2)
#使用 linspace(start, end, steps) 函数, 表示 从 start 到 end, step 份 一维向量
i = torch.linspace(1, 6, 2)
#使用 randperm(num) 函数,生成长度为 num 的随机排列向量
j = torch.randperm(4)
# 使用 shape 查看 tensor 的维度
a = torch.randn(2, 2)
a.shape
# 查看 Tensor 中元素的个数
a = torch.randn(2, 2)
a.numel()