如何使用 Python 和 TensorFlow 訓練伊利亞特資料集?


TensorFlow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用可以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。這是因為它使用了 NumPy 和多維陣列。這些多維陣列也稱為“張量”。該框架支援與深度神經網路一起工作。

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

pip install tensorflow

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

我們將使用伊利亞特資料集,其中包含 William Cowper、Edward(Derby 伯爵)和 Samuel Butler 三個譯本的文字資料。該模型經過訓練,可以在給出單行文字時識別翻譯者。所使用的文字檔案已進行預處理。這包括刪除文件頁首和頁尾、行號和章節標題。

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

示例

以下是程式碼片段:

vocab_size += 2

print("Configure the dataset for better performance")
train_data = configure_dataset(train_data)
validation_data = configure_dataset(validation_data)

print("Train the model")
model = create_model(vocab_size=vocab_size, num_labels=3)
model.compile(
   optimizer='adam',
   loss=losses.SparseCategoricalCrossentropy(from_logits=True),
   metrics=['accuracy'])
print("Fit the training data to the model")
history = model.fit(train_data, validation_data=validation_data, epochs=3)

print("Finding the accuracy and loss associated with training")
loss, accuracy = model.evaluate(validation_data)

print("The loss is : ", loss)
print("The accuracy is : {:2.2%}".format(accuracy))

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

輸出

Configure the dataset for better performance
Train the model
Fit the training data to the model
Epoch 1/3
697/697 [==============================] - 35s 17ms/step - loss: 0.6891 - accuracy: 0.6736 -
val_loss: 0.3718 - val_accuracy: 0.8404
Epoch 2/3
697/697 [==============================] - 8s 11ms/step - loss: 0.3149 - accuracy: 0.8713 -
val_loss: 0.3621 - val_accuracy: 0.8422
Epoch 3/3
697/697 [==============================] - 8s 11ms/step - loss: 0.2165 - accuracy: 0.9162 -
val_loss: 0.4002 - val_accuracy: 0.8404
Finding the accuracy and loss associated with training
79/79 [==============================] - 1s 2ms/step - loss: 0.4002 - accuracy: 0.8404
The loss is : 0.40021833777427673
The accuracy is : 84.04%

解釋

  • 該模型在預處理的向量化資料集上進行訓練。

  • 完成後,將其編譯並擬合到模型中。

  • 使用“evaluate”方法評估與模型相關的損失和準確性。

  • 此資料顯示在控制檯上。

更新於:2021年1月19日

86 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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