如何使用 Keras 在 Python 中實現遷移學習?


TensorFlow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用,可以實現演算法、深度學習應用程式等等。它用於研究和生產目的。

張量是 TensorFlow 中使用的資料結構。它有助於連線資料流圖中的邊。這個資料流圖被稱為“資料流圖”。張量只不過是多維陣列或列表。

Keras 在希臘語中意為“角”。Keras 是作為 ONEIROS 專案(開放式神經電子智慧機器人作業系統)研究的一部分而開發的。Keras 是一個用 Python 編寫的深度學習 API。它是一個高階 API,具有高效的介面,有助於解決機器學習問題。

它執行在 TensorFlow 框架之上。它旨在幫助快速進行實驗。它提供了開發和封裝機器學習解決方案所需的必要抽象和構建塊。

它具有高度可擴充套件性,並具有跨平臺能力。這意味著 Keras 可以在 TPU 或 GPU 叢集上執行。Keras 模型也可以匯出到 Web 瀏覽器或行動電話上執行。

Keras 已經存在於 TensorFlow 包中。可以使用以下程式碼行訪問它。

import tensorflow
from tensorflow import keras

我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助在瀏覽器上執行 Python 程式碼,無需任何配置,並且可以免費訪問 GPU(圖形處理單元)。Colaboratory 建立在 Jupyter Notebook 之上。以下是程式碼片段:

示例

model = keras.Sequential([
   keras.Input(shape=(784))
   layers.Dense(32, activation='relu'),
   layers.Dense(32, activation='relu'),
   layers.Dense(32, activation='relu'),
   layers.Dense(10),
])
print("Load the pre-trained weights")
model.load_weights(...)
print("Freeze all the layers except the last layer")
for layer in model.layers[:-1]:
   layer.trainable = False
print("Recompile the model and train it")
print("The last layer weights will be updated")
model.compile(...)
model.fit(...)

程式碼來源:https://www.tensorflow.org/guide/keras/sequential_model

輸出

Load the pre-trained weights
Freeze all the layers except the last layer
Recompile the model and train it
The last layer weights will be updated

解釋

  • 遷移學習是指凍結模型中的底層並訓練頂層。

  • 構建順序模型。

  • 載入預訓練的舊模型權重並將其與該模型繫結。

  • 凍結底層,最後一層除外。

  • 迭代各層,並將除最後一層外的每一層的“layer.trainable”設定為“False”。

  • 將其編譯並擬合到資料。

更新於:2021年1月18日

273 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.