Keras学习笔记二:保存本地模型和调用本地模型
使用深度学习模型时当然希望可以保存下训练好的模型,需要的时候直接调用,不再重新训练
一、保存模型到本地
以mnist数据集下的AutoEncoder 去噪为例。添加:
file_path="MNIST_data/weights-improvement-{epoch:02d}-{val_loss:.2f}.hdf5"
tensorboard = TensorBoard(log_dir='/tmp/tb', histogram_freq=0, write_graph=False)
checkpoint = ModelCheckpoint(filepath=file_path,verbose=1,monitor='val_loss', save_weights_only=False,mode='auto' ,save_best_only=True,period=1)
autoencoder.fit(x_train_noisy, x_train,
epochs=100,
batch_size=128,
shuffle=True,
validation_data=(x_test_noisy, x_test),
callbacks=[checkpoint,tensorboard])
这里的tensorboard和checkpoint分别是
1、启用tensorboard可视化工具,新建终端使用tensorboard --logdir=/tmp/tb 命令
2、保存ModelCheckpoint到MNIST_data/文件夹下,这里的参数设置为观察val_loss ,当有提升时保存一次模型,如下


二、从本地读取模型
假设读取模型后使用三个图片做去噪实验:(测试的图片数量修改 pic_num )
import os
import numpy as np
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
import matplotlib.pyplot as plt
from keras.models import Model,Sequential,load_model
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img
from keras.callbacks import TensorBoard , ModelCheckpoint
print("_________________________keras start_____________________________")
pic_num = 3
base_dir = 'MNIST_data' #基准目录
train_dir = os.path.join(base_dir,'my_test') #train目录
validation_dir="".join(train_dir)
test_datagen = ImageDataGenerator(rescale= 1./255)
validation_generator = test_datagen.flow_from_directory(validation_dir,
target_size = (28,28),
color_mode = "grayscale",
batch_size = pic_num,
class_mode = "categorical")#利用test_datagen.flow_from_directory(图像地址,目标size,批量数目,标签分类情况)
for x_train,batch_labels in validation_generator:
break
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
y_train = x_train # create model
model = load_model('MNIST_data/my_model.hdf5')
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print("Created model and loaded weights from file") # estimate accuracy on whole dataset using loaded weights
y_train=model.predict(x_train) n = pic_num
for i in range(n):
ax = plt.subplot(2, n, i+1)
plt.imshow(x_train[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax = plt.subplot(2, n, i+1+n)
plt.imshow(y_train[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
迭代67次效果:

参考:
https://keras-zh.readthedocs.io/getting-started/faq/#_3
https://keras-zh.readthedocs.io/models/model/#predict
https://cloud.tencent.com/developer/article/1049579
Keras学习笔记二:保存本地模型和调用本地模型的更多相关文章
- [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计
源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...
- asp.net MVC日志插件Log4Net学习笔记二:保存日志到sqlserver的配置
1.写到sqlserver的配置: <!--保存到SQLSERVER数据库日志--> <log4net> <appender name="AdoNetAppen ...
- Django学习笔记二
Django学习笔记二 模型类,字段,选项,查询,关联,聚合函数,管理器, 一 字段属性和选项 1.1 模型类属性命名限制 1)不能是python的保留关键字. 2)不允许使用连续的下划线,这是由dj ...
- Keras学习笔记——Hello Keras
最近几年,随着AlphaGo的崛起,深度学习开始出现在各个领域,比如无人车.图像识别.物体检测.推荐系统.语音识别.聊天问答等等.因此具备深度学习的知识并能应用实践,已经成为很多开发者包括博主本人的下 ...
- amazeui学习笔记二(进阶开发5)--Web 组件开发规范Rules
amazeui学习笔记二(进阶开发5)--Web 组件开发规范Rules 一.总结 1.见名知意:见那些class名字知意,见函数名知意,见文件名知意 例如(HISTORY.md Web 组件更新历史 ...
- 纯JS实现KeyboardNav(学习笔记)二
纯JS实现KeyboardNav(学习笔记)二 这篇博客只是自己的学习笔记,供日后复习所用,没有经过精心排版,也没有按逻辑编写 这篇主要是添加css,优化js编写逻辑和代码排版 GitHub项目源码 ...
- AJax 学习笔记二(onreadystatechange的作用)
AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...
- JMX学习笔记(二)-Notification
Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...
- java之jvm学习笔记二(类装载器的体系结构)
java的class只在需要的时候才内转载入内存,并由java虚拟机的执行引擎来执行,而执行引擎从总的来说主要的执行方式分为四种, 第一种,一次性解释代码,也就是当字节码转载到内存后,每次需要都会重新 ...
随机推荐
- gflags 编译动态库
gflags 编译动态库 这里涉及到gflags的安装,原来使用 sudo apt-get install libgflags-dev 但是后面有人在环境中下载安装了libgflags的安装包,解压后 ...
- mark ubuntu 16.04 64bit + cpu only install mtcnn
大神代码链接 称之为MTCNN人脸检测算法,同时有大神已经GitHub上开源了其基于caffe的C++ API 的源代码,https://github.com/DaFuCoding/MTCNN_Caf ...
- uni app以及小程序 --环境搭建以及编辑器
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html 根据以上网页下载自己电脑相应的版本的微信开发者工具(目录 ...
- JS 中的跨域请求
跨域请求并不仅仅只是 Ajax 的跨域请求,而是对于一个页面来说,只要它请求了其他域名的资源了,那么这个过程就属于跨域请求了. 比如,一个带有其他域名的 src 的 <img> 标签,以及 ...
- 转载: Linux查看系统开机时间
转自: https://www.cnblogs.com/kerrycode/p/3759395.html 查看Linux系统运行了多久时间,此时需要知道上次开机启动时间: 有时候由于断电或供电故障突然 ...
- 获取指定开始行数$start,跨度$limit的文件内容
// 获取指定开始行数$page,跨度$step的文件内容 function getLine($file_name, $start, $limit) { $f = new SplFileObject( ...
- yii2-cache组件第三个参数Dependency $dependency的作用浅析
用法如下: $cache->set($key, $result, Configs::instance()->cacheDuration, new TagDependency([ 'tags ...
- OSG入坑之路[转]
转载自:https://segmentfault.com/a/1190000010506374?utm_source=tag-newest osg插件原理:https://blog.csdn.net/ ...
- MyBatis笔记-03-CRUD
3.CRUD 1.namespace namespace中的包名要和Dao/mapper接口的包名保持一致 2.select 选择查询语句: id:就是对应的namespace中的方法名: resul ...
- iOS View的一些操作定义为宏
#define ViewOf(__View__,__TAG__) [__View__ viewWithTag:__TAG__]#define LabelOf(__View__,__TAG__) ((U ...