About Keras models
翻译原文:https://keras.io/models/about-keras-models/
keras中有两个主要的模型类型 the Sequential model 和 the 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
_________________________________________________________________