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.]]]]
平时工作比较忙,抽时间把计算过程再讲一边。