本期继续介绍pytorch中,tensor的建立方法。
使用rand函数进行tensor初始化:
rand函数会随机产生0~1之间的数值(不包括1)。
在pytorch中使用torch.rand(d1, d2)来建立tensor
# torch.rand(d1, d2)
a = torch.rand(3, 3)
print(a)输出
tensor([[0.2509, 0.6947, 0.8994],
[0.9532, 0.8325, 0.1682],
[0.3213, 0.0603, 0.1677]])若使用rand_like的函数,torch.rand_like(a)表示接收的参数不再是shape,而是tensor类型。将上面的a的shape读出来后,再送给rand函数。
b = torch.rand_like(a)
print(b)输出
tensor([[0.9398, 0.4583, 0.7190],
[0.6468, 0.1100, 0.3356],
[0.6659, 0.2104, 0.5645]])同样为3行3列的tensor
若想指定范围,生成一个矩阵,API为:torch.randint(min, max, [d1, d2])
# torch.randint(min, max, [d1, d2])
c = torch.randint(1, 10, [4, 5])
print(c)tensor([[8, 1, 5, 5, 3],
[7, 7, 7, 8, 7],
[3, 5, 8, 8, 2],
[3, 9, 3, 9, 2]])若想构建呈正态分布的tensor矩阵,API为:torch.randn(d1, d2)
a = torch.randn(2, 2)
print(a)输出
tensor([[-0.2776, 0.9721],
[-1.1160, 1.7064]])加入N(均值, 方差)参数可以进一步调参
若想自己设置相应的均值和方差,
b = torch.normal(mean=torch.full([10], 0), std=torch.arange(1, 0, -0.1))
# mean=torch.full([10], 0)生成长度为10,数值均为0的向量([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])。方差有1至0慢慢减少。
print(b)输出
tensor([-1.1304, -1.3701, 0.2754, 1.0300, -1.3834, -0.5762, 0.2491, 0.1440,
-0.0219, 0.0741])# 当想构建指定shape和全为某一数值的数组时。API:torch.full([d1, d2], a)
a = torch.full([3, 3], 2)
print(a)
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]])当想生成标量时,由于dim=0,因此可将前面的shape空着
a = torch.full([], 2)
print(a)tensor(2.)当然想生成一维张量时,
a = torch.full([1], 2)
print(a)tensor([2.])当想生成等差数列时,API: torch.arange(min, max)
a = torch.arange(0, 10)
print(a)tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])想每隔一段间距输出时,改API为:torch.arange(min, max, a)
a = torch.arange(1, 9, 3)
print(a)tensor([1, 4, 7])创建等分数列,torch.linspace(start, end, steps=a)
这里的a为数量值
a =torch.linspace(1, 9, steps=4)
# 将1至9平均4等分
print(a)tensor([1.0000, 3.6667, 6.3333, 9.0000])同样:torch,logspace(start, end, steps=a )
a =torch.logspace(0, -1, steps=10)
# 将0至-1,十等分,返回10的(均分数值)次幂
print(a)tensor([1.0000, 0.7743, 0.5995, 0.4642, 0.3594, 0.2783, 0.2154, 0.1668, 0.1292,
0.1000])当想生成全部为0,或全部为1的数组时:torch.ones(d1, d2) torch.zeros(d1, d2)。
a = torch.ones(2, 2)
b = torch.zeros(2, 2)
print(a)
print(b)输出
tensor([[1., 1.],
[1., 1.]])
tensor([[0., 0.],
[0., 0.]])当生成对角矩阵时,torch.eye(3, 3)
a = torch.eye(3, 3)
print(a)tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])另外randperm(随机打散)应用也较多,torch.randperm(a)
a = torch.randperm(5)
print(a)生成了0至4,5个索引
tensor([4, 3, 2, 1, 0])