TensorFlow卷積函數tf.nn.conv2d

tf.nn.conv2d

在TensorFlow中使用tf.nn.conv2d實現卷積操作,其格式如下:

 

tf.nn.conv2d(
    input,
    filter,
    strides,
    padding,
    use_cudnn_on_gpu=True,
    data_format='NHWC',
    dilations=[1, 1, 1, 1],
    name=None
)

Returns:
A Tensor. 

input:

指需要做卷積的輸入圖像(tensor),具有[batch,in_height,in_width,in_channels]這樣的4維shape,分別是圖片數量、圖片高度、圖片寬度、圖片通道數,數據類型爲float32或float64。

filter:

相當於CNN中的卷積核,它是一個tensor,shape是[filter_height,filter_width,in_channels,out_channels]:濾波器高度、寬度、圖像通道數、濾波器個數,數據類型和input相同。

strides:

卷積在每一維的步長,一般爲一個一維向量,長度爲4,一般爲[1,stride,stride,1]。

padding:

定義元素邊框和元素內容之間的空間,只能是‘SAME’(邊緣填充)或者‘VALID’(邊緣不填充)。

return:

返回值是Tensor

例子

例1(1個通道1個輸出)

假設我們用一個5*5的矩陣來模擬圖片,定義一個2*2點的卷積核

例1

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 1]))
filter = tf.Variable(tf.constant([-1.0, 0, 0, -1], shape=[2, 2, 1, 1]))
op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
  sess.run(init)
  print("op:\n",sess.run(op))

輸出如下:

op:
[[[[-2.]
[-2.]
[-1.]]

[[-2.]
[-2.]
[-1.]]

[[-1.]
[-1.]
[-1.]]]]

實際過程就是:

 

 

padding='SAME',這種情況tensorflow會先在邊側補0(優先右側和下方),然後經過卷積操作得到結果。

例2(1個通道3個輸出)

我們用三個filter來創造三個輸出:

 

多通道

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 5, 5, 1]))

raw = tf.Variable(tf.constant([-1.0, 0, 0, -1], shape=[2, 2, 1, 1]))
filter=tf.tile(raw,[1,1,1,3])

op=tf.nn.conv2d(input,filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print("op:\n",sess.run(op))

輸出結果:

output

三個filter相同,輸出了三個相同的結果(按列看)

例3(2個通道2個輸出)

例3.png

代碼:

 

import tensorflow as tf
input = tf.Variable(tf.constant(1.0, shape=[1, 3, 3, 2]))

raw = tf.Variable(tf.constant([-1, 9.0, 0, 0,0,0,1,0], shape=[2, 2, 2, 1]))
filter=tf.tile(raw,[1,1,1,2])

op=tf.nn.conv2d(input,filter, strides=[1, 2, 2, 1], padding='SAME')

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(filter))
    print("\nop:\n",sess.run(op))

輸出結果:

filter:

filter.png

這是兩個filter,紅框就是一個卷積核,綠框黃框分別對應着兩個通道。

卷積結果:

 

output.png

輸出就是兩個2x2的矩陣。



作者:PanDong
鏈接:https://www.jianshu.com/p/c72af2ff5393
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發佈了65 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章