Neural Structured Learning:使用結構化訊號進行訓練

Neural Structured Learning (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})