[TensorFlow案例教程 #20180106] 卷积神经网络CNN入门案例

作者:jcmp      发布时间:2021-05-13      浏览量:0
卷积神经网络CNN入门案例

卷积神经网络CNN入门案例

关于卷积神经网络的资料网上很多,不再赘述,这里推荐几篇不错,很容易入门的文章

关键部分:TensorFlow中重点,tf.nn.conv2d是怎样实现卷积的?

先上代码

LEVEL=3 # LEVEL代表输出通道数x = tf.placeholder('float32', [1, None, None, 1])filter_weight = tf.get_variable('weights', [2, 2, 1, LEVEL], initializer = tf.constant_initializer(W))conv = tf.nn.conv2d(x, filter_weight, strides=[1, 1, 1, 1], padding='SAME')

最关键参数说明:

输入数据说明

假设现在有幅3x3的图片M如下图,图像深度为1,写成矩阵如下,此时M的shape = (3,3)

但是我们前面说了,输入的图片要满足(1,3,3,1)的形势,所以我们要把M重新reshape成下面的形式:

M.shape = (1, 3, 3, 1)M = np.array([    [        [[1],[2],[3]],        [[4],[5],[6]],        [[7],[8],[9]]    ]        ])

这个矩阵就是下面这么一个鬼,看起来是不是很恶心,不过还好,这个只是TensorFlow用来计算的,我们还是用上面(3x3)的矩阵来计算。

我们假设滤波器的参数为:

同样,W.shape = (2, 2, 1, 3),所以我们要经过一次reshape,TensorFlow认识的矩阵如下:

W = np.array([    [[[1,2,3]],     [[4,5,6]]],    [[[7,8,9]],     [[0,1,2]]]    ])

这个矩阵稍微好一点~

import tensorflow as tfimport numpy as np# M 假设是输入的图像矩阵,图像深度为1M = np.array([    [        [[1],[2],[3]],        [[4],[5],[6]],        [[7],[8],[9]]    ]        ])# M.shape = (1, 3, 3, 1)# M[0,:,:,0] = [[1, 2, 3],#               [5, 6, 7],#               [8, 9, 0]]# filter_weight,权重# [2, 2, 1, 3] 代表 2*2过滤器大小,1代表输入的层数,3代表输出的层数LEVEL = 3W = np.array([    [[[1,2,3]],     [[4,5,6]]],    [[[7,8,9]],     [[0,1,2]]]    ])# W.shape = (2, 2,3,1)# W[:,:,0,0] = [[1, 4],[7, 0]]# W[:,:,0,1] = [[2, 5],[8, 1]]# W[:,:,0,2] = [[3, 6],[9, 2]]filter_weight = tf.get_variable('weights', [2, 2, 1, LEVEL], initializer = tf.constant_initializer(W))biases = tf.get_variable('biases', [LEVEL], initializer = tf.constant_initializer(0))M = np.asarray(M, dtype='float32')x = tf.placeholder('float32', [1, None, None, 1])conv = tf.nn.conv2d(x, filter_weight, strides=[1, 1, 1, 1], padding='SAME')conv_with_bias = tf.nn.bias_add(conv, biases)pool = tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='SAME')with tf.Session() as sess:    tf.global_variables_initializer().run()    convoluted_M = sess.run(conv_with_bias, feed_dict={x: M})    pooled_M = sess.run(pool, feed_dict={x: M})    for i in range(3):        print("convoluted_M",i,':\n', convoluted_M[0,:,:,i])    print("pooled_M: \n", pooled_M)

GITHUB 链接下载

最终的输出为:

convoluted_M 0 : [[ 37.  49.  45.] [ 73.  85.  69.] [ 39.  44.   9.]]convoluted_M 1 : [[  49.   65.   54.] [  97.  113.   84.] [  54.   61.   18.]]convoluted_M 2 : [[  61.   81.   63.] [ 121.  141.   99.] [  69.   78.   27.]]

写成标准的矩阵就是