1.全连接层直接实现手写数字神经网络

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data#对于使用FLAGS,则在终端上运行的命令python mnistClassify.py --is_train=0
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer("is_train",1,"指定程序是否为训练")def full_connected():#加载MNIST数据mnist = input_data.read_data_sets("./MNIST/", one_hot=True)#1.建立数据占位符 x[None,784]  y[None,10]with tf.variable_scope("data"):x = tf.placeholder(tf.float32,[None,784])y_true = tf.placeholder(tf.int32,[None,10])#2.建立一个全连接层的神经网络模型with tf.variable_scope("model"):#随机初始化权重和偏置weight = tf.Variable(tf.random_normal([784,10],mean=0.0,stddev=1.0),name="w")bias = tf.Variable(tf.constant(0.0,shape=[10]))y_predict = tf.matmul(x,weight) + bias#3.Softmax交叉熵损失函数, 求出所有样本的损失,然后求平均值with tf.variable_scope("loss"):#求平均交叉损失函数loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))#4.梯度下降求出损失函数with tf.variable_scope("optimizer"):#学习率leaning_rate = 0.1train_op = tf.train.GradientDescentOptimizer(leaning_rate).minimize(loss)#5.计算准确率with tf.variable_scope("acc"):equal_list = tf.equal(tf.argmax(y_true,1),tf.argmax(y_predict,1))# equal_list None个样本    [1 0 0 1 0 1 . . . . ]accuracy = tf.reduce_mean(tf.cast(equal_list,tf.float32))#收集变量 单个数字值收集tf.summary.scalar("losses",loss)tf.summary.scalar("acc",accuracy)#高纬度变量收集tf.summary.histogram("weight",weight)tf.summary.histogram("bias",bias)#定义初始化变量opinit_op = tf.global_variables_initializer()#创建一个Serveserve = tf.train.Saver()#合并Summarymeger = tf.summary.merge_all()#开启会话训练with tf.Session() as sess:sess.run(init_op)#建立事件events文件,然后写入filewrites = tf.summary.FileWriter("./MNIST/Events/",graph=sess.graph)if FLAGS.is_train == 1:# 迭代步数去训练,更新参数去预测for i in range(2000):# 取出训练集的特征值和目标值train_x, train_y = mnist.train.next_batch(50)sess.run(train_op, feed_dict={x: train_x, y_true: train_y})# 写入每步训练的值summary = sess.run(meger, feed_dict={x: train_x, y_true: train_y})filewrites.add_summary(summary, i)print("训练第%d步,准确率为:%f" % (i, sess.run(accuracy, feed_dict={x: train_x, y_true: train_y})))# 保存模型serve.save(sess, "./MNIST/model/fc_model")else:#加载模型serve.restore(sess,"./MNIST/model/fc_model")#如果是0,做出预测for i in range(100):#每次预测一张图片x_test, y_test = mnist.test.next_batch(1)print("第%d张图片,手写数字目标是:%d, 预测的图片结果是:%d"%(i,tf.argmax(y_test,1).eval(),tf.argmax(sess.run(y_predict,feed_dict={x: x_test, y_true: y_test}),1).eval()))def prdect():# 加载MNIST数据mnist = input_data.read_data_sets("./MNIST/", one_hot=True)# 1.建立数据占位符 x[None,784]  y[None,10]with tf.variable_scope("data"):x = tf.placeholder(tf.float32, [None, 784])y_true = tf.placeholder(tf.int32, [None, 10])# 2.建立一个全连接层的神经网络模型with tf.variable_scope("model"):# 随机初始化权重和偏置weight = tf.Variable(tf.random_normal([784, 10], mean=0.0, stddev=1.0), name="w")bias = tf.Variable(tf.constant(0.0, shape=[10]))y_predict = tf.matmul(x, weight) + bias# 创建一个Serveserve = tf.train.Saver()with tf.Session() as sess:# 加载模型serve.restore(sess, "./MNIST/model/fc_model")# 如果是0,做出预测for i in range(100):# 每次预测一张图片x_test, y_test = mnist.test.next_batch(1)print("第%d张图片,手写数字目标是:%d, 预测的图片结果是:%d" % (i,tf.argmax(y_test, 1).eval(),tf.argmax(sess.run(y_predict, feed_dict={x: x_test, y_true: y_test}), 1).eval()))if __name__ == "__main__":full_connected()prdect()
  1. 卷积神经网络实现手写数字神经网络
def weight_variable(shape):"""定义一个初始化的权重:param shape::return:"""weight = tf.Variable(tf.random_normal(shape=shape, mean=0.0, stddev=1.0), "w")return weightdef bias_variable(shape):"""定义一个初始化的偏置:param shape::return:"""b = tf.Variable(tf.constant(0.0,shape=shape))return bdef model():"""自定义卷积模型:return:"""# 1.建立数据占位符 x[None,784]  y[None,10]with tf.variable_scope("data"):x = tf.placeholder(tf.float32, [None, 784])y_true = tf.placeholder(tf.int32, [None, 10])#2.一层卷积 卷积,激活,池化with tf.variable_scope("conv1"):#随机初始化偏置和权重weight_1 = weight_variable([5, 5, 1, 32])bias_1 = bias_variable([32])#对输入x进行形状的改变  [None, 28, 28, 1]x_reshape = tf.reshape(x, [-1, 28, 28, 1])#卷积conv1 = tf.nn.conv2d(x_reshape,weight_1,strides=1, padding="SAME") + bias_1#激活函数x_relu1 = tf.nn.relu(conv1)#池化 2*2 , strides2 [None, 28, 28, 2] -----> [None, 14, 14, 32]x_pool1 = tf.nn.max_pool(x_relu1,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")#二层卷积:5*5*32 64个filter , strides=1with tf.variable_scope("conv2"):# 随机初始化偏置和权重weight_2 = weight_variable([5, 5, 32, 64])bias_2 = bias_variable([64])#卷积,激活,池化#[None, 14, 14, 32] ----> [None, 14, 14, 64]# 卷积conv2 = tf.nn.conv2d(x_pool1, weight_2, strides=1, padding="SAME") + bias_2# 激活函数x_relu2 = tf.nn.relu(conv2)# 池化 2*2 , strides2 [None, 14, 14, 64] -----> [None, 7, 7, 64]x_pool2 = tf.nn.max_pool(x_relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")#全连接层   [None, 7, 7, 64] --->  [None, 7, 7, 64]*[7*7*64,10] + [10] = [None, 10]with tf.variable_scope("fc"):# 随机初始化偏置和权重weight_fc = weight_variable([7*7*64, 10])bias_fc = bias_variable([10])#修改形状  [None, 7, 7, 64] ----> [None,7*7*64]x_fc_reshpe = tf.reshape(x_pool2,[-1,7*7*64])#进行矩阵运算出每个样本的10个结果y_predict = tf.matmul(x_fc_reshpe,weight_fc) + bias_fcreturn x, y_true, y_predictdef conv_fc():"""卷积神经网络训练手写数字:return:"""# 加载MNIST数据mnist = input_data.read_data_sets("./MNIST/", one_hot=True)#定义模型,得出输出x, y_true, y_predict = model()#进行交叉熵损失计算# 3.Softmax交叉熵损失函数, 求出所有样本的损失,然后求平均值with tf.variable_scope("loss"):# 求平均交叉损失函数loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))# 4.梯度下降求出损失函数with tf.variable_scope("optimizer"):# 学习率leaning_rate = 0.001train_op = tf.train.GradientDescentOptimizer(leaning_rate).minimize(loss)# 5.计算准确率with tf.variable_scope("acc"):equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))# equal_list None个样本    [1 0 0 1 0 1 . . . . ]accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))#初始化变量init_op = tf.global_variables_initializer()#开启会话with tf.Session() as sess:sess.run(init_op)for i in range(1000):# 取出训练集的特征值和目标值train_x, train_y = mnist.train.next_batch(50)sess.run(train_op, feed_dict={x: train_x, y_true: train_y})print("训练第%d步,准确率为:%f" % (i, sess.run(accuracy, feed_dict={x: train_x, y_true: train_y})))return None
if __name__ == "__main__":# full_connected()# prdect()conv_fc()

Tensorflow实现简单的手写数字神经网络模型相关推荐

  1. TensorFlow笔记(3)——利用TensorFlow和MNIST数据集训练一个最简单的手写数字识别模型...

    前言 当我们开始学习编程的时候,第一件事往往是学习打印"Hello World".就好比编程入门有Hello World,机器学习入门有MNIST. MNIST是一个入门级的计算机 ...

  2. TensorFlow 2.0 mnist手写数字识别(CNN卷积神经网络)

    TensorFlow 2.0 (五) - mnist手写数字识别(CNN卷积神经网络) 源代码/数据集已上传到 Github - tensorflow-tutorial-samples 大白话讲解卷积 ...

  3. 神经网络和深度学习(二)——一个简单的手写数字分类网络

    本文转自:https://blog.csdn.net/qq_31192383/article/details/77198870 一个简单的手写数字分类网络 接上一篇文章,我们定义了神经网络,现在我们开 ...

  4. tensorflow实现CNN识别手写数字

    上一篇使用TensorFlow识别手写数字,是直接采用了softmax进行多分类,直接将28*28的图片转换成为了784维的向量作为输入,然后通过一个(784,10)的权重,将输入转换成一个10维的向 ...

  5. PYQT5+CNN(TensorFlow-keras)做一个简单的手写数字识别PC端图形化小程序

    目录 前言 一.功能介绍 1.画板识别 2.图片识别 二.UI设计 1.整体设计思想 2.颜色设计 3.Logo 设计 4.按钮设计 三.算法介绍 1.图片预处理 2.数字分割和显示 3.识别算法 4 ...

  6. tensorflow入门之MINIST手写数字识别

    最近在学tensorflow,看了很多资料以及相关视频,有没有大佬推荐一下比较好的教程之类的,谢谢.最后还是到了官方网站去,还好有官方文档中文版,今天就结合官方文档以及之前看的教程写一篇关于MINIS ...

  7. 走进tensorflow第十步——手写数字识别中的input_data模块

    本来想来个综合的大程序,刚写了点发现东西较多,那就一点点整吧,东西太杂容易懵圈.. 在前几篇中的手写数字识别中一开始都有这么两句代码: from tensorflow.examples.tutoria ...

  8. 小白玩机器学习(6)--- 基于Tensorflow.js的在线手写数字识别

    一.题目要求 1.三个js文件,分别完成:网络训练以及模型保存.模型加载及准确率测试.在线手写数字识别: 2.模型测试准确率要高于99.3%(尽量): 3.在线手写数字识别需要能够通过鼠标在画布中写入 ...

  9. MOOC网深度学习应用开发1——Tensorflow基础、多元线性回归:波士顿房价预测问题Tensorflow实战、MNIST手写数字识别:分类应用入门、泰坦尼克生存预测

    Tensorflow基础 tensor基础 当数据类型不同时,程序做相加等运算会报错,可以通过隐式转换的方式避免此类报错. 单变量线性回归 监督式机器学习的基本术语 线性回归的Tensorflow实战 ...

最新文章

  1. 贝叶斯定理:AI 不只是个理科生 | 赠书
  2. .NET 调用JS:WebBrowser.Document.InvokeScript 方法抛出“指定的转换无效”异常的原因
  3. Sql Server2008——远程过程调用失败
  4. java学习(83):常用基础类object
  5. git保存账号密码_Altium Designer 通过Git实现版本控制
  6. oracle数据恢复
  7. Android “Theme.AppCompat.Light”解决方法
  8. windows 设置定时锁屏
  9. 花生壳域名解析更新代码(C#),不想安装花生壳客户端的可以用这个
  10. 如何关闭计算机服务检测,交互式服务检测老是弹出来?Win7系统交互式服务检测怎么关闭方法...
  11. matlab颜色直方图特征提取,灰度直方图特征提取的Matlab实现
  12. 实验吧-密码学(二)
  13. 电商平台-安全设计与架构
  14. 387:字符串中的第一个唯一字符
  15. kubernetes hpa源码分析
  16. “偷听”李敖先生2005北京大学演讲记
  17. 基于RFID的定位技术有几种?哪种最成熟?
  18. hadoop机架感知原理
  19. 15个有趣的555电路,没事可以自己做一做
  20. RLC的AM和UM mode的区别

热门文章

  1. request,response,session
  2. HDU4081 Qin Shi Huang's National Road System(次小生成树)
  3. 在windows下添加php的Imagick扩展
  4. JQuery模拟二------添加extend函数和简单选择器
  5. C#调用C++编写的dll库
  6. 动态HTML事件(Event)小结
  7. 使用IConfigurationSectionHandler在web.config中增加自定义配置
  8. tornado-ioloop-async-io
  9. 小李飞刀:SQL题目刷起来!
  10. 菜鸟学Linux 第030篇笔记 yum使用,源码编译安装