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

Xây dựng Sequential Model (Dense Layer) với TensorFlow/Keras Python

Mô tả

Tạo model Sequential bằng cách thêm các Dense layer rõ ràng, sau đó gọi model trên dữ liệu test.

Cách 1: Tạo layer riêng lẻ rồi kết hợp (Functional style)

import tensorflow as tf
from tensorflow.keras import layers

# Tạo 3 Dense layer riêng biệt
layer1 = layers.Dense(2, activation="relu", name="layer_1")
layer2 = layers.Dense(3, activation="relu", name="layer_2")
layer3 = layers.Dense(4, name="layer_3")

print("Three dense layers created")

# Gọi tuần tự (functional call)
x = tf.ones((4, 4))  # Batch 4, input dim 4
y = layer3(layer2(layer1(x)))

print("Model called on test data")
print(f"Output shape: {y.shape}")  # (4, 4)

# Xem layers
print("Layers:", [layer.name for layer in [layer1, layer2, layer3]])

Cách 2: Sequential constructor với list layers (Khuyên dùng)

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

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

print("Model summary:")
model.summary()

# Gọi trên test data
x = tf.ones((2, 4))
y = model(x)
print(f"\nOutput shape: {y.shape}")  # (2, 4)

Đầu ra model.summary()

Model: "my_sequential_model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 layer_1 (Dense)             (None, 2)                 10
 layer_2 (Dense)             (None, 3)                 9
 layer_3 (Dense)             (None, 4)                 16
=================================================================
Total params: 35
Trainable params: 35
Non-trainable params: 0
_________________________________________________________________

Cách 3: Add layer lần lượt (Incremental)

model = Sequential(name="incremental_model")
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 added")
model.summary()

So sánh 3 cách

CáchƯu điểmNhược điểmDùng khi
Layer riêng + callLinh hoạt, reuse layer, custom forwardPhức tạp, không có summary() tự độngCustom training loop, shared layers
Sequential(list)Ngắn gọn, có summary, dễ đọcÍt linh hoạt sau khi tạoPhổ biến nhất
Sequential.add()Xây dựng động, có thể trong loopCần input_shape ở layer đầuArchitecture tìm kiếm tự động (NAS)

Compile & Train

model.compile(optimizer='adam', loss='mse', metrics=['mae'])
history = model.fit(X_train, y_train, epochs=10, validation_split=0.2)