前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Keras保存模型

Keras保存模型

作者头像
润森
发布2019-11-04 22:30:46
9910
发布2019-11-04 22:30:46
举报
文章被收录于专栏:毛利学Python毛利学Python

学习一时爽,一直学习一直爽

 Hello,大家好,我是 もうり,一个从无到有的技术+语言小白。

一旦你利用Keras完成了训练,你可以将你的网络保存在HDF5里面。

keras的模型保存分为多种情况。

一、不保存模型只显示大概结构 model.summary() 这个函数会打印模型结构,但是仅仅是打印到控制台。

keras.utils.plot_model() 使用graphviz中的dot.exe生成网络结构拓扑图

二、保存模型结构 keras.models.Model

对象的to_json,to_yaml只保存模型结构,加载时使用keras.models.model_from_json(),keras.models.model_from_yaml()

keras.model.get_config()返回文本形式的配置 使用keras.model.model_from_config可以加载模型。

三、保存全部结构(最常用的方法) keras.core.saving.py这个文件十分重要,keras的模型保存、加载都需要这个文件。 但是不建议直接使用这个文件,因为keras中的Model对象和models模块会调用这个文件。 keras.core包下的内容一般供内部使用,不暴露给使用者。

Model对象提供了save()和save_wights()两个方法。

只需要导入from keras.models import model_from_json就是这么简单

基于Iris数据集如何保存model

代码语言:javascript
复制
'''
@author: 毛利
'''
from sklearn import datasets
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
from keras.models import model_from_json


dataset = datasets.load_iris()
x = dataset.data
Y = dataset.target
# 二分类  将标签转换成分类编码(每一列代表一类,是为1,否为0)
Y_labels = to_categorical(Y, num_classes=3)
seed = 4
np.random.seed(seed)

# 这里使用rmsprop优化器,adam也行
def create_model(optimizer='rmsprop', init='glorot_uniform'):
    model = Sequential()
    model.add(Dense(units=4, activation='relu', input_dim=4, kernel_initializer=init))
    model.add(Dense(units=6, activation='relu', kernel_initializer=init))
    model.add(Dense(units=3, activation='softmax', kernel_initializer=init))
    # categorical:分类的  crossentropy:交叉熵
    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
    return model




model = create_model()
model.fit(x, Y_labels, epochs=200, batch_size=5, verbose=0)
# evaluate: 评价
scores = model.evaluate(x, Y_labels, verbose=0)
print('%s: %.2f%%' % (model.metrics_names[1], scores[1]*100))

可以保存yaml from keras.models import model_from_yaml

代码语言:javascript
复制
'''
@author: 毛利
'''
from sklearn import datasets
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
from keras.models import model_from_yaml


dataset = datasets.load_iris()
x = dataset.data
Y = dataset.target
# 将标签转换成分类编码(每一列代表一类,是为1,否为0)
Y_labels = to_categorical(Y, num_classes=3)
seed = 4
np.random.seed(seed)


def create_model(optimizer='rmsprop', init='glorot_uniform'):
    model = Sequential()
    model.add(Dense(units=4, activation='relu', input_dim=4, kernel_initializer=init))
    model.add(Dense(units=6, activation='relu', kernel_initializer=init))
    model.add(Dense(units=3, activation='softmax', kernel_initializer=init))
    # categorical:分类的  crossentropy:交叉熵
    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
    return model


model = create_model()
model.fit(x, Y_labels, epochs=200, batch_size=5, verbose=0)
# evaluate: 评价
scores = model.evaluate(x, Y_labels, verbose=0)
print('%s: %.2f%%' % (model.metrics_names[1], scores[1]*100))

# 将模型保存成YAML文件
model_yaml = model.to_yaml()
with open('../model/model.yaml', 'w') as file:
    file.write(model_yaml)
# 保存模型权重值
model.save_weights('../model/model.yaml.h5')
# 从YAML文件中加载模型
with open('../model/model.yaml', 'r') as file:
    model_yaml = file.read()
# 加载模型
new_model = model_from_yaml(model_yaml)
new_model.load_weights('../model/model.yaml.h5')
# 必须先编译模型
new_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# 评估从YAML文件中加载的模型
scores = new_model.evaluate(x, Y_labels, verbose=0)
print('%s: %.2f%%' % (new_model.metrics_names[1], scores[1]*100))
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小刘IT教程 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基于Iris数据集如何保存model
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档