- cpu:torch.IntTensor
- gpu:torch.cuda.IntTensor
- a = torch.rand(1, 2, 3) # dim=3,shape=[1,2,3],随机取0~1之间的数
- b = a[0] # 在第一个维度上取,得到的就是shape=[2,3]的dim=2的Tensor
- a = np.array([2, 3.3])
- a = torch.from_numpy(a) # torch.DoubleTensor
- a = torch.FloatTensor([2, 3.3]) # 尽量少用这种方式,容易和给shape的情况看混淆
- b = torch.tensor([2, 3.3]) # 现有list时尽量用这种方式
- # 注意小写的tensor只接受现有的数据;而大写的Tensor相当于就是FloatTensor,既可以接收现有的数据,也可以接受shape来创建指定形状的Tensor。
- # shape=2,3,所使用的相同的元素为7
- b = torch.full([2, 3], 7)
c = torch.arange(0, 8, 2) # tensor([0, 2, 4, 6]) a = torch.randn(2, 3) # 2行3列,正态分布~N(0,1) 得到的是torch.FloatTensor类型的数据 - # 生成2行3列的数据
- a = torch.empty(2, 3)
- b = torch.FloatTensor(2, 3)
- c = torch.IntTensor(2, 3)
a = torch.rand(3, 3) 随机初始化:
形如*_like接受一个Tensor,将这个Tensor的shape读取出来之后在送入*所表示的函数
- # 下面的rand_like(a)即将a的shape=3,3读出来传给torch.rand()函数
- b = torch.rand_like(a)
在区间[1,10)上随机采样,生成shape=2,2的LongTensor
c = torch.randint(1, 10, [2, 2]) - w1 = torch.randn(200, 784, requires_grad=True)
- torch.nn.init.kaiming_normal_(w1)
torch.set_default_tensor_type(torch.DoubleTensor) - # 取出a这个Tensor中大于0.5的元素
- a = torch.randn(3, 4)
- print(a)
- x = a.ge(0.5)
- print(x)
- print(a[x])
- print(a.unsqueeze(0).shape) # 在0号维度位置插入一个维度
- print(a.unsqueeze(-1).shape) # 在最后插入一个维度
- print(a.unsqueeze(3).shape) # 在3号维度位置插入一个维度
- a = torch.Tensor(1, 4, 1, 9)
- print(a.shape)
- print(a.squeeze().shape) # 能删除的都删除掉
- print(a.squeeze(0).shape) # 尝试删除0号维度,ok
- print(a.squeeze(2).shape) # 尝试删除2号维度,ok
- print(a.squeeze(3).shape) # 尝试删除3号维度,3号维度是9不是1,删除失败
- b = torch.rand(32)
- f = torch.rand(4, 32, 14, 14)
- # 想要把b加到f上面去
- # 先进行维度增加
- b = b.unsqueeze(1).unsqueeze(2).unsqueeze(0)
- print(b.shape)
-
- # 再进行维度扩展
- b = b.expand(4, -1, 14, 14) # -1表示这个维度保持不变,这里写32也可以
- print(b.shape)
- # 运行结果:torch.Size([1, 32, 1, 1])
- # torch.Size([4, 32, 14, 14])
tensor.t() - d = torch.Tensor(6, 3, 1, 2)
- print(d.transpose(1, 3).contiguous().shape) # 1号维度和3号维度交换
h.permute(0, 2, 3, 1) - a = torch.rand(4, 32, 8)
- b = torch.rand(5, 32, 8)
- print(torch.cat([a, b], dim=0).shape) # torch.Size([9, 32, 8]
- c = torch.rand(4, 3, 32, 32)
- d = torch.rand(4, 3, 32, 32)
- print(torch.stack([c, d], dim=2).shape) # torch.Size([4, 3, 2, 32, 32])
- print(torch.stack([c, d], dim=0).shape) # torch.Size([2, 4, 3, 32, 32])
- a = torch.rand(2, 4, 3, 32, 32)
- a1, a2 = a.split(1, dim=0) # 对0号维度拆分,拆分后每个Tensor取长度1
- print(a1.shape, a2.shape) # torch.Size([1, 4, 3, 32, 32]) torch.Size([1, 4, 3, 32, 32])
- b = torch.rand(4, 3, 32, 32)
- b1, b2 = b.split([2, 1], dim=1) # 对1号维度拆分,拆分后第一个维度取2,第二个维度1
- print(b1.shape, b2.shape) # torch.Size([4, 2, 32, 32]) torch.Size([4, 1, 32, 32])
- c = torch.rand(7, 4)
- c1, c2, c3, c4 = c.chunk(4, dim=0)
- print(c1.shape, c2.shape, c3.shape, c4.shape)
-
- # 结果:torch.Size([2, 4]) torch.Size([2, 4]) torch.Size([2, 4]) torch.Size([1, 4])