使用tf.reduce_mean()做avg_pool

本文介绍了如何在TensorFlow中使用tf.reduce_mean()函数进行平均池化操作。对于二维张量,0轴表示按列取平均,1轴表示按行取平均;对于三维张量,0轴表示按宽,1轴表示按高,2轴表示按长。通过示例解释了如何对不同维度的张量进行平均值计算,并指出该操作保持了输出维度与输入维度相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

reduce_mean(
    input_tensor,
    axis=None,
    keepdims=None,
    name=None,
    reduction_indices=None,
    keep_dims=None
)

axis表示按那个维度进行取平均值,当axis参数为list时,会按照list的值依次进行取平均,对于二维张量其取值有01,表示两个维度;当三维张量时其取值可以有012,表示三个维度,否则会出错

  • 对于二维张量
    0表示按列取平均
    1表示按行取平均
  • 对于三维张量:如图1,
    0标志按宽,也就是张量的第一个维度
    1表示按高,也就是张量的第二个维度
    2表示按长,也就是张量的第三个维度
    7239122-77aa931e6fea6fdc.png
    图1

    可以这样理解:对于如下这个数组

class CBAMLayer(tf.keras.layers.Layer): def __init__(self, reduction_ratio=16, **kwargs): super(CBAMLayer, self).__init__(**kwargs) self.reduction_ratio = reduction_ratio def build(self, input_shape): channel = input_shape[-1] self.shared_layer_one = layers.Dense(channel // self.reduction_ratio, activation='relu') self.shared_layer_two = layers.Dense(channel) self.conv2d = layers.Conv2D(1, kernel_size=7, padding='same', activation='sigmoid') def call(self, input_feature): x = tf.cast(input_feature, tf.float32) # 统一数据类型 # Channel attention avg_pool = tf.reduce_mean(x, axis=[1, 2], keepdims=True) max_pool = tf.reduce_max(x, axis=[1, 2], keepdims=True) avg_out = self.shared_layer_two(self.shared_layer_one(avg_pool)) max_out = self.shared_layer_two(self.shared_layer_one(max_pool)) cbam_feature = tf.nn.sigmoid(avg_out + max_out) cbam_feature = tf.cast(cbam_feature, x.dtype) # 统一数据类型 channel_refined = x * cbam_feature avg_spatial = tf.reduce_mean(channel_refined, axis=-1, keepdims=True) max_spatial = tf.reduce_max(channel_refined, axis=-1, keepdims=True) concat = tf.concat([avg_spatial, max_spatial], axis=-1) spatial_attention = self.conv2d(concat) refined_feature = channel_refined * spatial_attention return channel_refined # Spatial attention avg_spatial = tf.reduce_mean(channel_refined, axis=-1, keepdims=True) max_spatial = tf.reduce_max(channel_refined, axis=-1, keepdims=True) concat = tf.concat([avg_spatial, max_spatial], axis=-1) spatial_attention = self.conv2d(concat) refined_feature = channel_refined * spatial_attention return tf.cast(refined_feature, input_dtype) def get_config(self): config = super(CBAMLayer, self).get_config() config.update({'reduction_ratio': self.reduction_ratio}) return
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值