[深度学习] tf.keras入门5-模型保存和载入
目录
模型可以在训练中或者训练完成后保存。具体文档参考:https://tensorflow.google.cn/tutorials/keras/save_and_restore_models
设置
依赖项设置:
!pip install -q h5py pyyaml
模型建立:
from __future__ import absolute_import, division, print_function
import os
import tensorflow as tf
from tensorflow import keras
tf.__version__
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_labels = train_labels[:1000]
test_labels = test_labels[:1000]
train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0
# 模型创建模型
def create_model():
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return model
#创建模型
model = create_model()
model.summary()
基于checkpoints的模型保存
通过ModelCheckpoint模块来自动保存数据
#创建回调函数
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only=True, #只保存权重
verbose=1)
model = create_model()
model.fit(train_images, train_labels, epochs = 10,
validation_data = (test_images,test_labels),
callbacks = [cp_callback]) #保存模型
通过load_weight读取权重
#对全新没有训练的模型进行预测
model = create_model()
loss, acc = model.evaluate(test_images, test_labels)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc)) #11.4%
#载入权重参数后的模型
model.load_weights(checkpoint_path)
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #86.2
手动保存权重
# 保存权重
model.save_weights('./checkpoints/my_checkpoint')
#恢复模型
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #87.00%
整个模型保存
基于keras的HD5文件保存整个模型所有参数,优化器参数等。
#将整个模型保存为HDF5文件
model = create_model()
model.fit(train_images, train_labels, epochs=5)
model.save('my_model.h5')
#载入一个相同的模型
new_model = keras.models.load_model('my_model.h5')
new_model.summary()
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #86.30%
总体代码
from __future__ import absolute_import, division, print_function
import os
import tensorflow as tf
from tensorflow import keras
tf.__version__
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_labels = train_labels[:1000]
test_labels = test_labels[:1000]
train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0
# 模型创建模型
def create_model():
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return model
#创建模型
model = create_model()
model.summary()
checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
'''
#创建回调函数
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
save_weights_only=True, #只保存权重
verbose=1)
model = create_model()
model.fit(train_images, train_labels, epochs = 10,
validation_data = (test_images,test_labels),
callbacks = [cp_callback]) #保存模型
#对全新没有训练的模型进行预测
model = create_model()
loss, acc = model.evaluate(test_images, test_labels)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc)) #11.4%
#载入权重参数后的模型
model.load_weights(checkpoint_path)
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #86.2
# 保存权重
model.save_weights('./checkpoints/my_checkpoint')
#恢复模型
model = create_model()
model.load_weights('./checkpoints/my_checkpoint')
loss,acc = model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #87.00%
'''
#将整个模型保存为HDF5文件
model = create_model()
model.fit(train_images, train_labels, epochs=5)
model.save('my_model.h5')
#载入一个相同的模型
new_model = keras.models.load_model('my_model.h5')
new_model.summary()
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc)) #86.30%
[深度学习] tf.keras入门5-模型保存和载入的更多相关文章
- [深度学习] tf.keras入门1-基本函数介绍
目录 构建一个简单的模型 序贯(Sequential)模型 网络层的构造 模型训练和参数评价 模型训练 模型的训练 tf.data的数据集 模型评估和预测 基本模型的建立 网络层模型 模型子类函数构建 ...
- [深度学习] tf.keras入门4-过拟合和欠拟合
过拟合和欠拟合 简单来说过拟合就是模型训练集精度高,测试集训练精度低:欠拟合则是模型训练集和测试集训练精度都低. 官方文档地址为 https://tensorflow.google.cn/tutori ...
- [深度学习] tf.keras入门3-回归
目录 波士顿房价数据集 数据集 数据归一化 模型训练和预测 模型建立和训练 模型预测 总结 回归主要基于波士顿房价数据库进行建模,官方文档地址为:https://tensorflow.google.c ...
- [深度学习] tf.keras入门2-分类
目录 Fashion MNIST数据库 分类模型的建立 模型预测 总体代码 主要介绍基于tf.keras的Fashion MNIST数据库分类, 官方文档地址为:https://tensorflow. ...
- 深度学习:Keras入门(一)之基础篇
1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorflow的深度学习框架. Keras是一个高层神经网络API,支持快速实验,能够把你的idea迅速转换为结 ...
- 深度学习:Keras入门(一)之基础篇【转】
本文转载自:http://www.cnblogs.com/lc1217/p/7132364.html 1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorfl ...
- 深度学习:Keras入门(一)之基础篇(转)
转自http://www.cnblogs.com/lc1217/p/7132364.html 1.关于Keras 1)简介 Keras是由纯python编写的基于theano/tensorflow的深 ...
- 深度学习:Keras入门(二)之卷积神经网络(CNN)
说明:这篇文章需要有一些相关的基础知识,否则看起来可能比较吃力. 1.卷积与神经元 1.1 什么是卷积? 简单来说,卷积(或内积)就是一种先把对应位置相乘然后再把结果相加的运算.(具体含义或者数学公式 ...
- 深度学习:Keras入门(二)之卷积神经网络(CNN)【转】
本文转载自:https://www.cnblogs.com/lc1217/p/7324935.html 说明:这篇文章需要有一些相关的基础知识,否则看起来可能比较吃力. 1.卷积与神经元 1.1 什么 ...
随机推荐
- windows下利用_popen,_wpoen创建管道进行系统命令输出数据
转载: https://blog.csdn.net/greless/article/details/72383762 参考: http://www.linuxidc.com/Linux/2011-04 ...
- Linux-->文件目录作用查询
Linux的目录结构 在Linux中他的根目录都是决定好的无法改名,并且每一个目录他的作用都是决定好的 在Linux中一切都是文件!,Linux会把所有的硬件都映射成文件 / 代表根目录 /bin / ...
- Ajax的使用(jquery的下载)
Ajax学习笔记(jquery的下载) JQuery的官网下载 地址:http://jquery.com 右上角的"Download JQuery" 三个可供下载的文件: Prod ...
- 齐博x1万能数据统计接口
为何叫万能数据统计接口呢?因为可以调用全站任何数据表的数据总条数,并且可以设置查询条件http://qb.net/index.php/index/wxapp.count.html?table=memb ...
- Python学习三天计划-3
面向对象 一.类的定义 1.类定义 class是关键字,表示要定义类了 类的属性,即定义在类中的变量(成员变量) 类的行为,即定义在类中的函数(成员方法) 2.对象 创建类对象的语法: class S ...
- IDEA& Android Studio 配置
1.配置环境 首先要安装好JDK,但不需要单独下载SDK,只需在IDEA或AS的"设置->外观与行为->->系统设置->Android SDK"中下载相应版 ...
- win10+ubuntu双系统的坑
1.把U盘里\EFI\BOOT\grubx64.efi文件重命名为mmx64.efi,避免系统提示缺少文件而退出安装: 2.如果电脑显卡为N卡,则在install Ubuntu时,按e进入编辑,在qu ...
- python字符串的一些操作
# 1.变量的多次赋值 print('1.变量的多次赋值') name = '小明' # 没有意义的 name = '小刚' # 对前面创建的变量名称进行覆盖 # 删除原来的数据,写入新的数据 pri ...
- pycharm系列---基本配置
自动加入头文件 # _*_ coding: utf-8 _*_ # @Time : ${DATE} ${TIME} # @Author : xiechunhui # @Version:V 0.1 # ...
- 部署redis集群
1.redis部署 redis单实例部署参考:https://www.cnblogs.com/silgen/p/16537299.html 版本:6.2.7 集群:6个节点(redis集群至少3个节点 ...