如何使用 Python 將分類頭附加到 TensorFlow?
TensorFlow 可以使用一個包含密集層的順序模型來附加分類頭,也可以使用先前定義的特徵提取器模型。
閱讀更多: 什麼是 TensorFlow 以及 Keras 如何與 TensorFlow 協作建立神經網路?
包含至少一層卷積層的神經網路被稱為卷積神經網路。我們可以使用卷積神經網路構建學習模型。
影像分類遷移學習背後的直覺是,如果一個模型在一個大型且通用的資料集上進行訓練,則此模型可以有效地用作視覺世界的通用模型。它將學習特徵對映,這意味著使用者不必從頭開始在大型資料集上訓練大型模型。
TensorFlow Hub 是一個包含預訓練 TensorFlow 模型的儲存庫。TensorFlow 可用於微調學習模型。
我們將瞭解如何使用 TensorFlow Hub 中的模型與 tf.keras,使用 TensorFlow Hub 中的影像分類模型。完成後,可以執行遷移學習以微調模型以用於自定義影像類別。這是透過使用預訓練的分類器模型來獲取影像並預測它是做什麼的來完成的。這可以在不需要任何訓練的情況下完成。
我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助透過瀏覽器執行 Python 程式碼,並且無需任何配置即可免費訪問 GPU(圖形處理單元)。Colaboratory 建立在 Jupyter Notebook 之上。
示例
print("Attaching a classification head")
num_classes = len(class_names)
model = tf.keras.Sequential([
feature_extractor_layer,
tf.keras.layers.Dense(num_classes)
])
print("The base architecture of the model")
model.summary()
print("The predictions are made")
predictions = model(image_batch)
print("The dimensions of the predictions")
predictions.shape程式碼來源 −https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub
輸出
Attaching a classification head The base architecture of the model Model: "sequential_3" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= keras_layer_1 (KerasLayer) (None, 1280) 2257984 _________________________________________________________________ dense_3 (Dense) (None, 5) 6405 ================================================================= Total params: 2,264,389 Trainable params: 6,405 Non-trainable params: 2,257,984 _________________________________________________________________ The predictions are made The dimensions of the predictions TensorShape([32, 5])
解釋
- 分類頭已附加到模型。
- 完成此操作後,將確定模型的基本架構。
- 這是藉助“摘要”方法完成的。
- 確定資料的維度。
- 此資訊顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP