tf.nn.conv2d是TensorFlow里面實現卷積的函數,參考文檔對它的介紹並不是很詳細,實際上這是搭建卷積神經網絡比較核心的一個方法,非常重要
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
除去name參數用以指定該操作的name,與方法有關的一共五個參數:
第一個參數input:指需要做卷積的輸入圖像,它要求是一個Tensor,具有[batch, in_height, in_width, in_channels]這樣的shape,具體含義是
[訓練時一個batch的圖片數量, 圖片高度, 圖片寬度, 圖像通道數],注意
這是一個4維的Tensor,要求類型為float32和float64其中之一
第二個參數filter:相當於CNN中的卷積核,
它要求是一個Tensor,具有
[filter_height, filter_width, in_channels, out_channels]這樣的shape
,具體含義是[卷積核的高度,
],要求類型與參數input相同,有一個地方需要注意,第三維卷積核的寬度,圖像通道數,卷積核個數
,就是參數input的第四維in_channels
第三個參數strides:卷積時在圖像每一維的步長,這是一個一維的向量,長度4
第四個參數padding:string類型的量,只能是"SAME","VALID"其中之一,這個值決定了不同的卷積方式(后面會介紹)
第五個參數:use_cudnn_on_gpu:bool類型,是否使用cudnn加速,默認為true
結果返回一個Tensor,這個輸出,就是我們常說的feature map
import tensorflow as tf input = tf.Variable([ [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]]) input=tf.reshape(input,[1,4,4,1]) filter = tf.Variable(tf.random_normal([2,2,1,1])) op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID') init=tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(input)) print(sess.run(op)) sess.close()
s輸出結果:
[[[[ 1.]
[ 2.]
[ 3.]
[ 4.]]
[[ 5.]
[ 6.]
[ 7.]
[ 8.]]
[[ 8.]
[ 7.]
[ 6.]
[ 5.]]
[[ 4.]
[ 3.]
[ 2.]
[ 1.]]]]
[[[[ -5.89250851]
[ -7.98477077]
[-10.077034 ]]
[[-12.00638008]
[-12.8220768 ]
[-13.63777256]]
[[-12.93785667]
[-10.84559441]
[ -8.75333118]]]]
參考:http://blog.csdn.net/mao_xiao_feng/article/details/53444333