如何使用 Python 中的 TensorFlow 對資料進行標準化?


我們將使用花卉資料集,其中包含數千朵花的影像。它包含 5 個子目錄,每個類別都有一個子目錄。一旦使用“get_file”方法下載了花卉資料集,它將被載入到環境中以供使用。

可以透過在模型中引入歸一化層來標準化花卉資料。此層稱為“Rescaling”層,它使用“map”方法應用於整個資料集。

閱讀更多: 什麼是 TensorFlow 以及 Keras 如何與 TensorFlow 協作建立神經網路?

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

print("Normalization layer is created ")
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
print("This layer is applied to dataset using map function ")
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
print(np.min(first_image), np.max(first_image))

程式碼來源: https://www.tensorflow.org/tutorials/images/classification

輸出

Normalization layer is created
This layer is applied to dataset using map function
0.0 1.0

解釋

  • RGB 通道值在 [0, 255] 範圍內。
  • 這對於神經網路來說並不理想。
  • 根據經驗,確保輸入值較小。
  • 因此,我們可以將值標準化為介於 [0, 1] 之間。
  • 這是透過使用 Rescaling 層完成的。
  • 可以透過呼叫 map 函式將該層應用於資料集來完成。
  • 另一種方法是在模型定義中包含該層。
  • 這將簡化部署過程。

更新於: 2021 年 2 月 20 日

309 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.