get_config
方法Model.get_config()
回傳物件的配置。
物件配置是一個 Python 字典 (可序列化),包含重新實例化它所需的所有資訊。
from_config
方法Model.from_config(config, custom_objects=None)
從其配置建立一個運算。
此方法是 get_config
的反向操作,能夠從配置字典中實例化相同的運算。
注意:如果您覆寫此方法,您可能會收到一個序列化的 dtype 配置,它是一個 dict
。您可以如下將其反序列化
if "dtype" in config and isinstance(config["dtype"], dict):
policy = dtype_policies.deserialize(config["dtype"])
引數
get_config
的輸出。回傳值
一個運算實例。
clone_model
函數keras.models.clone_model(
model,
input_tensors=None,
clone_function=None,
call_function=None,
recursive=False,
**kwargs
)
複製一個 Functional 或 Sequential Model
實例。
模型複製類似於在新的輸入上調用模型,只是它會建立新的層(以及新的權重),而不是共享現有層的權重。
請注意,clone_model
不會保留模型內共享物件的唯一性(例如,附加到兩個不同層的單個變數將被還原為兩個單獨的變數)。
引數
Model
的實例(可以是 Functional 模型或 Sequential 模型)。Input
物件。fn(layer)
,用於複製目標模型中的每一層(除了 Input
實例)。它接收要複製的層實例作為引數,並回傳要在模型副本中使用的對應層實例。如果未指定,此可呼叫函數預設為以下序列化/反序列化函數:lambda layer: layer.__class__.from_config(layer.get_config())
。透過傳遞自訂的可呼叫函數,您可以自訂模型的副本,例如,透過包裝某些感興趣的層(例如,您可能想將所有 LSTM
實例替換為等效的 Bidirectional(LSTM(...))
實例)。預設值為 None
。fn(layer, *args, **kwargs)
,用於調用每個複製的層和一組輸入。它接收層實例、調用引數和關鍵字引數,並回傳調用輸出。如果未指定,此可呼叫函數預設為常規的 __call__()
方法:def fn(layer, *args, **kwargs): return layer(*args, **kwargs)
。透過傳遞自訂的可呼叫函數,您可以在給定層之前或之後插入新的層。注意:此引數只能與 Functional 模型一起使用。False
,則會透過呼叫 clone_function()
來複製內部模型。如果為 True
,則會透過呼叫 clone_model()
並使用相同的 clone_function
、call_function
和 recursive
引數來複製內部模型。請注意,在這種情況下,call_function
不會傳播到任何 Sequential 模型(因為它不適用於 Sequential 模型)。回傳值
一個 Model
的實例,在新的輸入張量之上,使用新實例化的權重來重現原始模型的行為。如果自訂的 clone_function
或 call_function
修改了層或層調用,則複製的模型行為可能與原始模型不同。
範例
# Create a test Sequential model.
model = keras.Sequential([
keras.layers.Input(shape=(728,)),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(1, activation='sigmoid'),
])
# Create a copy of the test model (with freshly initialized weights).
new_model = clone_model(model)
使用 clone_function
透過在任何地方設定隨機種子來使模型具有確定性
def clone_function(layer):
config = layer.get_config()
if "seed" in config:
config["seed"] = 1337
return layer.__class__.from_config(config)
new_model = clone_model(model, clone_function=clone_function)
使用 call_function
在每個 Dense
層之後添加一個 Dropout
層(而不重新建立新的層)
def call_function(layer, *args, **kwargs):
out = layer(*args, **kwargs)
if isinstance(layer, keras.layers.Dense):
out = keras.layers.Dropout(0.5)(out)
return out
new_model = clone_model(
model,
clone_function=lambda x: x, # Reuse the same layers.
call_function=call_function,
)
請注意,子類模型預設無法複製,因為它們的內部層結構未知。若要在子類模型的情況下實現與 clone_model
等效的功能,只需確保模型類別實現 get_config()
(以及可選的 from_config()
),並調用
new_model = model.__class__.from_config(model.get_config())
在子類模型的情況下,您無法使用自訂的 clone_function
。