神經結構化學習:使用結構化訊號進行訓練

神經結構化學習 (NSL) 是一種新的學習典範,除了特徵輸入外,還會結合結構化訊號來訓練神經網路。結構可以是圖表所代表的顯性結構,或是對抗性擾動所引起的隱性結構。

結構化訊號通常用於表示樣本之間 (可能已標記或未標記) 的關係或相似性。因此,在神經網路訓練期間運用這些訊號,可以充分利用已標記和未標記的資料,進而提高模型準確性,尤其是在已標記資料量相對較少的情況下。此外,透過新增對抗性擾動產生的樣本訓練的模型,已證實能有效抵禦惡意攻擊,這些攻擊旨在誤導模型的預測或分類。

NSL 廣義化為神經圖表學習對抗性學習。TensorFlow 中的 NSL 架構提供下列容易使用的 API 和工具,供開發人員使用結構化訊號訓練模型

  • Keras API,可使用圖表 (顯性結構) 和對抗性擾動 (隱性結構) 進行訓練。
  • TF 運算和函式,可在使用較低階 TensorFlow API 時,使用結構進行訓練
  • 工具,用於建構圖表和建立圖表輸入以進行訓練

整合結構化訊號僅在訓練期間完成。因此,服務/推論工作流程的效能保持不變。如需神經結構化學習的詳細資訊,請參閱我們的架構說明。若要開始使用,請參閱我們的安裝指南,如需 NSL 的實務簡介,請查看我們的教學課程。

import tensorflow as tf
import neural_structured_learning as nsl

# Prepare data.
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Create a base model -- sequential, functional, or subclass.
model = tf.keras.Sequential([
    tf.keras.Input((28, 28), name='feature'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

# Wrap the model with adversarial regularization.
adv_config = nsl.configs.make_adv_reg_config(multiplier=0.2, adv_step_size=0.05)
adv_model = nsl.keras.AdversarialRegularization(model, adv_config=adv_config)

# Compile, train, and evaluate.
adv_model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
adv_model.fit({'feature': x_train, 'label': y_train}, batch_size=32, epochs=5)
adv_model.evaluate({'feature': x_test, 'label': y_test})