tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)dom
第一個參數input:指須要作卷積的輸入圖像,它要求是一個Tensor,具備[batch, in_height, in_width, in_channels]這樣的shape,具體含義是[訓練時一個batch的圖片數量, 圖片高度, 圖片寬度, 圖像通道數],注意這是一個4維的Tensor,要求類型爲float32和float64其中之一,其中圖像通道數:好比rgb24圖像,通道數爲3ide
第二個參數filter:至關於CNN中的卷積核,它要求是一個Tensor,具備[filter_height, filter_width, in_channels, out_channels]這樣的shape,具體含義是[卷積核的高度,卷積核的寬度,圖像通道數,卷積核個數],要求類型與參數input相同,有一個地方須要注意,第三維in_channels,就是參數input的第四維code
第三個參數strides:卷積時在圖像每一維的步長,這是一個一維的向量,長度4orm
第四個參數padding:string類型的量,只能是"SAME","VALID"其中之一,這個值決定了不一樣的卷積方式(後面會介紹)blog
第五個參數:use_cudnn_on_gpu:bool類型,是否使用cudnn加速,默認爲true圖片
結果返回一個Tensor,這個輸出,就是咱們常說的feature map,shape仍然是[batch, height, width, channels]這種形式。
---------------------
舉個例子:input
input = tf.Variable(tf.random_normal([1,10,10,5])) filter = tf.Variable(tf.random_normal([3,3,5,1])) op = tf.nn.conv2d(input,filter,strides=[1,1,1,1],padding ='VALID') print(op)
輸出:string
strides參數由於只有兩維,一般strides取[1,stride,stride,1]it
修改成2試一下效果io
input = tf.Variable(tf.random_normal([1,10,10,5])) filter = tf.Variable(tf.random_normal([3,3,5,1])) op = tf.nn.conv2d(input,filter,strides=[1,2,1,1],padding ='VALID') print(op)
輸出:
*****************************上一個完整的卷積池化的例子**********************
import tensorflow as tf import os import numpy as np import sys import io import cv2 as cv os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' input = tf.Variable(tf.random_normal([1,28,28,1])) filter = tf.Variable(tf.random_normal([5,5,1,32])) filter2 = tf.Variable(tf.random_normal([5,5,32,64])) op = tf.nn.conv2d(input,filter,strides=[1,1,1,1],padding ='SAME') print(op) op = tf.nn.max_pool(op,ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding ='SAME') print(op) op = tf.nn.conv2d(op,filter2,strides=[1,1,1,1],padding ='SAME') print(op) op = tf.nn.max_pool(op,ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding ='SAME') print(op)
輸出以下: