# 比较与torch.nn.MaxPool2d的功能差异

## torch.nn.MaxPool2d

```torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)(input) -> Tensor
```

## mindspore.nn.MaxPool2d

```mindspore.nn.MaxPool2d(kernel_size=1, stride=1, pad_mode="valid", padding=0, dilation=1, return_indices=False, ceil_mode=False, data_format="NCHW")(x) -> Tensor
```

## 差异对比

PyTorch：对输入的多维数据进行二维的最大池化运算。

MindSpore：MindSpore此API实现功能同时兼容TensorFlow和PyTorch，`pad_mode` 为 “valid” 或者 “same” 时，功能与TensorFlow一致，`pad_mode` 为 “pad” 时，功能与PyTorch一致，MindSpore相比PyTorch1.8.1额外支持了维度为2的输入，与PyTorch1.12一致。

PyTorch

MindSpore

kernel_size

kernel_size

stride

stride

dilation

dilation

return_indices

return_indices

ceil_mode

ceil_mode

input

x

-

-

data_format

### 代码示例1

```# PyTorch
import torch
from torch import tensor
import numpy as np

pool = torch.nn.MaxPool2d(kernel_size=3, stride=1)
x = tensor(np.random.randint(0, 10, [1, 2, 4, 4]), dtype=torch.float32)
output = pool(x)
result = output.shape
print(tuple(result))
# (1, 2, 2, 2)

# MindSpore
import mindspore
from mindspore import Tensor
import numpy as np

pool = mindspore.nn.MaxPool2d(kernel_size=3, stride=1)
x = Tensor(np.random.randint(0, 10, [1, 2, 4, 4]), mindspore.float32)
output = pool(x)
result = output.shape
print(result)
# (1, 2, 2, 2)
```

### 代码示例2

mindspore为 `pad` 模式时，行为一致。

```# PyTorch
import torch
import numpy as np

np_x = np.random.randint(0, 10, [1, 2, 4, 4])
x = torch.tensor(np_x, dtype=torch.float32)
max_pool = torch.nn.MaxPool2d(kernel_size=2, stride=1, padding=1, dilation=1, return_indices=False)
output = max_pool(x)
result = output.shape
print(tuple(result))
# (1, 2, 5, 5)

# MindSpore
import mindspore as ms
from mindspore import Tensor
import mindspore.nn as nn
import numpy as np

np_x = np.random.randint(0, 10, [1, 2, 4, 4])
x = Tensor(np_x, ms.float32)