#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.]]