Pytorch没有对全局平均(最大)池化单独封装为一层。需要自己实现。下面有两种简单的实现方式。
- 使用torch.max_pool1d()定义一个网络层。
- 使用nn.AdaptiveMaxPool1d(1)并设置输出维度是1
import torch
import torch.nn as nn
import numpy as np
#第一种方式
class GlobalMaxPool1d(nn.Module):
def __init__(self):
super(GlobalMaxPool1d,self).__init__()
def forward(self, x):
return torch.max_pool1d(x,kernel_size=x.shape[2])
a = torch.tensor(np.arange(24),dtype=torch.float).view(2,3,4).cuda()
gmp1 = GlobalMaxPool1d()
print(gmp1(a))
#第二种方式
gmp2 = torch.nn.AdaptiveMaxPool1d(1)
print(gmp2(a))
运行结果一样。
tensor([[[ 3.],
[ 7.],
[11.]],
[[15.],
[19.],
[23.]]], device='cuda:0')
tensor([[[ 3.],
[ 7.],
[11.]],
[[15.],
[19.],
[23.]]], device='cuda:0')