tf.nn.conv2d 是tensorflow中面实现卷积层的函数,这是在搭建卷积神经网络卷积层中的核心方法。
函数参数
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
-
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相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维 -
strides:卷积时在图像每一维的步长,这是一个一维的向量,长度为4
(形如[1,2,2,1]) -
padding:只能为"SAME"或 “VALID” 其中之一,这个值决定了两种的卷积方式
-
use_cudnn_on_gpu:是否使用cudnn加速,默认值为true(bool型变量)
-
name:指定该操作的name。
返回值也为一个Tensor,就是我们常说的feature map,shape是[batch_size, height, width, channels]这种形式。
实例
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_sample_images
import matplotlib.pyplot as plt
dataset=np.array(load_sample_images().images,dtype=np.float32)
batch_size,height,width,channels=dataset.shape
#print(batch_size,height,width,channels) --> 2 427 640 3
filters_test=np.zeros(shape=(7,7,channels,2),dtype=np.float32)
filters_test[:3:,0]=1
filters_test[3:,:,1]=1
X=tf.placeholder(tf.float32,shape=(None,height,width,channels))
convolution=tf.nn.conv2d(X,filters_test,strides=[1,2,2,1],padding="SAME")
with tf.Session() as sess:
output=sess.run(convolution,feed_dict={X:dataset})
plt.imshow(output[0,:,:,1])
plt.show()
原图: (plt.imshow(dataset[0,:,:,1])
)
输出结果: