TensorFlow Mnist数据集-卷积神经网络实现

本文使用Mnist数据集对卷积神经网络进行一次体验,主要流程为:

conv1+pool1-->conv2+pool2-->FC1+Drop-->FC2

上述流程使用的参数不同预测的正确率也不同,这个过程就是调参。

导入依赖包:

import tensorflow as tf
import random
import numpy as np
import matplotlib.pyplot as plt
import datetime
%matplotlib inline

加载数据集:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)

设置参数Mnist数据集图像和其对应的标签值:

tf.reset_default_graph()
sess = tf.InteractiveSession()
# 输入值为28*28*1(通道:若为彩色图应为3),而不再是784一长条的像素点。卷积神经网络的输入应该是一个立体的结构
# 输入的图像一般都是正方形(如28*28、256*256、24*24等),正方形的卷积效果比长方形要好
x = tf.placeholder("float", shape = [None, 28,28,1])
y_ = tf.placeholder("float", shape = [None, 10])

设置第一层卷积+池化层(特征提取):

# 5*5卷积窗口,1通道图像。32种不同的卷积核
W_conv1 = tf.Variable(tf.truncated_normal([5 ,5, 1, 32], stddev=0.1))
b_conv1 = tf.Variable(tf.constant(.1, shape = [32]))

# strides=[batchSize,横着滑动步长,竖着滑动步长,通道数],第一个参数和最后一个参数一般都设置为1。padding 99%使用SAME,自动为图像补充
h_conv1 = tf.nn.conv2d(input=x, filter=W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1
# 非线性激活函数对卷积后的特征做映射,卷积+RELU组合
h_conv1 = tf.nn.relu(h_conv1)
# ksize=[batchSize,h,w,通道数];strides滑动两个单元格
h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
“padding=”参数取值
padding取值意义操作后图像的高和宽参数含义
padding=‘SAME’会自动用0填充元素

W:输入图像的size;

F:窗口filter的size;

S:步长;

:对A向上取整

 

 

padding=‘VALID’会舍弃窗口覆盖不到的元素

定义卷积、池化函数:

def conv2d(x, W):
    return tf.nn.conv2d(input=x, filter=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')

第二层卷积+池化层(特征提取)、第一次全连接层+Drop、第二次全连接层:

# 第二个卷积层。32为第一次卷积的特征图数;得到64个图
W_conv2 = tf.Variable(tf.truncated_normal([5 ,5, 32, 64], stddev=0.1))
b_conv2 = tf.Variable(tf.constant(.1, shape = [64]))
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# 全连接层。两次池化后,28 * 28变成了7*7。64张图。把7*7*64转成1024特征
W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))
b_fc1 = tf.Variable(tf.constant(.1, shape = [1024]))
# 把7*7*64的h_pool2变成一个长条
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# 指定保留率
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 第二个全连接层
W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))
b_fc2 = tf.Variable(tf.constant(.1, shape = [10]))

y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

程序加载:

crossEntropyLoss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))
trainStep = tf.train.AdamOptimizer().minimize(crossEntropyLoss)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

sess.run(tf.global_variables_initializer())

batchSize = 50
for i in range(1000):
    batch = mnist.train.next_batch(batchSize)
    # batch[0]为784(28*28)长度的一维数组,需转成四维数组
    trainningInputs = batch[0].reshape([batchSize, 28, 28, 1])
    trainninLabels = batch[1]
    if i%100 ==0:
        train_accuracy = accuracy.eval(session=sess, feed_dict={x: trainningInputs, y_: trainninLabels, keep_prob: 0.5})
        print("step %d, training accuracy %g"%(i, train_accuracy))
    trainStep.run(session=sess, feed_dict={x: trainningInputs, y_: trainninLabels, keep_prob: 0.5})

运行结果:

step 0, training accuracy 0.1
step 100, training accuracy 0.86
step 200, training accuracy 0.98
step 300, training accuracy 1
step 400, training accuracy 0.92
step 500, training accuracy 1
step 600, training accuracy 1
step 700, training accuracy 0.96
step 800, training accuracy 0.98
step 900, training accuracy 1

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值