Keras Functional API cho phép tùy biến layer. Method get_config() trả về dict các tham số khởi tạo để serialize/deserialize model.
Ví dụ: Custom Layer với get_config
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class CustomDense(layers.Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True
)
self.b = self.add_weight(
shape=(self.units,),
initializer="random_normal",
trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
def get_config(self):
return {"units": self.units}
# Tạo model dùng custom layer
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
# Lấy config và rebuild
config = model.get_config()
new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})
print("Constructor arguments retrieved via get_config()")
Kết quả
Constructor arguments retrieved via get_config()
Giải thích
get_config()bắt buộc override trong custom layer để lưu tham sốunits.Model.from_configtái tạo model từ config, cần cung cấpcustom_objectsmap tên class.- Quan trọng cho save/load model, hyperparameter tuning, model sharing.