Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Khi nào nên dùng Sequential Model TensorFlow/Keras Python

Mô tả

Sequential model phù hợp khi: stack layer tuyến tính, mỗi layer có 1 input tensor và 1 output tensor.

✅ Phù hợp dùng Sequential khi:

  • Feedforward network (MLP, CNN đơn giản, RNN đơn giản).
  • Transfer learning: feature extractor + classification head.
  • Model không chia sẻ layer (shared layers).
  • Không có multiple inputs/outputs.
  • Không có skip connections (ResNet), branching.

❌ KHÔNG phù hợp Sequential khi:

  • Multiple inputs (ví dụ: wide & deep, Siamese network).
  • Multiple outputs (multi-task learning).
  • Shared layers (cùng layer dùng cho nhiều nhánh).
  • Skip connections / residual connections.
  • Complex topology (Inception, DenseNet, U-Net).

Ví dụ: Sequential phù hợp (3-layer MLP)

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(2, activation="relu", name="layer_1"),
    layers.Dense(3, activation="relu", name="layer_2"),
    layers.Dense(4, name="layer_3"),
])

print("A sequential model is being defined, that has three layers")

# Test
x = tf.ones((2, 2))
y = model(x)
print("The model is being called on test data")
print(f"Output shape: {y.shape}")

# Xem layers
print("The layers are:")
for layer in model.layers:
    print(f"  {layer.name}: {layer.output_shape}")

Đầu ra

A sequential model is being defined, that has three layers
The model is being called on test data
Output shape: (2, 4)
The layers are:
  layer_1: (None, 2)
  layer_2: (None, 3)
  layer_3: (None, 4)

Ví dụ: CẦN Functional API (không dùng Sequential được)

# Multiple inputs
input_a = keras.Input(shape=(32,), name="input_a")
input_b = keras.Input(shape=(32,), name="input_b")
merged = layers.Concatenate()([input_a, input_b])
output = layers.Dense(1)(merged)

model = keras.Model(inputs=[input_a, input_b], outputs=output)

# Shared layer
shared_dense = layers.Dense(64, activation='relu')
x1 = shared_dense(input_a)
x2 = shared_dense(input_b)  # Cùng weights

# Residual connection
x = layers.Dense(64)(inputs)
residual = layers.Add()([x, inputs])  # Skip connection

Quyết định nhanh

Đặc điểm modelSequentialFunctional API
Single input/output✅✅
Multiple inputs/outputs❌✅
Shared layers❌✅
Non-linear topology❌✅
Đơn giản, nhanh✅⚠️

Mẹo: Bắt đầu với Sequential. Khi cần tính năng nâng cao, chuyển sang Functional API (có thể convert: functional_model = keras.Model(inputs=seq_model.input, outputs=seq_model.output)).