Pytorch:expand_as() 和 expand()用法

expand的含義:爲1的維度可以變大維度或者維度數增多
tensor_1.expand(size):把tensor_1擴展成size的形狀
tensor_1.expand_as(tensor_2) :把tensor_1擴展成和tensor_2一樣的形狀
在這裏插入圖片描述

import torch
#1
x = torch.randn(2, 1, 1)#爲1可以擴展爲3和4
x = x.expand(2, 3, 4)
print('x :', x.size())
>>> x : torch.Size([2, 3, 4])
#2
#擴展一個新的維度必須在最前面,否則會報錯
x = x.expand(2, 3, 4, 6)
>>> RuntimeError: The expanded size of the tensor (3) must match the existing size (2) at non-singleton dimension 1.
x = x.expand(6, 2, 3, 4)
>>> x : torch.Size([6, 2, 3, 4])
#3
#某一個維度爲-1表示不改變該維度的大小
x = x.expand(6, -1, -1, -1)
>>> x : torch.Size([6, 2, 1, 1])

在這裏插入圖片描述

import torch
#1
x = torch.randn(2, 1, 1)#爲1可以擴展爲3和3 
y = torch.randn(2, 3, 3)
x = x.expand_as(y)
print('x :', x.size())
>>> x : torch.Size([2, 3, 3])
#2
x = torch.randn(2, 2, 2)#爲2不可以擴展爲3和4
y = torch.randn(2, 3, 4)
x = x.expand_as(y)
print('x :', x.size())
>>> RuntimeError: The expanded size of the tensor (4) must match the existing size (2) at non-singleton dimension 2.  Target sizes: [2, 3, 4].
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章