深度学习:TensorFlow2构建、保存、加载神经网络模型【经典流程】

本文主要是介绍深度学习:TensorFlow2构建、保存、加载神经网络模型【经典流程】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、network.save_weights、network.load_weights

保存模型的参数,加载已保存的参数的network的结构必须和之前的network的所有结构一模一样

import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 放在 import tensorflow as tf 之前才有效import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets# 一、获取数据集
(X_train, Y_train), (X_test, Y_test) = datasets.mnist.load_data()
print('X_train.shpae = {0},Y_train.shpae = {1}------------type(X_train) = {2},type(Y_train) = {3}'.format(X_train.shape, Y_train.shape, type(X_train), type(Y_train)))# 二、数据处理
# 预处理函数:将numpy数据转为tensor
def preprocess(x, y):x = tf.cast(x, dtype=tf.float32) / 255.x = tf.reshape(x, [28 * 28])y = tf.cast(y, dtype=tf.int32)y = tf.one_hot(y, depth=10)return x, y# 2.1 处理训练集
# print('X_train.shpae = {0},Y_train.shpae = {1}------------type(X_train) = {2},type(Y_train) = {3}'.format(X_train.shape, Y_train.shape, type(X_train), type(Y_train)))
dataset_train = tf.data.Dataset.from_tensor_slices((X_train, Y_train))  # 此步骤自动将numpy类型的数据转为tensor
dataset_train = dataset_train.map(preprocess)  # 调用map()函数批量修改每一个元素数据的数据类型
dataset_train = dataset_train.shuffle(len(X_train))  # 打散dataset_train中的样本顺序,防止图片的原始顺序对神经网络性能的干扰
print('dataset_train = {0},type(dataset_train) = {1}'.format(dataset_train, type(dataset_train)))
batch_size_train = 20000  # 每个batch里的样本数量设置100-200之间合适。
dataset_batch_train = dataset_train.batch(batch_size_train)  # 将dataset_batch_train中每sample_num_of_each_batch_train张图片分为一个batch,读取一个batch相当于一次性并行读取sample_num_of_each_batch_train张图片
print('dataset_batch_train = {0},type(dataset_batch_train) = {1}'.format(dataset_batch_train, type(dataset_batch_train)))
# 2.2 处理测试集
dataset_test = tf.data.Dataset.from_tensor_slices((X_test, Y_test))  # 此步骤自动将numpy类型的数据转为tensor
dataset_test = dataset_test.map(preprocess)  # 调用map()函数批量修改每一个元素数据的数据类型
dataset_test = dataset_test.shuffle(len(X_test))  # 打散样本顺序,防止图片的原始顺序对神经网络性能的干扰
batch_size_test = 5000  # 每个batch里的样本数量设置100-200之间合适。
dataset_batch_test = dataset_test.batch(batch_size_test)  # 将dataset_test中每sample_num_of_each_batch_test张图片分为一个batch,读取一个batch相当于一次性并行读取sample_num_of_each_batch_test张图片# 三、构建神经网络结构:Dense 表示全连接神经网络,激活函数用 relu
network = keras.Sequential([layers.Dense(500, activation=tf.nn.relu),  # 降维:784-->500layers.Dense(300, activation=tf.nn.relu),  # 降维:500-->300layers.Dense(100, activation=tf.nn.relu),  # 降维:300-->100layers.Dense(10)])  # 降维:100-->10,最后一层一般不需要在此处指定激活函数,在计算Loss的时候会自动运用激活函数
network.build(input_shape=[None, 784])  # 28*28=784,None表示样本数量,是不确定的值。
network.summary()  # 打印神经网络model的简要信息# 四、设置神经网络各个参数
network.compile(optimizer=optimizers.Adam(lr=0.01),loss=tf.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])# 五、给神经网络喂数据,训练神经网络模型参数
print('\n++++++++++++++++++++++++++++++++++++++++++++Training 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.fit(dataset_batch_train, epochs=5, validation_data=dataset_batch_test, validation_freq=2)  # validation_freq参数表示每多少个epoch做一次验证/validation
print('++++++++++++++++++++++++++++++++++++++++++++Training 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')# 六、模型评估 test/evluation
print('\n++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.evaluate(dataset_batch_test)
print('++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')network.save_weights('weights.ckpt')
print('\n================saved weights================')
del network
print('================del network================')# 七、创建一个和所加载参数的原始network一模一样的network
print('================创建一个和所加载参数的原始network一模一样的network================')
network = keras.Sequential([layers.Dense(500, activation=tf.nn.relu),  # 降维:784-->500layers.Dense(300, activation=tf.nn.relu),  # 降维:500-->300layers.Dense(100, activation=tf.nn.relu),  # 降维:300-->100layers.Dense(10)])  # 降维:100-->10,最后一层一般不需要在此处指定激活函数,在计算Loss的时候会自动运用激活函数
network.build(input_shape=[None, 784])  # 28*28=784,None表示样本数量,是不确定的值。
network.compile(optimizer=optimizers.Adam(lr=0.01),loss=tf.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])
network.load_weights('weights.ckpt')
print('================loaded weights================')# 八、模型评估 test/evluation
print('\n++++++++++++++++++++++++++++++++++++++++++++加载weights后--->Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.evaluate(dataset_batch_test)
print('++++++++++++++++++++++++++++++++++++++++++++加载weights后--->Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')# 九、模型上线应用
sample = next(iter(dataset_batch_test))  # 从 dataset_batch_test 中取一个batch数据做模拟
x = sample[0]
y = sample[1]  # one-hot
pred = network.predict(x)  # [b, 10]
y = tf.argmax(y, axis=1)  # convert back to number
pred = tf.argmax(pred, axis=1)
print('\n++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
print(pred)
print(y)
print('++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:结束++++++++++++++++++++++++++++++++++++++++++++')

打印结果:

X_train.shpae = (60000, 28, 28),Y_train.shpae = (60000,)------------type(X_train) = <class 'numpy.ndarray'>type(Y_train) = <class 'numpy.ndarray'>
dataset_train = <ShuffleDataset shapes: ((784,), (10,)), types: (tf.float32, tf.float32)>type(dataset_train) = <class 'tensorflow.python.data.ops.dataset_ops.ShuffleDataset'>
dataset_batch_train = <BatchDataset shapes: ((None, 784), (None, 10)), types: (tf.float32, tf.float32)>type(dataset_batch_train) = <class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 500)               392500    
_________________________________________________________________
dense_1 (Dense)              (None, 300)               150300    
_________________________________________________________________
dense_2 (Dense)              (None, 100)               30100     
_________________________________________________________________
dense_3 (Dense)              (None, 10)                1010      
=================================================================
Total params: 573,910
Trainable params: 573,910
Non-trainable params: 0
_________________________________________________________________++++++++++++++++++++++++++++++++++++++++++++Training 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
Epoch 1/5
3/3 [==============================] - 2s 113ms/step - loss: 2.7174 - accuracy: 0.1086
Epoch 2/5
3/3 [==============================] - 3s 492ms/step - loss: 2.6596 - accuracy: 0.1666 - val_loss: 1.6333 - val_accuracy: 0.4709
Epoch 3/5
3/3 [==============================] - 2s 115ms/step - loss: 1.5516 - accuracy: 0.4968
Epoch 4/5
3/3 [==============================] - 2s 255ms/step - loss: 1.0690 - accuracy: 0.6475 - val_loss: 0.7587 - val_accuracy: 0.7859
Epoch 5/5
3/3 [==============================] - 2s 115ms/step - loss: 0.7137 - accuracy: 0.7955
++++++++++++++++++++++++++++++++++++++++++++Training 阶段:结束++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
2/2 [==============================] - 0s 22ms/step - loss: 0.5240 - accuracy: 0.8493
++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++================saved weights================
================del network================
================创建一个和所加载参数的原始network一模一样的network================
================loaded weights================++++++++++++++++++++++++++++++++++++++++++++加载weights后--->Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
2/2 [==============================] - 0s 22ms/step - loss: 0.5223 - accuracy: 0.8486
++++++++++++++++++++++++++++++++++++++++++++加载weights后--->Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:开始++++++++++++++++++++++++++++++++++++++++++++
tf.Tensor([6 3 7 ... 5 1 0], shape=(5000,), dtype=int64)
tf.Tensor([6 3 7 ... 3 1 0], shape=(5000,), dtype=int64)
++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:结束++++++++++++++++++++++++++++++++++++++++++++Process finished with exit code 0

二、network.save()、network.load()

保存整个模型,加载后再根据network的通常做法进行操作。

import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 放在 import tensorflow as tf 之前才有效import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets# 一、获取数据集
(X_train, Y_train), (X_test, Y_test) = datasets.mnist.load_data()
print('X_train.shpae = {0},Y_train.shpae = {1}------------type(X_train) = {2},type(Y_train) = {3}'.format(X_train.shape, Y_train.shape, type(X_train), type(Y_train)))# 二、数据处理
# 预处理函数:将numpy数据转为tensor
def preprocess(x, y):x = tf.cast(x, dtype=tf.float32) / 255.x = tf.reshape(x, [28 * 28])y = tf.cast(y, dtype=tf.int32)y = tf.one_hot(y, depth=10)return x, y# 2.1 处理训练集
# print('X_train.shpae = {0},Y_train.shpae = {1}------------type(X_train) = {2},type(Y_train) = {3}'.format(X_train.shape, Y_train.shape, type(X_train), type(Y_train)))
dataset_train = tf.data.Dataset.from_tensor_slices((X_train, Y_train))  # 此步骤自动将numpy类型的数据转为tensor
dataset_train = dataset_train.map(preprocess)  # 调用map()函数批量修改每一个元素数据的数据类型
dataset_train = dataset_train.shuffle(len(X_train))  # 打散dataset_train中的样本顺序,防止图片的原始顺序对神经网络性能的干扰
print('dataset_train = {0},type(dataset_train) = {1}'.format(dataset_train, type(dataset_train)))
batch_size_train = 20000  # 每个batch里的样本数量设置100-200之间合适。
dataset_batch_train = dataset_train.batch(batch_size_train)  # 将dataset_batch_train中每sample_num_of_each_batch_train张图片分为一个batch,读取一个batch相当于一次性并行读取sample_num_of_each_batch_train张图片
print('dataset_batch_train = {0},type(dataset_batch_train) = {1}'.format(dataset_batch_train, type(dataset_batch_train)))
# 2.2 处理测试集
dataset_test = tf.data.Dataset.from_tensor_slices((X_test, Y_test))  # 此步骤自动将numpy类型的数据转为tensor
dataset_test = dataset_test.map(preprocess)  # 调用map()函数批量修改每一个元素数据的数据类型
dataset_test = dataset_test.shuffle(len(X_test))  # 打散样本顺序,防止图片的原始顺序对神经网络性能的干扰
batch_size_test = 5000  # 每个batch里的样本数量设置100-200之间合适。
dataset_batch_test = dataset_test.batch(batch_size_test)  # 将dataset_test中每sample_num_of_each_batch_test张图片分为一个batch,读取一个batch相当于一次性并行读取sample_num_of_each_batch_test张图片# 三、构建神经网络结构:Dense 表示全连接神经网络,激活函数用 relu
network = keras.Sequential([layers.Dense(500, activation=tf.nn.relu),  # 降维:784-->500layers.Dense(300, activation=tf.nn.relu),  # 降维:500-->300layers.Dense(100, activation=tf.nn.relu),  # 降维:300-->100layers.Dense(10)])  # 降维:100-->10,最后一层一般不需要在此处指定激活函数,在计算Loss的时候会自动运用激活函数
network.build(input_shape=[None, 784])  # 28*28=784,None表示样本数量,是不确定的值。
network.summary()  # 打印神经网络model的简要信息# 四、设置神经网络各个参数
network.compile(optimizer=optimizers.Adam(lr=0.01),loss=tf.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])# 五、给神经网络喂数据,训练神经网络模型参数
print('\n++++++++++++++++++++++++++++++++++++++++++++Training 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.fit(dataset_batch_train, epochs=5, validation_data=dataset_batch_test, validation_freq=2)  # validation_freq参数表示每多少个epoch做一次验证/validation
print('++++++++++++++++++++++++++++++++++++++++++++Training 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')# 六、模型评估 test/evluation
print('\n++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.evaluate(dataset_batch_test)
print('++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')network.save('model.h5')
print('\n================saved total model================')
del network
print('================del network================')# 七、从磁盘加载保存的整体模型(包括所有参数、结构...)
print('================loaded model from file================')
network = tf.keras.models.load_model('model.h5', compile=False)
network.compile(optimizer=optimizers.Adam(lr=0.01),loss=tf.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])# 八、模型评估 test/evluation
print('\n++++++++++++++++++++++++++++++++++++++++++++从磁盘加载整个model后--->Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
network.evaluate(dataset_batch_test)
print('++++++++++++++++++++++++++++++++++++++++++++从磁盘加载整个model后--->Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++')# 九、模型上线应用
sample = next(iter(dataset_batch_test))  # 从 dataset_batch_test 中取一个batch数据做模拟
x = sample[0]
y = sample[1]  # one-hot
pred = network.predict(x)  # [b, 10]
y = tf.argmax(y, axis=1)  # convert back to number
pred = tf.argmax(pred, axis=1)
print('\n++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:开始++++++++++++++++++++++++++++++++++++++++++++')
print(pred)
print(y)
print('++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:结束++++++++++++++++++++++++++++++++++++++++++++')

打印结果:

X_train.shpae = (60000, 28, 28),Y_train.shpae = (60000,)------------type(X_train) = <class 'numpy.ndarray'>type(Y_train) = <class 'numpy.ndarray'>
dataset_train = <ShuffleDataset shapes: ((784,), (10,)), types: (tf.float32, tf.float32)>type(dataset_train) = <class 'tensorflow.python.data.ops.dataset_ops.ShuffleDataset'>
dataset_batch_train = <BatchDataset shapes: ((None, 784), (None, 10)), types: (tf.float32, tf.float32)>type(dataset_batch_train) = <class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 500)               392500    
_________________________________________________________________
dense_1 (Dense)              (None, 300)               150300    
_________________________________________________________________
dense_2 (Dense)              (None, 100)               30100     
_________________________________________________________________
dense_3 (Dense)              (None, 10)                1010      
=================================================================
Total params: 573,910
Trainable params: 573,910
Non-trainable params: 0
_________________________________________________________________++++++++++++++++++++++++++++++++++++++++++++Training 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
Epoch 1/5
3/3 [==============================] - 2s 119ms/step - loss: 2.4869 - accuracy: 0.2464
Epoch 2/5
3/3 [==============================] - 2s 514ms/step - loss: 3.5169 - accuracy: 0.3786 - val_loss: 1.5471 - val_accuracy: 0.5026
Epoch 3/5
3/3 [==============================] - 2s 116ms/step - loss: 1.4532 - accuracy: 0.5238
Epoch 4/5
3/3 [==============================] - 2s 273ms/step - loss: 0.9930 - accuracy: 0.6789 - val_loss: 0.6357 - val_accuracy: 0.8010
Epoch 5/5
3/3 [==============================] - 2s 112ms/step - loss: 0.6005 - accuracy: 0.8118
++++++++++++++++++++++++++++++++++++++++++++Training 阶段:结束++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
2/2 [==============================] - 0s 24ms/step - loss: 0.4489 - accuracy: 0.8735
++++++++++++++++++++++++++++++++++++++++++++Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++================saved total model================
================del network================
================loaded model from file================++++++++++++++++++++++++++++++++++++++++++++从磁盘加载整个model后--->Evluation 阶段:开始++++++++++++++++++++++++++++++++++++++++++++
2/2 [==============================] - 0s 21ms/step - loss: 0.4505 - accuracy: 0.8729
++++++++++++++++++++++++++++++++++++++++++++从磁盘加载整个model后--->Evluation 阶段:结束++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:开始++++++++++++++++++++++++++++++++++++++++++++
tf.Tensor([9 0 9 ... 5 1 9], shape=(5000,), dtype=int64)
tf.Tensor([9 0 9 ... 5 1 9], shape=(5000,), dtype=int64)
++++++++++++++++++++++++++++++++++++++++++++加载weights后--->应用阶段:结束++++++++++++++++++++++++++++++++++++++++++++Process finished with exit code 0

三、tf.saved_model.save()、tf.saved_model.load()、

保存为可以被其他语言(比如:C++)调用的格式
在这里插入图片描述

这篇关于深度学习:TensorFlow2构建、保存、加载神经网络模型【经典流程】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1128904

相关文章

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

一文详解如何从零构建Spring Boot Starter并实现整合

《一文详解如何从零构建SpringBootStarter并实现整合》SpringBoot是一个开源的Java基础框架,用于创建独立、生产级的基于Spring框架的应用程序,:本文主要介绍如何从... 目录一、Spring Boot Starter的核心价值二、Starter项目创建全流程2.1 项目初始化(

Python 中的异步与同步深度解析(实践记录)

《Python中的异步与同步深度解析(实践记录)》在Python编程世界里,异步和同步的概念是理解程序执行流程和性能优化的关键,这篇文章将带你深入了解它们的差异,以及阻塞和非阻塞的特性,同时通过实际... 目录python中的异步与同步:深度解析与实践异步与同步的定义异步同步阻塞与非阻塞的概念阻塞非阻塞同步

使用Java实现通用树形结构构建工具类

《使用Java实现通用树形结构构建工具类》这篇文章主要为大家详细介绍了如何使用Java实现通用树形结构构建工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录完整代码一、设计思想与核心功能二、核心实现原理1. 数据结构准备阶段2. 循环依赖检测算法3. 树形结构构建4. 搜索子

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

SpringBoot项目启动报错"找不到或无法加载主类"的解决方法

《SpringBoot项目启动报错找不到或无法加载主类的解决方法》在使用IntelliJIDEA开发基于SpringBoot框架的Java程序时,可能会出现找不到或无法加载主类com.example.... 目录一、问题描述二、排查过程三、解决方案一、问题描述在使用 IntelliJ IDEA 开发基于

使用Python和python-pptx构建Markdown到PowerPoint转换器

《使用Python和python-pptx构建Markdown到PowerPoint转换器》在这篇博客中,我们将深入分析一个使用Python开发的应用程序,该程序可以将Markdown文件转换为Pow... 目录引言应用概述代码结构与分析1. 类定义与初始化2. 事件处理3. Markdown 处理4. 转

Redis中高并发读写性能的深度解析与优化

《Redis中高并发读写性能的深度解析与优化》Redis作为一款高性能的内存数据库,广泛应用于缓存、消息队列、实时统计等场景,本文将深入探讨Redis的读写并发能力,感兴趣的小伙伴可以了解下... 目录引言一、Redis 并发能力概述1.1 Redis 的读写性能1.2 影响 Redis 并发能力的因素二、

Spring AI ectorStore的使用流程

《SpringAIectorStore的使用流程》SpringAI中的VectorStore是一种用于存储和检索高维向量数据的数据库或存储解决方案,它在AI应用中发挥着至关重要的作用,本文给大家介... 目录一、VectorStore的基本概念二、VectorStore的核心接口三、VectorStore的

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言