Tensorflow MINIST数据模型的训练,保存,恢复和手写字体识别

使用TensorFlow搭建卷积神经网络模型,实现MNIST手写数字识别,并介绍了模型的训练、保存及恢复过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  最近刚接触tensorflow,同样和广大网友一样采用MINIST数据来做手写识别,内容以注释的形式在代码里了

 模型训练和保存

 1.首先下载MINIST数据库(下载地址) ,四个文件下载后放到和你的python文件同一个目录下,不用解压,然后输入,其中e2.jpg在文末可下载

#coding=utf-8 
# 载入MINIST数据需要的库
from tensorflow.examples.tutorials.mnist import input_data
# 保存模型需要的库
from tensorflow.python.framework.graph_util import convert_variables_to_constants 
from tensorflow.python.framework import graph_util 
# 导入其他库
import tensorflow as tf
import cv2  
import numpy as np 
#获取MINIST数据
mnist = input_data.read_data_sets(".",one_hot = True)
# 创建会话 
sess = tf.InteractiveSession()
 
#占位符
x = tf.placeholder("float", shape=[None, 784], name="Mul")
y_ = tf.placeholder("float",shape=[None, 10],  name="y_")
#变量
W = tf.Variable(tf.zeros([784,10]),name='x')
b = tf.Variable(tf.zeros([10]),'y_')
 
#权重
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)
#偏差
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)
#卷积
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')
#相关变量的创建
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_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)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
 
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",name='rob')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
 
#用于训练用的softmax函数
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name='res')
#用于训练作完后,作测试用的softmax函数
y_conv2=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2,name="final_result")
 
#交叉熵的计算,返回包含了损失值的Tensor。
 
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
#优化器,负责最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
#计算准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#初始化所以变量
sess.run(tf.global_variables_initializer())
 
 # 保存输入输出,可以为之后用
tf.add_to_collection('res', y_conv)
tf.add_to_collection('output', y_conv2)
tf.add_to_collection('x', x)
 
#训练开始
for i in range(20000):
  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})
    print "step %d, training accuracy %g"%(i, train_accuracy)
#run()可以看做输入相关值给到函数中的占位符,然后计算的出结果,这里将batch[0],给xbatch[1]给y_
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
 
#将当前图设置为默认图
graph_def = tf.get_default_graph().as_graph_def() 
#将上面的变量转化成常量,保存模型为pb模型时需要,注意这里的final_result和前面的y_con2是同名,只有这样才会保存它,否则会报错,
# 如果需要保存其他tensor只需要让tensor的名字和这里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,  
                graph_def, ['final_result'])  
#保存前面训练后的模型为pb文件
with tf.gfile.GFile("grf.pb", 'wb') as f:  
        f.write(output_graph_def.SerializeToString())
 
#用saver 保存模型
saver = tf.train.Saver()   
saver.save(sess, "model_data/model")  
 
#导入图片,同时灰度化
im = cv2.imread('pic/e2.jpg',cv2.IMREAD_GRAYSCALE)
#反转图像,因为e2.jpg为白底黑字   
im =reversePic(im)
cv2.namedWindow("camera", cv2.WINDOW_NORMAL); 
cv2.imshow('camera',im)  
cv2.waitKey(0) 

#调整大小
im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)   
x_img = np.reshape(im , [-1 , 784])  


#输出图像矩阵
# print x_img 
 
#用上面导入的图片对模型进行测试
output = sess.run(y_conv2 , feed_dict={x:x_img })  
# print 'the y_con :   ', '\n',output  
print 'the predict is : ', np.argmax(output) 
print "test accracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})


输出:




没有CUDA加速,训练的会比较慢,但都可以训练,只是速度区别

1)其中用Saver保存模型的代码:

saver = tf.train.Saver()   
saver.save(sess, "model_data/model") 


最终会产生model_data文件夹,其中包含了:


2)保存模型为pb格式的代码:

#将当前图设置为默认图
graph_def = tf.get_default_graph().as_graph_def() 
#将上面的变量转化成常量,保存模型为pb模型时需要,注意这里的final_result和前面的y_con2是同名,只有这样才会保存它,否则会报错,
# 如果需要保存其他tensor只需要让tensor的名字和这里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,  
                graph_def, ['final_result'])  
#保存前面训练后的模型为pb文件
with tf.gfile.GFile("grf.pb", 'wb') as f:  
        f.write(output_graph_def.SerializeToString())

最终在当前目录生成grf.pb文件


模型的恢复:

1.用Saver保存的模型的恢复:

# -*- coding:utf-8 -*-    
import cv2  
import tensorflow as tf  
import numpy as np  
from sys import path  
#用于将自定义输入图片反转
def reversePic(src):
        # 图像反转  
    for i in range(src.shape[0]):
        for j in range(src.shape[1]):
            src[i,j] = 255 - src[i,j]
    return src 
          
def main():  
    sess = tf.InteractiveSession()  
#模型恢复
    saver=tf.train.import_meta_graph('model_data/model.meta')
 
    saver.restore(sess, 'model_data/model')
    graph = tf.get_default_graph()
    
    # 获取输入tensor,,获取输出tensor
    input_x = sess.graph.get_tensor_by_name("Mul:0")
    y_conv2 = sess.graph.get_tensor_by_name("final_result:0")

    # 也可以上面注释,通过下面获取输出输入tensor,
    # y_conv2 = tf.get_collection('output')[0]
    # # x= tf.get_collection('x')[0]
    # input_x = graph.get_operation_by_name('Mul').outputs[0]
    # keep_prob = graph.get_operation_by_name('rob').outputs[0]
    
    path="pic/e2.jpg"  
    im = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
    #反转图像,因为e2.jpg为白底黑字   
    im =reversePic(im)
    cv2.namedWindow("camera", cv2.WINDOW_NORMAL); 
    cv2.imshow('camera',im)  
    cv2.waitKey(0)  
    # im=cv2.threshold(im, , 255, cv2.THRESH_BINARY_INV)[1];

    im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)  

    # im=cv2.threshold(im,200,255,cv2.THRESH_TRUNC)[1]
    # im=cv2.threshold(im,60,255,cv2.THRESH_TOZERO)[1]
 
    #数据从0~255转为-0.5~0.5  
    # img_gray = (im - (255 / 2.0)) / 255  
    x_img = np.reshape(im , [-1 , 784])  
    output = sess.run(y_conv2 , feed_dict={input_x:x_img})  
    print 'the predict is %d' % (np.argmax(output)) 
    #关闭会话  
    sess.close()  
  
if __name__ == '__main__':  
    main()  


2.pb模型的恢复

#coding=utf-8 
from __future__ import absolute_import, unicode_literals
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework.graph_util import convert_variables_to_constants 
from tensorflow.python.framework import graph_util 
import cv2 
import numpy as np  
mnist = input_data.read_data_sets(".",one_hot = True)
import tensorflow as tf

#用于将自定义输入图片反转
def reversePic(src):
        # 图像反转  
    for i in range(src.shape[0]):
        for j in range(src.shape[1]):
            src[i,j] = 255 - src[i,j]
    return src 

with tf.Session() as persisted_sess:
  print("load graph")
  with tf.gfile.FastGFile("grf.pb",'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    persisted_sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')
  # print("map variables")
  with tf.Session() as sess:

        # tf.initialize_all_variables().run()
        input_x = sess.graph.get_tensor_by_name("Mul:0")
        y_conv_2 = sess.graph.get_tensor_by_name("final_result:0")


        path="pic/e2.jpg"  
        im = cv2.imread(path,cv2.IMREAD_GRAYSCALE) 
        #反转图像,因为e2.jpg为白底黑字   
        im =reversePic(im)
        cv2.namedWindow("camera", cv2.WINDOW_NORMAL); 
        cv2.imshow('camera',im)  
        cv2.waitKey(0) 
        # im=cv2.threshold(im, , 255, cv2.THRESH_BINARY_INV)[1];
 
        im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)  
        # im =reversePic(im)
        # im=cv2.threshold(im,200,255,cv2.THRESH_TRUNC)[1]
        # im=cv2.threshold(im,60,255,cv2.THRESH_TOZERO)[1]

        # img_gray = (im - (255 / 2.0)) / 255  
        x_img = np.reshape(im , [-1 , 784])  
        output = sess.run(y_conv_2 , feed_dict={input_x:x_img})  
        print 'the predict is %d' % (np.argmax(output)) 
        #关闭会话  
        sess.close() 


其中e2.jpg:



输出结果都是:



注意:

     用MINIST训练出来的模型。主要用来识别手写数字的,而且对输入的图片要求是近似黑底白字的,所以如果图片预处理不合适会导致识别率不高。

     如果直接用官方的图片输 入,则识别完全没问题

     附官方图片和e2.jpg的下载地址






        

             
 

    

### 使用 TensorFlow 实现 MNIST 手写数字识别 为了使用 TensorFlow 进行 MNIST 手写数字识别,可以按照以下方法设置环境并编写代码。 #### 创建虚拟环境并安装依赖库 建议先创建一个虚拟环境来管理项目的依赖项。接着通过 `pip` 安装所需的包,特别是 TensorFlow 版本 2.2 或更高版本[^1]: ```bash python -m venv my_env source my_env/bin/activate # Linux or macOS my_env\Scripts\activate # Windows pip install tensorflow==2.2 ``` #### 加载必要的模块配置 GPU (如果适用) 在脚本开头部分加载所需的所有 Python 库,并根据硬件情况启用或禁用 GPU 支持: ```python import tensorflow as tf from tensorflow.keras import datasets, layers, models print(tf.__version__) ``` 这段代码会打印当前使用的 TensorFlow 版本号,确认是否成功安装了指定版本的 TensorFlow[^4]。 #### 准备数据集 接下来获取 MNIST 数据集并通过 Keras API 对其做预处理工作,包括下载、归一化图像像素值到 `[0, 1]` 范围内以及调整输入张量形状以便于后续操作: ```python (train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data() train_images = train_images.reshape((60000, 28, 28, 1)) test_images = test_images.reshape((10000, 28, 28, 1)) # Normalize pixel values to be between 0 and 1 train_images, test_images = train_images / 255.0, test_images / 255.0 ``` 这里的数据集已经被划分为训练集 (`train_images`, `train_labels`) 测试集 (`test_images`, `test_labels`). 各自包含了对应的手写字体图片及其标签信息. #### 构建 CNN 模型架构 定义一个简单的卷积神经网络(CNN),它由两个卷积层组成,后面跟着最大池化层(MaxPooling Layer),最后连接全连接层(Dense Layers): ```python model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10)) # Output layer with softmax activation function omitted here. ``` 此模型接受大小为 `(28, 28)` 的灰度图作为输入,在最后一层输出长度为 10 的向量表示属于各个类别的概率分布. #### 编译与训练模型 编译阶段指定了损失函数(categorical crossentropy)、优化器(adam optimizer) 及评估指标(accuarcy). 训练过程则调用了 fit 方法传入训练数据完成参数更新迭代. ```python model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels)) ``` 上述命令将在本地运行五个 epoch 来拟合给定的数据集;期间还会计算验证集上的性能表现用于监控过拟合现象的发生. #### 测试模型效果 当训练完成后可利用 evaluate() 函数快速查看整个测试集中预测结果的好坏程度: ```python test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print(f'\nTest accuracy: {test_acc}') ``` 这一步骤能够给出最终分类准确性得分,帮助理解所建立模型的实际效能.
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值