tf.reduce_*系列是tensorflow中对张量计算最常用的一个API,主要作用就是对指定维度的张量进行数学计算,并降维(指定维度数值计算后消失)
以tf.reduce_mean为例,能对指定维度进行求均值操作
tf.reduce_mean(
input_tensor, axis=None, keepdims=False, name=None
)
参数 | 注解 |
---|---|
input_tensor | 输入 |
axis | 指定维度,如果为None(默认),对所有维度进行操作 |
keepdims | 保持原有输入维度,即指定降维维度保持长度为1 |
name | 命名 |
比如第一张高4, 宽4,3色的图
img1 = tf.random.normal([4,4,3])
在3色通道(axis=2)求平均后
tf.reduce_mean(img1, axis=2)
<tf.Tensor: shape=(5, 4), dtype=float32, numpy=
array([[-0.9854448 , -1.0194012 , 1.4945674 , -3.3110707 ],
[ 1.5118184 , 1.2675568 , -0.02910066, -2.9339857 ],
[ 2.526368 , 0.7716782 , -0.24042308, -1.1135492 ],
[ 0.81224906, 1.0296633 , 1.6201943 , 2.174279 ],
[ 0.06326652, 0.9522829 , -1.2772858 , -2.5536993 ]],
dtype=float32)>
axis维度求均值后消失,变成一个高5,宽4的灰度图
再比如对于同一张图片,引入batch维度后
img2 = tf.random.normal([1,4,4,3])
对画面的高和宽取全局平均
tf.reduce_mean(img2, axis=[1,2])
<tf.Tensor: shape=(1, 3), dtype=float32, numpy=array([[-0.29505053, 0.18306601, 0.0032706 ]], dtype=float32)>
此操作过程与GlobalAveragePooling2D相同
tf.keras.layers.GlobalAveragePooling2D()(img2)