下面是一个具体的Python代码示例,展示如何使用TensorFlow实现一个简单的神经网络来解决手写数字识别问题(使用MNIST数据集)。以下是一个完整的Python代码示例,展示如何使用TensorFlow构建和训练一个简单的神经网络来进行手写数字识别。

MNIST数据集的训练集有60000个样本:

Python代码

import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
import json
import os # 加载MNIST数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data() # 预处理数据
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255 # 构建神经网络模型
def create_model():
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.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax')) # 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model # 训练模型并保存
def train_and_save_model():
model = create_model()
history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))
model.save('mnist_model.h5') # 保存训练历史记录
with open('training_history.json', 'w') as f:
json.dump(history.history, f) # 加载模型和历史记录
def load_model_and_history():
model = tf.keras.models.load_model('mnist_model.h5') with open('training_history.json', 'r') as f:
history = json.load(f) return model, history # 评估模型
def evaluate_model(model):
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("Test accuracy: {}".format(test_acc)) # 可视化训练过程
def plot_training_history(history):
plt.plot(history['accuracy'], label='accuracy')
plt.plot(history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0, 1])
plt.legend(loc='lower right')
plt.show() # 检查是否已经存在模型和历史记录
if not os.path.exists('mnist_model.h5') or not os.path.exists('training_history.json'):
train_and_save_model() model, training_history = load_model_and_history()
evaluate_model(model)
plot_training_history(training_history)

代码解释

  1. 加载MNIST数据集

    mnist = tf.keras.datasets.mnist
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
  2. 预处理数据

    • 将图像数据调整为 (28, 28, 1) 的形状。
    • 将像素值标准化为 [0, 1] 之间。
    train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
    test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
  3. 构建神经网络模型

    • 使用 Sequential 模型,按顺序添加层。
    • 添加卷积层、池化层、全连接层。
    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.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.Flatten())
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(10, activation='softmax'))
  4. 编译模型

    • 使用 adam 优化器,损失函数为 sparse_categorical_crossentropy,评估指标为 accuracy
    model.compile(optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])
  5. 训练模型

    • 训练模型5个epochs,并使用验证数据集评估模型性能。
    history = model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels))
  6. 评估模型

    • 在测试集上评估模型性能,并打印测试准确率。
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print(f"Test accuracy: {test_acc}")
  7. 可视化训练过程

    • 绘制训练和验证准确率随epoch变化的曲线。
    plt.plot(history.history['accuracy'], label='accuracy')
    plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    plt.xlabel('Epoch')
    plt.ylabel('Accuracy')
    plt.ylim([0, 1])
    plt.legend(loc='lower right')
    plt.show()

通过这个修正后的示例,应该可以正常运行并训练一个简单的神经网络模型来进行手写数字识别。

手写数字识别-使用TensorFlow构建和训练一个简单的神经网络的更多相关文章

  1. Softmax用于手写数字识别(Tensorflow实现)-个人理解

    softmax函数的作用   对于分类方面,softmax函数的作用是从样本值计算得到该样本属于各个类别的概率大小.例如手写数字识别,softmax模型从给定的手写体图片像素值得出这张图片为数字0~9 ...

  2. 基于卷积神经网络的手写数字识别分类(Tensorflow)

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  3. TensorFlow 之 手写数字识别MNIST

    官方文档: MNIST For ML Beginners - https://www.tensorflow.org/get_started/mnist/beginners Deep MNIST for ...

  4. TensorFlow使用RNN实现手写数字识别

    学习,笔记,有时间会加注释以及函数之间的逻辑关系. # https://www.cnblogs.com/felixwang2/p/9190664.html # https://www.cnblogs. ...

  5. Android+TensorFlow+CNN+MNIST 手写数字识别实现

    Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...

  6. 第三节,TensorFlow 使用CNN实现手写数字识别(卷积函数tf.nn.convd介绍)

    上一节,我们已经讲解了使用全连接网络实现手写数字识别,其正确率大概能达到98%,这一节我们使用卷积神经网络来实现手写数字识别, 其准确率可以超过99%,程序主要包括以下几块内容 [1]: 导入数据,即 ...

  7. 第二节,TensorFlow 使用前馈神经网络实现手写数字识别

    一 感知器 感知器学习笔记:https://blog.csdn.net/liyuanbhu/article/details/51622695 感知器(Perceptron)是二分类的线性分类模型,其输 ...

  8. python-积卷神经网络全面理解-tensorflow实现手写数字识别

    首先,关于神经网络,其实是一个结合很多知识点的一个算法,关于cnn(积卷神经网络)大家需要了解: 下面给出我之前总结的这两个知识点(基于吴恩达的机器学习) 代价函数: 代价函数 代价函数(Cost F ...

  9. Tensorflow之MNIST手写数字识别:分类问题(1)

    一.MNIST数据集读取 one hot 独热编码独热编码是一种稀疏向量,其中:一个向量设为1,其他元素均设为0.独热编码常用于表示拥有有限个可能值的字符串或标识符优点:   1.将离散特征的取值扩展 ...

  10. Tensorflow实战 手写数字识别(Tensorboard可视化)

    一.前言 为了更好的理解Neural Network,本文使用Tensorflow实现一个最简单的神经网络,然后使用MNIST数据集进行测试.同时使用Tensorboard对训练过程进行可视化,算是打 ...

随机推荐

  1. 企业生产环境中的麒麟V10(ARM架构)操作系统部署jdk和redis三主三从交叉版集群

    前言:麒麟ARM操作系统是国企和政务机关推行信创化选择率比较高的一款操作系统,然而ARM操作系统非主流的X86系统,除了命令一样,在架构方面差别极大,初次接触多多少少会踩坑,下面我将在公司中部署的实例 ...

  2. 阿里巴巴 MySQL 数据库之索引规约 (二)

    索引规约 强制部分 [强制] 业务上具有唯一特性的字段,即使是多个字段的组合,也必须建成唯一索引. 说明:不要以为唯一索引影响了 insert 速度,这个速度损耗可以忽略,但提高查找速度是明显的:另外 ...

  3. WNS 后台Push服务调试脚本

    一.API说明 https://cloud.tencent.com/document/product/276/3212   二.推送脚本 #!/usr/local/bin/python3 # -*- ...

  4. 大厂边缘组VS小厂核心组,要怎么选?

    有问必答 最近有粉丝提问:大厂边缘组VS小厂核心组,怎么选? 这确实是个好问题,读者老爷们可以先问下自己:如果有一份月薪2W在大厂边缘组打螺丝的Offer且不加班,另外还有一份月薪2W5,在小厂核心组 ...

  5. 记 Codes 开源免费研发管理平台 —— 日报与工时融合集中式填报的创新实现

    继上一回合生成式全局看板的创新实现后,本篇我们来讲一讲日报与工时融合集中式填报的创新实现. 市面上所有的研发管理软件,大多都有工时相关功能,但是却没有日报功能,好像也没什么问题,但是在使用过程中体验非 ...

  6. vue-cli 单文件组件 工具安装

    https://cli.vuejs.org/zh/ 在很多 Vue 项目中,我们使用 Vue.component 来定义全局组件,紧接着用 new Vue({ el: '#container '}) ...

  7. SELinux策略语法以及示例策略

    首发公号:Rand_cs SELinux策略语法以及示例策略 本文来讲述 SELinux 策略常用的语法,然后解读一下 SELinux 这个项目中给出的示例策略 安全上下文 首先来看一下安全上下文的格 ...

  8. Mac 上切换 node 版本总结

    Mac 上切换 node 版本总结 背景 在做项目的时候,往往会遇到老项目没有升级的问题,node环境版本比较低,自己电脑安装或者新项目安装了最新版本的 node 环境,那么既要支持老版本的使用也要支 ...

  9. linux查看端口命令 lsof netstat

    [root@VM-4-3-centos /]# lsof -i:8881COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEnode 15526 roo ...

  10. Java扫描文件目录大小及递归扫描

    #Java扫描文件目录大小及递归扫描 package com.example.core.mydemo; import org.apache.commons.io.FileUtils; import j ...