TensorFlow中nn.conv2d与nn.avg_pool的理解


使用TensorFlow求卷积和池化:

import tensorflow as tf
import numpy as np

M = np.array([
        [[1],[-1],[0]],
        [[-1],[2],[1]],
        [[0],[2],[-2]]
    ])

print ("Matrix shape is: ",M.shape)

filter_weight = tf.get_variable('weights', [2, 2, 1, 1], initializer = tf.constant_initializer([ [1, -1],
                                                 [0, 2]]))
biases = tf.get_variable('biases', [1], initializer = tf.constant_initializer(1))

M = np.asarray(M, dtype='float32')
M = M.reshape(1, 3, 3, 1)
print("Reshaped M: \n", M)

x = tf.placeholder('float32', [1, None, None, 1])
# 在3x3的M的右边和下面补零,卷积窗口每次移动两个单位。得到的conv为2x2的矩阵,再转成高维矩阵--[1, 2, 2, 1]
conv = tf.nn.conv2d(x, filter_weight, strides = [1, 2, 2, 1], padding = 'SAME') 
# 将卷积求得的值加上偏置就为所求值
bias = tf.nn.bias_add(conv, biases)
# 在3x3的M的右边和下面不补零,卷积窗口从左上角每次移动两个单位,遇到数据不足时,只取当前数据。
# 得到的pool为2x2的矩阵,再转成高维矩阵--[1, 2, 2, 1]
pool = tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    convoluted_M = sess.run(bias,feed_dict={x:M})
    pooled_M = sess.run(pool,feed_dict={x:M})
    
    print ("convoluted_M: \n", convoluted_M.reshape(2, 2))
    print ("pooled_M: \n", pooled_M.reshape(2, 2))

输出结果如下:


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fengyuzhe13

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值