【TensorFlow】池化层max_pool中两种paddding操作

max_pool()padding参数有两种模式validsame模式。
Tensorflow的padding和卷积层一样也有padding操作,两种不同的操作输出的结果有区别:

函数原型max_pool(value, ksize, strides, padding, data_format="NHWC", name=None)

这一解释除了tf.nn.max_pool,还适用于tf.nn.conv2dtf.layer.*下的相关函数

if padding = "SAME": 
    output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])
if padding = "VALID": 
    output_spatial_shape[i] = ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i]) / strides[i]).

也就是说

“VALID” 模式,在剩余行列数小于池化窗口大小时,将最右边和最下面的列或行抛弃,只保留有效值;
“SAME” 模式则是在剩余行列数不足时补充0来满足池化窗口的大小,保持窗口被池化区域相同;
所以输出尺寸不是池化窗口的整数倍时,same模式的输出要比valid的大。

#我们来看看函数的定义
#source code:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py  line:2116
@tf_export("nn.max_pool")
def max_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
  """Performs the max pooling on the input.
  Args:
    value: A 4-D `Tensor` of the format specified by `data_format`.
    ksize: A list or tuple of 4 ints. The size of the window for each dimension
      of the input tensor.
    strides: A list or tuple of 4 ints. The stride of the sliding window for
      each dimension of the input tensor.
    padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
      See the "returns" section of `tf.nn.convolution` for details.
    data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.
    name: Optional name for the operation.
  Returns:
    A `Tensor` of format specified by `data_format`.
    The max pooled output tensor.
  """
  with ops.name_scope(name, "MaxPool", [value]) as name:
    value = ops.convert_to_tensor(value, name="input")
    return gen_nn_ops.max_pool(
        value,
        ksize=ksize,
        strides=strides,
        padding=padding,
        data_format=data_format,
        name=name)

#其中pool()函数 padding的代码如下所示
#dilation_rate 默认为1的序列Defaults to [1]*N
#nn_ops.py line876
    If padding = "SAME":
      output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])
    #'same'方法输出尺寸直接为 input_size/strides_size
    
    If padding = "VALID":
      output_spatial_shape[i] =
        ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i])
             / strides[i]).
	#'valid'方法输出尺寸为 [input_size-(pooling_win_size-1)*1]/stride_size

用例子解释一下:
1.@MiniQuark

#"VALID" = without padding:
   inputs:         1  2  3  4  5  6  7  8  9  10 11 (12 13)
                  |________________|                dropped
                                 |_________________|
#"SAME" = with zero padding:
               pad|                                      |pad
   inputs:      0 |1  2  3  4  5  6  7  8  9  10 11 12 13|0  0
               |________________|
                              |_________________|
                                             |________________|

2.@Olivier Moindrot

x = tf.constant([[1., 2., 3.],
                 [4., 5., 6.]])

x = tf.reshape(x, [1, 2, 3, 1])  				#先转为张量输入

valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')   
same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')

valid_pad.get_shape() == [1, 1, 1, 1]  # valid_pad is [5.]       #3,6那一列被丢掉了
|1 2    ...3|
|4 5    ...6|

在这里插入图片描述

same_pad.get_shape() == [1, 1, 2, 1]   # same_pad is  [5., 6.]      #加上了第四列,第二个窗口的max是6
|1 2 3 0|
|4 5 6 0|     ->|5,6|

在这里插入图片描述

在这里插入图片描述
icon from easyicon


ref:
api:https://www.tensorflow.org/api_docs/python/tf/nn/max_pool
blog:https://blog.csdn.net/accumulate_zhang/article/details/78359856
blog:https://blog.csdn.net/wuzqChom/article/details/74785643
stackflow:https://stackoverflow.com/questions/37674306/what-is-the-difference-between-same-and-valid-padding-in-tf-nn-max-pool-of-t
code:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py
gen_nn_ops.max_pool如何得到:
build:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/BUILD#L273
gen_nn.ops:https://stackoverflow.com/questions/41147734/looking-for-source-code-of-from-gen-nn-ops-in-tensorflow

### 解决方案 `AttributeError` 错误通常发生在调用 `nn.Conv2d` 时未提供必需的参数。根据官方文档[^2],`nn.Conv2d` 是一个二维卷积层,其定义如下: ```python torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None) ``` 其中,`in_channels`, `out_channels`, 和 `kernel_size` 是必填参数。如果缺少这些参数之一,则会抛出 `AttributeError`。 以下是可能导致该错误的原因及其解决方案: #### 原因分析与修复方法 1. **缺失必要参数** 如果在实例化 `nn.Conv2d` 时遗漏了某些必要的参数(如 `padding`),则会出现此错误。默认情况下,`padding` 参数为 `0`,但如果显式指定其他值,则需要正确传递给函数。 示例代码展示如何正确初始化 `Conv2d` 层并设置 `padding` 参数: ```python import torch.nn as nn conv_layer = nn.Conv2d( in_channels=3, # 输入通道数 out_channels=64, # 输出通道数 kernel_size=3, # 卷积核大小 stride=1, # 步幅,默认为1 padding=1, # 补零数量 dilation=1, # 膨胀率,默认为1 groups=1, # 组卷积的数量,默认为1 bias=True # 是否使用偏置项,默认为True ) ``` 2. **拼写错误或语法问题** 可能存在键入错误或者变量名冲突的情况。例如,将 `padding` 写成 `paddding` 或者忘记赋值操作符 (`=`) 都可能引发类似的异常。 3. **版本兼容性问题** 不同版本之间可能存在 API 更改。因此建议确认当前使用的 PyTorch 版本是否支持所采用的方法签名。可以运行以下命令检查安装的库版本号: ```bash pip show torch ``` 并查阅对应版本的手册页面验证具体实现细节[^2]。 --- ### 完整示例程序 下面给出一段完整的 Python 程序用于演示如何避免此类错误的发生: ```python import torch from torch import nn class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() # 初始化第一个卷积层 self.conv1 = nn.Conv2d( in_channels=1, out_channels=32, kernel_size=(5, 5), stride=1, padding=2 # 设置合理的补零量以保持输入尺寸不变 ) # 添加激活函数 ReLU self.relu = nn.ReLU() # 最大池化层 Max Pooling Layer self.pool = nn.MaxPool2d(kernel_size=2) def forward(self, x): x = self.conv1(x) x = self.relu(x) x = self.pool(x) return x if __name__ == "__main__": model = SimpleCNN() input_tensor = torch.randn((1, 1, 28, 28)) # 创建模拟数据 (batch size, channels, height, width) output = model(input_tensor) print(f'Output Shape: {output.shape}') ``` 上述脚本构建了一个简单的 CNN 架构,并通过前向传播测试模型功能正常与否。 --- ### 注意事项 当遇到类似问题时,请仔细阅读报错信息定位确切位置;同时参照官方教程学习最佳实践模式有助于减少开发过程中常见陷阱的影响程度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值