tensorflow 卷积操作实例 tf.nn.conv2d


#encoding:utf-8
import numpy as np
import tensorflow as tf

#输入数据(图像)
x_image = tf.placeholder(tf.float32, shape = [5, 5])
x = tf.reshape(x_image, [1, 5, 5 ,1])
#filter
W_cpu = np.array([[1, 1, 1], [0, -1, 0], [0, -1 , 1]], dtype = np.float32)
W= tf.Variable(W_cpu)
W = tf.reshape(W, [3, 3, 1, 1])

#步长,卷积类型
strides = [1, 1, 1, 1]
padding = 'VALID'

#卷积
#x的4个参数是[batch, in_height, in_width, in_channels],代表[训练时图片的数量, 图片的高度,图片的宽度,图像通道数]
#y的4个参数是[filter_heigth, filter_width, in_channels, out_channels ],代表[卷积核的高度,卷积核的宽度,图像通道数, 卷积核个数]
#strides:卷积时每一维的步长,这是一个一维的向量,长度为4
#padding':VALID表示without padding SAME with zero padding
y = tf.nn.conv2d(x, W, strides, padding)

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

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	x = sess.run(x, feed_dict = {x_image : x_data})
	W = sess.run(W, feed_dict = {x_image : x_data})
	y = sess.run(y, feed_dict = {x_image : x_data})
print "The shape of X:", x.shape
print x.reshape(5, 5)
print ""

print "The shape of W:" , W.shape
print W.reshape(3, 3)
print ""

print "The shape of y:", y.shape
print y.reshape(3, 3)
print ""

输出:

The shape of X: (1, 5, 5, 1)
[[ 1.  0.  0.  0.  0.]
 [ 2.  1.  1.  2.  1.]
 [ 1.  1.  2.  2.  0.]
 [ 2.  2.  1.  0.  0.]
 [ 2.  1.  2.  1.  1.]]

The shape of W: (3, 3, 1, 1)
[[ 1.  1.  1.]
 [ 0. -1.  0.]
 [ 0. -1.  1.]]

The shape of y: (1, 3, 3, 1)
[[ 1. -1. -4.]
 [ 2.  1.  2.]
 [ 3.  3.  4.]]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值