如何使用預製 Estimator 在 Tensorflow 中下載 Iris 資料集?


Tensorflow 可以使用預製 Estimator 透過 Keras 包中的 `get_file` 方法下載 iris 資料集。Google API 儲存著 iris 資料集,可以將其作為引數傳遞給 `get_file` 方法。

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

我們將使用 Keras Sequential API,它有助於構建一個順序模型,該模型用於處理簡單的層堆疊,其中每一層都只有一個輸入張量和一個輸出張量。

包含至少一層卷積層的神經網路稱為卷積神經網路。我們可以使用卷積神經網路構建學習模型。

TensorFlow Text 包含一系列與文字相關的類和操作,可用於 TensorFlow 2.0。TensorFlow Text 可用於預處理序列建模。

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

讓我們瞭解如何使用 Estimator。

Estimator 是 TensorFlow 中對完整模型的高階表示。它旨在實現輕鬆擴充套件和非同步訓練。

模型使用 iris 資料集進行訓練。它有 4 個特徵和一個標籤。

  • 萼片長度
  • 萼片寬度
  • 花瓣長度
  • 花瓣寬度

基於這些資訊,可以定義一些有助於解析資料的常量。

示例

import tensorflow as tf
import pandas as pd
print("Column names defined")
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
print("Iris training data is being downloaded")
train_path = tf.keras.utils.get_file(
"iris_training.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv")
print("Iris test data is being downloaded")
test_path = tf.keras.utils.get_file(
"iris_test.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv")
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
print("Sample data is being displayed")
train.head()

程式碼來源 -https://www.tensorflow.org/tutorials/estimator/premade#first_things_first

輸出

Column names defined
Iris training data is being downloaded
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv
8192/2194 [================================================================================================================] - 0s 0us/step
Iris test data is being downloaded
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv
8192/573 [============================================================================================================================================================================================================================================================================================================================================================================================================================================] - 0s 0us/step
Sample data is being displayed
SepalLength SepalWidth PetalLength PetalWidth Species
0 6.4 2.8 5.6 2.2 2
1 5.0 2.3 3.3 1.0 1
2 4.9 2.5 4.5 1.7 2
3 4.9 3.1 1.5 0.1 0
4 5.7 3.8 1.7 0.3 0

解釋

  • 定義列名。
  • 下載資料。
  • 在控制檯上顯示一些示例資料。

更新於: 2021年2月22日

155 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.