博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
人工智能实践:Tensorflow笔记(五):卷积网络基础与实践
阅读量:2052 次
发布时间:2019-04-28

本文共 6957 字,大约阅读时间需要 23 分钟。

卷积网络

为了避免过拟合现象的发生,我们在实际应用时,往往不会将原始图片直接喂入全连接网络,会先对原始图片进行特征提取,把提取到的特征喂给全连接网络

 

卷积便是一种有效提取图片特征的方法

输出图片边长= (输入图片边长-卷积核长+1)/步长

有时候会在输入图片周围进行全0填充,这样可以保证输出图片的尺寸和输入图片一致

 

池化分为最大池化和均值池化

dropout可以有效减少过拟合

 

Lenet5卷积神经网络模型 

LeNet-5:是Yann LeCun在1998年设计的用于手写数字识别的卷积神经网络,当年美国大多数银行就是用它来识别支票上面的手写数字的,它是早期卷积神经网络中最有代表性的实验系统之一。

LenNet-5共有7层(2个卷积层、2个下抽样层(池化层)、3个全连接层),每层都包含不同数量的训练参数

 

mnist_lenet5_backward.py

# coding:utf-8import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_dataimport mnist_lenet5_forwardimport osimport numpy as npBATCH_SIZE = 100LEARNING_RATE_BASE = 0.005LEARNING_RATE_DECAY = 0.99REGULARIZER = 0.0001STEPS = 50000MOVING_AVERAGE_DECAY = 0.99MODEL_SAVE_PATH = "./model/"MODEL_NAME = "mnist_model"def backward(mnist):    x = tf.placeholder(tf.float32, [        BATCH_SIZE,        mnist_lenet5_forward.IMAGE_SIZE,        mnist_lenet5_forward.IMAGE_SIZE,        mnist_lenet5_forward.NUM_CHANNELS])    y_ = tf.placeholder(tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])    y = mnist_lenet5_forward.forward(x, True, REGULARIZER)    global_step = tf.Variable(0, trainable=False)    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(        logits=y, labels=tf.argmax(y_, 1))    cem = tf.reduce_mean(ce)    loss = cem + tf.add_n(tf.get_collection('losses'))    learning_rate = tf.train.exponential_decay(        LEARNING_RATE_BASE,        global_step,        mnist.train.num_examples / BATCH_SIZE,        LEARNING_RATE_DECAY,        staircase=True)    train_step = tf.train.GradientDescentOptimizer(        learning_rate).minimize(loss, global_step=global_step)    ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)    ema_op = ema.apply(tf.trainable_variables())    with tf.control_dependencies([train_step, ema_op]):        train_op = tf.no_op(name='train')    saver = tf.train.Saver()    with tf.Session() as sess:        init_op = tf.global_variables_initializer()        sess.run(init_op)        ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)        if ckpt and ckpt.model_checkpoint_path:            saver.restore(sess, ckpt.model_checkpoint_path)        for i in range(STEPS):            xs, ys = mnist.train.next_batch(BATCH_SIZE)            reshaped_xs = np.reshape(xs, (                BATCH_SIZE,                mnist_lenet5_forward.IMAGE_SIZE,                mnist_lenet5_forward.IMAGE_SIZE,                mnist_lenet5_forward.NUM_CHANNELS))            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={                                           x: reshaped_xs, y_: ys})            if i % 100 == 0:                print("After %d training step(s), loss on training batch is %g." % (                    step, loss_value))                saver.save(sess, os.path.join(MODEL_SAVE_PATH,                                              MODEL_NAME), global_step=global_step)def main():    mnist = input_data.read_data_sets("./data/", one_hot=True)    backward(mnist)if __name__ == '__main__':    main()

mnist_lenet5_forward.py

# coding:utf-8import tensorflow as tfIMAGE_SIZE = 28NUM_CHANNELS = 1 #灰度图,所以通道数是1#卷积核个数和卷积核大小CONV1_SIZE = 5CONV1_KERNEL_NUM = 32CONV2_SIZE = 5CONV2_KERNEL_NUM = 64FC_SIZE = 512OUTPUT_NODE = 10def get_weight(shape, regularizer):    w = tf.Variable(tf.truncated_normal(shape, stddev=0.1))    if regularizer != None:        tf.add_to_collection(            'losses', tf.contrib.layers.l2_regularizer(regularizer)(w))    return wdef get_bias(shape):    b = tf.Variable(tf.zeros(shape))    return bdef conv2d(x, w):    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')def max_pool_2x2(x):    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')def forward(x, train, regularizer):   #给出前向传播的网络结构    conv1_w = get_weight(        [CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_KERNEL_NUM], regularizer)    conv1_b = get_bias([CONV1_KERNEL_NUM])    conv1 = conv2d(x, conv1_w)    relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_b))    pool1 = max_pool_2x2(relu1)    conv2_w = get_weight(        [CONV2_SIZE, CONV2_SIZE, CONV1_KERNEL_NUM, CONV2_KERNEL_NUM], regularizer)    conv2_b = get_bias([CONV2_KERNEL_NUM])    conv2 = conv2d(pool1, conv2_w)    relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_b))    pool2 = max_pool_2x2(relu2)    pool_shape = pool2.get_shape().as_list()    nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]    reshaped = tf.reshape(pool2, [pool_shape[0], nodes])    fc1_w = get_weight([nodes, FC_SIZE], regularizer)    fc1_b = get_bias([FC_SIZE])    fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_w) + fc1_b)    if train:        fc1 = tf.nn.dropout(fc1, 0.5)    fc2_w = get_weight([FC_SIZE, OUTPUT_NODE], regularizer)    fc2_b = get_bias([OUTPUT_NODE])    y = tf.matmul(fc1, fc2_w) + fc2_b    return y

mnist_lenet5_test.py

# coding:utf-8import timeimport tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_dataimport mnist_lenet5_forwardimport mnist_lenet5_backwardimport numpy as npTEST_INTERVAL_SECS = 5def test(mnist):    with tf.Graph().as_default() as g:        x = tf.placeholder(tf.float32, [            mnist.test.num_examples,            mnist_lenet5_forward.IMAGE_SIZE,            mnist_lenet5_forward.IMAGE_SIZE,            mnist_lenet5_forward.NUM_CHANNELS])        y_ = tf.placeholder(            tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])        y = mnist_lenet5_forward.forward(x, False, None)        ema = tf.train.ExponentialMovingAverage(            mnist_lenet5_backward.MOVING_AVERAGE_DECAY)        ema_restore = ema.variables_to_restore()        saver = tf.train.Saver(ema_restore)        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))        while True:            with tf.Session() as sess:                ckpt = tf.train.get_checkpoint_state(                    mnist_lenet5_backward.MODEL_SAVE_PATH)                if ckpt and ckpt.model_checkpoint_path:                    saver.restore(sess, ckpt.model_checkpoint_path)                    global_step = ckpt.model_checkpoint_path.split(                        '/')[-1].split('-')[-1]                    reshaped_x = np.reshape(mnist.test.images, (                        mnist.test.num_examples,                        mnist_lenet5_forward.IMAGE_SIZE,                        mnist_lenet5_forward.IMAGE_SIZE,                        mnist_lenet5_forward.NUM_CHANNELS))                    accuracy_score = sess.run(                        accuracy, feed_dict={x: reshaped_x, y_: mnist.test.labels})                    print("After %s training step(s), test accuracy = %g" %                          (global_step, accuracy_score))                else:                    print('No checkpoint file found')                    return            time.sleep(TEST_INTERVAL_SECS)def main():    mnist = input_data.read_data_sets("./data/", one_hot=True)    test(mnist)if __name__ == '__main__':    main()

 

复现已有的卷积神经网络

代码

 

 

 

转载地址:http://hfulf.baihongyu.com/

你可能感兴趣的文章
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>
Go语言学习Part4-1:方法和接口
查看>>
Leetcode Go 《精选TOP面试题》20200628 69.x的平方根
查看>>
Leetcode C++ 剑指 Offer 09. 用两个栈实现队列
查看>>
Leetcode C++《每日一题》20200707 112. 路径总和
查看>>
云原生 第十一章 应用健康
查看>>
Leetcode C++ 《第202场周赛》
查看>>
云原生 第十二章 可观测性:监控与日志
查看>>
Leetcode C++ 《第203场周赛》
查看>>
云原生 第十三章 Kubernetes网络概念及策略控制
查看>>
《redis设计与实现》 第一部分:数据结构与对象 || 读书笔记
查看>>
《redis设计与实现》 第二部分(第9-11章):单机数据库的实现
查看>>
算法工程师 面经2019年5月
查看>>
搜索架构师 一面面经2019年6月
查看>>
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>
leetcode 50. Pow(x, n)
查看>>