利用Tensorflow和matplotlib直觀理解CNN的卷積層與池化層
阿新 • • 發佈:2019-01-10
卷積神經網路,CNN(Convolutional Neural Network),卷積神經網路是一種多層神經網路,擅長處理影象相關的深度學習問題。 與普通神經網路的區別在於,卷積神經網路包含了由卷積層(Convolutional layer)和池化層(Pooling layer)構成的特徵抽取器。 本文旨在通過呼叫tensorflow封裝好的卷積操作和池化操作函式以及python的matplotlib庫,直觀地感受一張圖片經過卷積層和池化層之後的效果,程式碼如下:
#!/usr/bin/python # -*- coding: UTF-8 -*- import matplotlib.pyplot as plt import tensorflow as tf from PIL import Image import numpy img = Image.open('dog.jpg') img_ndarray = numpy.asarray(img, dtype='float32') print(img_ndarray.shape) img_ndarray=img_ndarray[:,:,0] plt.figure() plt.subplot(221) plt.imshow(img_ndarray) w=[[-1.0,-1.0,-1.0], [-1.0,9.0,-1.0], [-1.0,-1.0,-1.0]] with tf.Session() as sess: img_ndarray=tf.reshape(img_ndarray,[1, 633, 650,1]) w=tf.reshape(w,[3,3,1,1]) img_cov=tf.nn.conv2d(img_ndarray, w, strides=[1, 1, 1, 1], padding='SAME') image_data=sess.run(img_cov) print(image_data.shape) plt.subplot(222) plt.imshow(image_data[0,:,:,0]) img_pool=tf.nn.max_pool(img_ndarray, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') image_data = sess.run(img_pool) plt.subplot(223) plt.imshow(image_data[0, :, :, 0]) plt.subplot(224) img_pool = tf.nn.max_pool(img_ndarray, ksize=[1, 4, 4, 1], strides=[1, 4, 4, 1], padding='SAME') image_data = sess.run(img_pool) plt.imshow(image_data[0, :, :, 0]) plt.show()
原始圖片如下:
卷積和池化效果如下: