使用tensorflow进行mnist数字识别【模型训练+预测+模型保存+模型恢复】
import sys,os
sys.path.append(os.pardir)
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from PIL import Image
import tensorflow as tf
def predict():
meta_path = 'ckpt/mnist.ckpt.meta'
model_path = 'ckpt/mnist.ckpt'
sess = tf.InteractiveSession ()
saver = tf.train.import_meta_graph (meta_path)
saver.restore (sess, model_path)
graph = tf.get_default_graph ()
W = graph.get_tensor_by_name ("w:0")
b = graph.get_tensor_by_name ("b:0")
x = tf.placeholder (tf.float32, [None, 784])
y = tf.nn.softmax (tf.matmul (x, W) + b)
keep_prob = tf.placeholder (tf.float32)
batch_xs, batch_ys=mnist.train.next_batch (100)
one_img = batch_xs[0].reshape ((1, 784))
one_num = batch_ys[0].reshape ((1, 10))
temp = sess.run (y, feed_dict={x: one_img, keep_prob: 1.0})
b = sess.run (tf.argmax (temp, 1))
a = sess.run (tf.arg_max (one_num, 1))
print(temp)
print(one_num)
if b == a:
print ("success! the num is :", (b[0]))
showImgTest(one_img)
else:
print ("mistakes predict.")
def trainNet():
x = tf.placeholder (tf.float32, [None, 784])
W = tf.Variable (tf.zeros ([784, 10]),name="w")
b = tf.Variable (tf.zeros ([10]),name="b")
y = tf.nn.softmax (tf.matmul (x, W) + b)
y_ = tf.placeholder (tf.float32, [None, 10])
keep_prob = tf.placeholder (tf.float32)
# 定义测试的准确率
correct_prediction = tf.equal (tf.argmax (y, 1), tf.argmax (y_, 1))
accuracy = tf.reduce_mean (tf.cast (correct_prediction, tf.float32))
#
saver = tf.train.Saver (max_to_keep=1)
max_acc = 0
train_accuracy = 0
#交叉熵
cross_entropy = tf.reduce_mean (-tf.reduce_sum (y_ * tf.log (y)))
# cross_error=cross_entropy_error_batch(y,y_)
train_step = tf.train.GradientDescentOptimizer (0.01).minimize (cross_entropy)
sess = tf.InteractiveSession ()
tf.global_variables_initializer ().run ()
for i in range (1000):
batch_xs, batch_ys = mnist.train.next_batch (100)
sess.run (train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})
if i % 100 == 0:
train_accuracy = accuracy.eval (feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})
print ("step %d, training accuracy %g" % (i, train_accuracy))
if train_accuracy > max_acc:
max_acc = train_accuracy
saver.save (sess, 'ckpt/mnist.ckpt')
if __name__ == '__main__':
mnist = input_data.read_data_sets ("MNIST_data/", one_hot=True)
choice=0
while choice == 0:
print ("------------------------tensorflow--------------------------")
print ("\t\t\t1\ttrain model..")
print("\t\t\t2\tpredict model")
print("\t\t\t3\tshow the first image")
print ("\t\t\t0\texit")
choice = input ("please input your choice!")
print(choice)
if choice == "1":
print("start train...")
trainNet()
if choice=="2":
predict()
if choice=="3":
showImg()




注:正在学习CNN,选项4还没有来的及做。后面补上
使用tensorflow进行mnist数字识别【模型训练+预测+模型保存+模型恢复】的更多相关文章
- TensorFlow学习笔记(三)MNIST数字识别问题
一.MNSIT数据处理 MNSIT是一个非常有名的手写体数字识别数据集.包含60000张训练图片,10000张测试图片.每张图片是28X28的数字. TonserFlow提供了一个类来处理 MNSIT ...
- 一个简单的TensorFlow可视化MNIST数据集识别程序
下面是TensorFlow可视化MNIST数据集识别程序,可视化内容是,TensorFlow计算图,表(loss, 直方图, 标准差(stddev)) # -*- coding: utf-8 -*- ...
- MNIST数字识别问题
摘自<Tensorflow:实战Google深度学习框架> import tensorflow as tf from tensorflow.examples.tutorials.mnist ...
- Pytorch CNN网络MNIST数字识别 [超详细记录] 学习笔记(三)
目录 1. 准备数据集 1.1 MNIST数据集获取: 1.2 程序部分 2. 设计网络结构 2.1 网络设计 2.2 程序部分 3. 迭代训练 4. 测试集预测部分 5. 全部代码 1. 准备数据集 ...
- Tensorflow手写数字识别训练(梯度下降法)
# coding: utf-8 import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data #p ...
- TensorFlow深度学习实战---MNIST数字识别问题
1.滑动平均模型: 用途:用于控制变量的更新幅度,使得模型在训练初期参数更新较快,在接近最优值处参数更新较慢,幅度较小 方式:主要通过不断更新衰减率来控制变量的更新幅度. 衰减率计算公式 : deca ...
- 吴裕雄 python 神经网络——TensorFlow实现回归模型训练预测MNIST手写数据集
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_dat ...
- Tensorflow手写数字识别---MNIST
MNIST数据集:包含数字0-9的灰度图, 图片size为28x28.训练样本:55000,测试样本:10000,验证集:5000
- Tensorflow手写数字识别(交叉熵)练习
# coding: utf-8import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data #pr ...
随机推荐
- GIT非常见命令使用笔记
1:修改已经提交N次代码的user.name和user.email 解决我在多电脑间,使用不同账户,git config 的global,system,local配置忽略改动,而添加了多台电脑ssh ...
- js如何将时间戳转换为标准时间
function formatDate(date,fmt){ let o = { 'M+' : date.getMonth() +1, //月份 'd+' : date.getDate(), //日 ...
- Google 地图切片URL地址解析
一.Google地图切片的投影方式及瓦片索引机制 1.地图投影 Google地图采用的是Web墨卡托投影(如下图),为了方便忽略了两极变形较大的地区,把世界地图做成了一个边长等于赤道周长的正方形(赤道 ...
- P1441 砝码称重
题目描述 现有n个砝码,重量分别为a1,a2,a3,……,an,在去掉m个砝码后,问最多能称量出多少不同的重量(不包括0). 输入输出格式 输入格式: 输入文件weight.in的第1行为有两个整数n ...
- HDU 1257 最少拦截系统(贪心 or LIS)
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1257 最少拦截系统 Time Limit: 2000/1000 MS (Java/Others) ...
- Oracle 创建函数
Oracle创建函数的方法如下: CREATE OR REPLACE FUNCTION FunctionName ( --传入参数 para NCHAR ) RETURN NUMBER IS --函数 ...
- 【Linux】LVM逻辑卷管理和RAID
LVM概述: 是对磁盘分区进行管理的一种机制 是一种将一个或多个硬盘的分区在逻辑上集合,相当于一个大硬盘来使用,当硬盘的空间不 够使用的时候,可以继续将其它的硬盘的分区加入其中,这样可以实现一种磁盘空 ...
- 使用jquery获取url上的参数(笔记)
使用jquery获取url上的参数(笔记) 一.做作业时经常要获取url上的参数 1.当url上有多个参数时 从互联网找到了一个方法 (function ($) { $.getUrlParam = f ...
- 大数据入门第六天——HDFS详解
一.概述 1.HDFS中的角色 Block数据: HDFS中的文件在物理上是分块存储(block),块的大小可以通过配置参数( dfs.blocksize)来规定,默认大小在hadoop2.x版本中是 ...
- mysql存储过程批量插入数据
DROP TABLE IF EXISTS TeachersInfo; CREATE TABLE TeachersInfo ( id INT NOT NULL AUTO_INCREMENT, teach ...