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

博客介绍了Keras中的两种主要模型类型,重点阐述了模型的一系列方法和属性,如获取层列表、输入输出张量列表,打印模型结构信息,获取和设置权重,保存和加载模型及权重等,还说明了保存文件包含的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
_________________________________________________________________
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值