【TensorFlow】tf.nn.max_pool实现池化操作
tensorflow
一个面向所有人的开源机器学习框架
项目地址:https://gitcode.com/gh_mirrors/te/tensorflow

·
max pooling是CNN当中的最大值池化操作,其实用法和卷积很类似
有些地方可以从卷积去参考【TensorFlow】tf.nn.conv2d是怎样实现卷积的?
tf.nn.max_pool(value, ksize, strides, padding, name=None)
参数是四个,和卷积很类似:
第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape
第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'
返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]
这种形式
示例源码:
假设有这样一张图,双通道
第一个通道:
第二个通道:
用程序去做最大值池化:
tensorflow
一个面向所有人的开源机器学习框架
项目地址:https://gitcode.com/gh_mirrors/te/tensorflow
import tensorflow as tf
a=tf.constant([
[[1.0,2.0,3.0,4.0],
[5.0,6.0,7.0,8.0],
[8.0,7.0,6.0,5.0],
[4.0,3.0,2.0,1.0]],
[[4.0,3.0,2.0,1.0],
[8.0,7.0,6.0,5.0],
[1.0,2.0,3.0,4.0],
[5.0,6.0,7.0,8.0]]
])
a=tf.reshape(a,[1,4,4,2])
pooling=tf.nn.max_pool(a,[1,2,2,1],[1,1,1,1],padding='VALID')
with tf.Session() as sess:
print("image:")
image=sess.run(a)
print (image)
print("reslut:")
result=sess.run(pooling)
print (result)
这里步长为1,窗口大小2×2,输出结果:
image:
[[[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]]
[[ 8. 7.]
[ 6. 5.]
[ 4. 3.]
[ 2. 1.]]
[[ 4. 3.]
[ 2. 1.]
[ 8. 7.]
[ 6. 5.]]
[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]]]]
reslut:
[[[[ 8. 7.]
[ 6. 6.]
[ 7. 8.]]
[[ 8. 7.]
[ 8. 7.]
[ 8. 7.]]
[[ 4. 4.]
[ 8. 7.]
[ 8. 8.]]]]
池化后的图就是:
证明了程序的结果是正确的。
我们还可以改变步长
pooling=tf.nn.max_pool(a,[1,2,2,1],[1,2,2,1],padding='VALID')
最后的result就变成:
reslut:
[[[[ 8. 7.]
[ 7. 8.]]
[[ 4. 4.]
[ 8. 8.]]]]
推荐内容
阅读全文
AI总结




一个面向所有人的开源机器学习框架
最近提交(Master分支:1 个月前 )
4f64a3d5
Instead, check for this case in `ResolveUsers` and `ResolveOperand`, by querying whether the `fused_expression_root` is part of the `HloFusionAdaptor`.
This prevents us from stepping into nested fusions.
PiperOrigin-RevId: 724311958
1 个月前
aa7e952e
Fix a bug in handling negative strides, and add a test case that exposes it.
We can have negative strides that are not just -1, e.g. with a combining
reshape.
PiperOrigin-RevId: 724293790
1 个月前
更多推荐
相关推荐
查看更多
tensorflow

一个面向所有人的开源机器学习框架
tensorflow

TensorFlow for R
TensorFlow

Project containig related material for my TensorFlow articles
热门开源项目
活动日历
查看更多
直播时间 2025-04-07 14:51:20

樱花限定季|G-Star校园行&华中农业大学专场
直播时间 2025-03-26 14:30:09

开源工业物联实战!
直播时间 2025-03-25 14:30:17

Heygem.ai数字人超4000颗星火燎原!
直播时间 2025-03-13 18:32:35

全栈自研企业级AI平台:Java核心技术×私有化部署实战
直播时间 2025-03-11 18:35:18

从0到1:Go IoT 开发平台的架构演进与生态蓝图
所有评论(0)