keras模型第四课 关于Model的方法 About Keras 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