conv2d(
input,#輸入一個4維tesor[batch, in_height, in_width, in_channels]
filter,#同樣是一個4維tensor[filter_height, filter_width, in_channels, out_channels]
strides,#步長,一維tensor表示
padding,#邊界填充,一般有“SAME”,“VALID”
use_cudnn_on_gpu=True,#可選,是否使用cudnn加速
data_format='NHWC',#可選擇,默認爲“NHWC”。 指定輸入和輸出數據的數據格式。 使用默認格式“NHWC”,數據按照 [batch, height, width, channels]的順序存儲。 或者,格式可以是“NCHW”,數據存儲順序爲:[batch,channels,height,width]。
name=None#操作名稱
)
conv2d做二維卷積操作。
看一個例子:
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 15 16:13:33 2017
@author: Administrator
"""
import numpy as np
import tensorflow as tf
#使用reshape構造一個tensor
#TypeError: Value passed to parameter 'input' has DataType int32 not in list of allowed values: float16, float32
'''
input_value = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
filter_value = np.array([1, 2, 3, 4, 5, 6, 7, 8])
'''
#定義常量,一維矩陣
input_value = tf.constant([1, 2, 3, 4, 5, 6, 7,8,9],dtype=tf.float32)
filter_value = tf.constant([1, 0, 1, 0],dtype=tf.float32)
input = tf.reshape(input_value,[1,3,3,1])
filter = tf.reshape(filter_value,[2,2,1,1])
op = tf.nn.conv2d(input,filter,strides = [1,1,1,1],padding ='SAME')
with tf.Session() as sess:
filter=sess.run(filter)
print(filter)
result = sess.run(op)
print(result)
輸出結果:
[[[[ 1.]]
[[ 0.]]]
[[[ 1.]]
[[ 0.]]]]
[[[[ 5.]
[ 7.]
[ 9.]]
[[ 11.]
[ 13.]
[ 15.]]
[[ 7.]
[ 8.]
[ 9.]]]]
可以放在圖片處理上理解:
input[圖片個數,圖片像素高,圖片像素寬,輸入通道A]這是tensor的shape。
filter必須和input保存一樣的shape。[卷積核的高, 卷積核的寬, 輸入通道A(和input一致), 輸出通道]。
tf.reshape(input_value,[1,3,3,1]):表示有一張照片,大小3*3,輸入通道1
filter = tf.reshape(filter_value,[2,2,1,1]):kernel爲2*2,輸入通道1,輸出通道1。
圖形解釋一下,上面的代碼。
如果使用VALID填充。修改一行代碼。
op = tf.nn.conv2d(input,filter,strides = [1,1,1,1],padding =’VALID’)
[[[[ 1.]]
[[ 0.]]]
[[[ 1.]]
[[ 0.]]]]
[[[[ 5.]
[ 7.]]
[[ 11.]
[ 13.]]]]
平時工作比較忙,抽時間把計算過程再講一邊。