Mô tả
Tạo Keras Sequential model bằng cách thêm layer lần lượt qua phương thức add(). Phù hợp khi architecture được xây dựng động.
Code ví dụ
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print("A sequential model is being created")
model = keras.Sequential()
# Thêm layer lần lượt
model.add(layers.Dense(2, activation="relu", input_shape=(4,)))
model.add(layers.Dense(3, activation="relu"))
model.add(layers.Dense(4))
print("Dense layers have been added to the model")
# Kiểm tra
model.summary()
# Test forward pass
x = tf.ones((2, 4))
y = model(x)
print(f"\nTest output shape: {y.shape}")
Đầu ra
A sequential model is being created Dense layers have been added to the model Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 2) 10 dense_1 (Dense) (None, 3) 9 dense_2 (Dense) (None, 4) 16 ================================================================= Total params: 35 Test output shape: (2, 4)
Khi nào dùng add() thay vì list constructor?
- Số layer không xác định trước (ví dụ: hyperparameter search).
- Thêm layer trong vòng lặp hoặc điều kiện.
- Cần can thiệp giữa các bước thêm (in shape, regularizer tùy biến).
Ví dụ: Thêm layer trong loop
model = keras.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(100,)))
# Thêm n hidden layers
n_hidden = 3
for i in range(n_hidden):
model.add(layers.Dense(32, activation='relu', name=f'hidden_{i}'))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(1, activation='sigmoid'))
model.summary()
Lưu ý quan trọng
- Layer đầu tiên phải có
input_shapehoặcinput_dim(trừ khi dùngInputLayer). - Model chưa build cho đến khi gọi
model.build()hoặc chạy forward pass đầu tiên. - Sau khi add xong, có thể dùng
model.pop()để xóa layer cuối nếu cần.
Sequential vs Functional API
Sequential: Stack tuyến tính, 1 input → 1 output mỗi layer.
Functional API: Multiple inputs/outputs, shared layers, non-linear topology (ResNet, Inception).