如何使用 Python 和 TensorFlow 迭代資料集並顯示樣本資料?


TensorFlow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用可以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。這是因為它使用了 NumPy 和多維陣列。這些多維陣列也稱為“張量”。該框架支援使用深度神經網路。它具有高度的可擴充套件性,並附帶許多流行的資料集。它使用 GPU 計算並自動管理資源。它附帶大量的機器學習庫,並得到良好的支援和文件記錄。該框架能夠執行深度神經網路模型、訓練它們以及建立預測各個資料集相關特徵的應用程式。

可以使用以下程式碼行在 Windows 上安裝 “tensorflow” 包:

pip install tensorflow

張量是 TensorFlow 中使用的資料結構。它有助於連線資料流圖中的邊。這個資料流圖被稱為“資料流圖”。張量只不過是一個多維陣列或列表。它們可以使用三個主要屬性來標識:

  • − 它說明張量的維度。可以理解為張量的階數或已定義張量的維度數。

  • 型別 − 它說明與張量元素相關聯的資料型別。它可以是一維、二維或 n 維張量。

  • 形狀 − 它是行數和列數的組合。

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

示例

print("Iterating through the training data")
for i, label in enumerate(raw_train_ds.class_names):
   print("Label", i, "maps to", label)
print("The training parameters have been defined")
raw_val_ds = preprocessing.text_dataset_from_directory(
   train_dir,
   batch_size=batch_size,
   validation_split=0.25,
   subset='validation',
   seed=seed)
print("The test dataset is being prepared")
test_dir = dataset_dir/'test'
raw_test_ds = preprocessing.text_dataset_from_directory(
   test_dir, batch_size=batch_size)

程式碼來源 − https://www.tensorflow.org/tutorials/load_data/text

輸出

Iterating through the training data
Label 0 maps to csharp
Label 1 maps to java
Label 2 maps to javascript
Label 3 maps to python
The training parameters have been defined
Found 8000 files belonging to 4 classes.
Using 2000 files for validation.
The test dataset is being prepared
Found 8000 files belonging to 4 classes.

解釋

  • 迭代訓練資料。

  • 在控制檯上顯示訓練集、測試集和驗證集的行數。

  • 使用 “text_dataset_from_directory” 實用程式預處理資料。

更新於: 2021年1月18日

294 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.