pytorch中的view算子 = paddle中的reshape算子
# pytorch
# AvgPool2d比AdaptiveAvgPool2d更快,但是使用View 和 Mean会比AvgPool2d快5倍.
class FastGlobalAvgPool2d(nn.Module):
def __init__(self, flatten=False):
super(FastGlobalAvgPool2d, self).__init__()
self.flatten = flatten
def forward(self, x):
if self.flatten:
in_size = x.size()
return x.view((in_size[0], in_size[1], -1)).mean(dim=2)
else:
return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1)
# paddle
# AvgPool2d比AdaptiveAvgPool2d更快,但是使用View 和 Mean会比AvgPool2d快5倍.
class FastGlobalAvgPool2d(nn.Layer):
def __init__(self, flatten=False):
super(FastGlobalAvgPool2d, self).__init__()
self.flatten = flatten
def forward(self, x):
in_size = x.shape
if self.flatten:
return x.reshape((in_size[0], in_size[1], -1)).mean(axis=-1)
else:
return x.reshape(in_size[0], in_size[1], -1).mean(axis=-1).reshape(in_size[0], in_size[1], 1, 1)
此外:
1:需要注意mean的参数,pytorch中是dim指定维度,paddle中是axis指定维度。