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


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com