python tensorflow基于cnn实现手写数字识别

作者:LN_IOS 时间:2023-05-09 06:22:06 

一份基于cnn的手写数字自识别的代码,供大家参考,具体内容如下


# -*- coding: utf-8 -*-

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 加载数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 以交互式方式启动session
# 如果不使用交互式session,则在启动session前必须
# 构建整个计算图,才能启动该计算图
sess = tf.InteractiveSession()

"""构建计算图"""
# 通过占位符来为输入图像和目标输出类别创建节点
# shape参数是可选的,有了它tensorflow可以自动捕获维度不一致导致的错误
x = tf.placeholder("float", shape=[None, 784]) # 原始输入
y_ = tf.placeholder("float", shape=[None, 10]) # 目标值

# 为了不在建立模型的时候反复做初始化操作,
# 我们定义两个函数用于初始化
def weight_variable(shape):
# 截尾正态分布,stddev是正态分布的标准偏差
initial = tf.truncated_normal(shape=shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)

# 卷积核池化,步长为1,0边距
def 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')

"""第一层卷积"""
# 由一个卷积和一个最大池化组成。滤波器5x5中算出32个特征,是因为使用32个滤波器进行卷积
# 卷积的权重张量形状是[5, 5, 1, 32],1是输入通道的个数,32是输出通道个数
W_conv1 = weight_variable([5, 5, 1, 32])
# 每一个输出通道都有一个偏置量
b_conv1 = bias_variable([32])

# 位了使用卷积,必须将输入转换成4维向量,2、3维表示图片的宽、高
# 最后一维表示图片的颜色通道(因为是灰度图像所以通道数维1,RGB图像通道数为3)
x_image = tf.reshape(x, [-1, 28, 28, 1])

# 第一层的卷积结果,使用Relu作为激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1))
# 第一层卷积后的池化结果
h_pool1 = max_pool_2x2(h_conv1)

"""第二层卷积"""
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

"""全连接层"""
# 图片尺寸减小到7*7,加入一个有1024个神经元的全连接层
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
# 将最后的池化层输出张量reshape成一维向量
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)

"""使用Dropout减少过拟合"""
# 使用placeholder占位符来表示神经元的输出在dropout中保持不变的概率
# 在训练的过程中启用dropout,在测试过程中关闭dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

"""输出层"""
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# 模型预测输出
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# 交叉熵损失
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))

# 模型训练,使用AdamOptimizer来做梯度最速下降
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 正确预测,得到True或False的List
correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y_conv, 1))
# 将布尔值转化成浮点数,取平均值作为精确度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 在session中先初始化变量才能在session中调用
sess.run(tf.global_variables_initializer())

# 迭代优化模型
for i in range(2000):
# 每次取50个样本进行训练
batch = mnist.train.next_batch(50)
if i%100 == 0:
 train_accuracy = accuracy.eval(feed_dict={
  x: batch[0], y_: batch[1], keep_prob: 1.0}) # 模型中间不使用dropout
 print("step %d, training accuracy %g" % (i, train_accuracy))
train_step.run(feed_dict={x:batch[0], y_:batch[1], keep_prob: 0.5})
print("test accuracy %g" % accuracy.eval(feed_dict={
  x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

做了2000次迭代,在测试集上的识别精度能够到0.9772……

来源:http://blog.csdn.net/LN_IOS/article/details/77966232

标签:python,tensorflow,数字识别
0
投稿

猜你喜欢

  • 详解MySQL索引原理以及优化

    2024-01-16 18:18:25
  • Mysql 取字段值逗号第一个数据的查询语句

    2024-01-23 14:29:09
  • Python列表推导式的使用方法

    2023-05-10 07:01:46
  • 在登录触发器错误情况下连接SQL Server的方法

    2024-01-25 19:37:51
  • Python Django框架模板渲染功能示例

    2023-03-12 17:39:03
  • 深入浅出分析Python装饰器用法

    2022-10-25 16:49:02
  • Python中的异常处理学习笔记

    2023-06-26 05:04:29
  • 5个CSS3技术实现设计增强

    2009-09-04 17:04:00
  • JupyterLab远程密码访问实现

    2022-06-04 23:52:26
  • anaconda python3.8安装后降级

    2021-09-12 05:28:51
  • python开启多个子进程并行运行的方法

    2022-02-21 12:33:30
  • 解决tensorflow由于未初始化变量而导致的错误问题

    2023-06-05 17:44:05
  • Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

    2024-04-08 10:55:44
  • 解析:正确的理解SQL Server和XML支持

    2009-01-23 13:52:00
  • Go语言中如何确保Cookie数据的安全传输

    2024-05-22 10:21:43
  • ThinkPHP3.1.2 使用cli命令行模式运行的方法

    2023-11-14 12:56:27
  • OpenCV学习之图像加噪与滤波的实现详解

    2022-09-20 04:40:57
  • 使用Pytorch实现two-head(多输出)模型的操作

    2023-08-20 07:00:05
  • Javascript浅拷贝与深拷贝实现

    2013-07-16 22:47:46
  • 改进SQL Server数据库系统安全五步走

    2009-01-20 11:47:00
  • asp之家 网络编程 m.aspxhome.com