pytorch学习笔记(1)
expand向左扩展维度、扩展元素个数
a=t.ones(2,3)
只能在左侧增加维度,而不能在右侧增加维度,也不能在中间增加维度
新增维度的元素个数可以为任意数字
a2=a.expand(1,2,3) print(a2.shape)#torch.Size([1, 2, 3])
|
左侧增加一个维度,元素个数为1 |
a2=a.expand(1,1,2,3) print(a2.shape)#torch.Size([1, 1, 2, 3])
|
左侧增加1个维度,元素个数1 |
a2=a.expand(3,2,3) print(a2.shape)#torch.Size([3, 2, 3]) |
左侧增加1个维度,元素个数复制为3份 |
# a2=a.expand(2,3,1) # print(a2.shape) # RuntimeError: The expanded size of the tensor (1) must match the existing size (3) at non-singleton dimension 2. Target sizes: [2, 3, 1]. Tensor sizes: [2, 3] |
Error:右侧增加维度,报错 |
a2=a.expand(2,1,3) print(a2.shape) # RuntimeError: The expanded size of the tensor (1) must match the existing size (2) at non-singleton dimension 1. Target sizes: [2, 1, 3]. Tensor sizes: [2, 3] |
Error:中间增加维度,报错 |
view扩展一个或者多个维度
a=t.ones(2,3)
扩展维度上的数字(元素个数)只能是1
a2=a.view(1,2,3) print(a2.shape)#torch.Size([1, 2, 3]) |
扩展第0维:[2, 3]→[1, 2, 3] |
a2=a.view(2,1,3) print(a2.shape)#torch.Size([2, 1, 3]) |
扩展第1维:[2, 3]→[2, 1, 3] |
a2=a.view(2,3,1) print(a2.shape)#torch.Size([2, 3, 1]) |
扩展第2维:[2, 3]→[2, 3, 1] |
a2=a.view(1,1,2,3) print(a2.shape)#torch.Size([1, 1, 2, 3]) |
扩展多个维度:[2, 3]→[1, 1, 2, 3] |
a2=a.view(1,1,2,1,1,3,1,1) print(a2.shape)#torch.Size([1, 1, 2, 1, 1, 3, 1, 1]) |
扩展多个维度:[2, 3]→[1, 1, 2, 1, 1, 3, 1, 1] |
a2=a.view(1,1,3,1,1,2,1,1) print(a2.shape)#torch.Size([1, 1, 3, 1, 1, 2, 1, 1]) |
扩展多个维度:[2, 3]→[1, 1, 3, 1, 1, 2, 1, 1] |
unsqueeze扩展一个维度
a=t.ones(2,3)
a2=a.unsqueeze(0) print(a2.shape)# torch.Size([1, 2, 3]) |
扩展第0维:[2, 3]→[1, 2, 3] |
a2=a.unsqueeze(1) print(a2.shape)# torch.Size([2, 1, 3]) |
扩展第1维:[2, 3]→[2, 1, 3] |
a2=a.unsqueeze(2) print(a2.shape)# torch.Size([2, 3, 1]) |
扩展第2维:[2, 3]→[2, 3, 1] |
a2=a.unsqueeze(3) #IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3) |
扩展第3维:Error |