跳轉到

1.3 Functional API

範例程式:Open In Colab

Functional API 是 Keras 中更有彈性的建模方式。當模型不再只是單一路徑,而是需要多輸入、多輸出、分支、合併或跳接時,就會用到 Functional API。

1. 學習目標

這篇用一個簡化的房價預測範例示範多輸入模型:一組輸入是數值特徵,另一組輸入是地區 one-hot 特徵。模型會分別處理兩組輸入,再把它們合併後預測房價。

這個範例的重點不是房價本身,而是讓讀者看懂「不同資料來源可以先走不同分支,再合併成同一個模型」的建模方式。

2. Functional API 的核心概念

Functional API 的寫法像是在組裝資料流:

inputs = tf.keras.Input(shape=(4,))
x = tf.keras.layers.Dense(16, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)

重點是 layer 可以像函數一樣被呼叫,並回傳下一段 tensor。這讓模型結構可以分支、合併與重複使用。

3. 多輸入模型範例

numeric_input = tf.keras.Input(shape=(3,), name='numeric')
area_input = tf.keras.Input(shape=(3,), name='area')

x = tf.keras.layers.Dense(16, activation='relu')(numeric_input)
combined = tf.keras.layers.Concatenate()([x, area_input])
output = tf.keras.layers.Dense(1)(combined)

model = tf.keras.Model(inputs=[numeric_input, area_input], outputs=output)

這種結構很常出現在真實專案:數值資料、類別資料、文字或圖片可能會用不同分支處理,再合併成最後的預測。

4. 何時該用 Functional API?

情境 建議
單一路徑模型 Sequential API 即可
多輸入資料 Functional API
多輸出任務 Functional API
需要分支或合併 Functional API
需要 skip connection Functional API

5. 如何套用自己的資料?

改成自己的資料時,需要確認每個輸入分支的 shape:

  1. 數值特徵:Input(shape=(數值欄位數,))
  2. 類別 one-hot:Input(shape=(類別展開後欄位數,))
  3. 圖片:Input(shape=(height, width, channels))
  4. 文字序列:Input(shape=(sequence_length,))

只要資料來源不只一種,或不同特徵需要不同前處理流程,就可以考慮 Functional API。常見例子包括數值特徵加類別特徵、圖片加表格資料、文字加使用者屬性等。

6. 小結

Functional API 是進階 Keras 模型設計的基礎。只要掌握 Input、layer 呼叫、ConcatenateModel(inputs, outputs),就能處理比 Sequential 更接近真實專案的資料型態。