keras模型第四课 关于Model的方法 About Keras models

About Keras models

翻译原文:https://keras.io/models/about-keras-models/

keras中有两个主要的模型类型 the Sequential modelthe Model class used with the functional API

模型中有一系列的方法和属性

from keras.layers import Dense, Input
from keras.models import Model, Sequential
import keras
import numpy as np
# 举例模型
data_input = Input(shape=(100, ))
x = Dense(64, activation='relu')(data_input)
x = Dense(64, activation='relu')(x)
y = Dense(1, activation='sigmoid')(x)

model = Model(data_input, y)

model.compile(optimizer=keras.optimizers.Adam(),
              loss=keras.losses.binary_crossentropy,
              metrics=['accuracy'])

# 创建numpy数据
x_train = np.random.random((100, 100))
y_train = np.random.randint(2, size=(100, 1))

# 训练模型
model.fit(x_train, y_train, epochs=10, batch_size=16)

· model.layers 是一个包含组成该模型的层的扁平列表

print(model.layers)
#[<keras.engine.input_layer.InputLayer object at 0x126997c88>, <keras.layers.core.Dense object at 0x126997cf8>, 
#<keras.layers.core.Dense object at 0x126997b38>, <keras.layers.core.Dense object at 0x126997668>]

· model.inputs 是一个包含输入张量的列表

print(model.inputs)
#[<tf.Tensor 'input_1:0' shape=(?, 100) dtype=float32>]

· model.outputs 是一个包含输出张量的列表

print(model.outputs)
#[<tf.Tensor 'dense_3/Sigmoid:0' shape=(?, 1) dtype=float32>]

· model.summary() 可以打印出模型结构信息

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 100)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                6464      
_________________________________________________________________
dense_2 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 65        
=================================================================
Total params: 10,689
Trainable params: 10,689
Non-trainable params: 0
_________________________________________________________________

· model.get_config() 返回一个包含模型配置的字典。模型可以通过以下方式从配置中恢复:

config = model.get_config()
reconfig_model = Model.from_config(config)
# 或者,对于Sequential模型
reconfig_model = Sequential.from_config(config)
reconfig_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 64)                6464      
_________________________________________________________________
dense_2 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 65        
=================================================================
Total params: 10,689
Trainable params: 10,689
Non-trainable params: 0
_________________________________________________________________

· model.get_weights() 返回一个该模型的权重张量的列表,是numpy数组

· model.set_weights(weights) 设定模型的权重,其两者的shape应该相同

· model.to_json() 以JSON字符串的形式返回模型。

注意,返回不包含权重,只包含模型结构。您可以通过以下方式从JSON字符串中恢复相同的模型(使用重新初始化的权重):

from keras.models import model_from_json

json_string = model.to_json()
rejson_model = model_from_json(json_string)
rejson_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 100)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                6464      
_________________________________________________________________
dense_2 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 65        
=================================================================
Total params: 10,689
Trainable params: 10,689
Non-trainable params: 0
_________________________________________________________________

· model.to_yaml() 以YAML字符串的形式返回模型。

注意,返回不包含权重,只包含模型结构。您可以通过以下方式从YAML字符串中恢复相同的模型(使用重新初始化的权重):

from keras.models import model_from_yaml

yaml_string = model.to_yaml()
reyaml_model = model_from_yaml(yaml_string)
reyaml_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 100)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                6464      
_________________________________________________________________
dense_2 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 65        
=================================================================
Total params: 10,689
Trainable params: 10,689
Non-trainable params: 0
_________________________________________________________________

· model.save_weights(filepath) 将模型的权重保存为HDF5文件

· model.load_weights(filepath, by_name=False)

从HDF5文件(由save_weights创建)加载模型的权重。默认情况下,结构应该保持不变。要将权重加载到不同的结构中(与某些层共享),使用by_name=True只加载具有相同名称的那些层。

· model.save(filepath) 将keras模型保存在HDF5文件,

文件中包含:

1、模型的结构,运行重构模型
2、模型的权重
3、训练配置(损失函数、优化器) 4、优化器的状态,允许精确地在停止的地方恢复训练

from keras.models import load_model

# 保存模型
model.save('test_model.h5')
del model #删除存在的函数

# 恢复模型
model = load_model('test_model.h5') 

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 100)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                6464      
_________________________________________________________________
dense_2 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_3 (Dense)              (None, 1)                 65        
=================================================================
Total params: 10,689
Trainable params: 10,689
Non-trainable params: 0
_________________________________________________________________
  • 2
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
2018 Modern text analysis is now very accessible using Python and open source tools, so discover how you can now perform modern text analysis in this era of textual data. This book shows you how to use natural language processing, and computational linguistics algorithms, to make inferences and gain insights about data you have. These algorithms are based on statistical machine learning and artificial intelligence techniques. The tools to work with these algorithms are available to you right now - with Python, and tools like Gensim and spaCy. You'll start by learning about data cleaning, and then how to perform computational linguistics from first concepts. You're then ready to explore the more sophisticated areas of statistical NLP and deep learning using Python, with realistic language and text samples. You'll learn to tag, parse, and model text using the best tools. You'll gain hands-on knowledge of the best frameworks to use, and you'll know when to choose a tool like Gensim for topic models, and when to work with Keras for deep learning. This book balances theory and practical hands-on examples, so you can learn about and conduct your own natural language processing projects and computational linguistics. You'll discover the rich ecosystem of Python tools you have available to conduct NLP - and enter the interesting world of modern text analysis. What you will learn Why text analysis is important in our modern age Understand NLP terminology and get to know the Python tools and datasets Learn how to pre-process and clean textual data Convert textual data into vector space representations Using spaCy to process text Train your own NLP models for computational linguistics Use statistical learning and Topic Modeling algorithms for text, using Gensim and scikit-learn Employ deep learning techniques for text analysis using Keras

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值