Keras cho phép tạo custom layer bằng cách kế thừa layers.Layer và triển khai build, call.
Cài đặt
pip install tensorflow
Ví dụ: Custom Dense Layer
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
# Sử dụng
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
model = keras.Model(inputs, outputs)
print("Keras model generated with CustomDense")
Kết quả
Keras model generated with CustomDense
Giải thích
build()tạo weight khi biết input_shape (lần đầu forward).call()định nghĩa forward pass:y = xW + b.add_weightđăng ký biến trainable với Keras.- Layer tích hợp được vào Sequential, Functional API, hỗ trợ serialization.
Lưu ý: Nên override get_config() để hỗ trợ save/load model (xem bài trước).