Keras 如何用於模型的訓練、評估和推理?
Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。
可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:
pip install tensorflow
Keras 是作為 ONEIROS 專案(開放式神經電子智慧機器人作業系統)研究的一部分開發的。Keras 是一個深度學習 API,用 Python 編寫。它是一個高階 API,具有高效的介面,有助於解決機器學習問題。
它具有高度可擴充套件性,並具有跨平臺能力。這意味著 Keras 可以執行在 TPU 或 GPU 叢集上。Keras 模型也可以匯出以在 Web 瀏覽器或手機上執行。
Keras 已經存在於 Tensorflow 包中。可以使用以下程式碼行訪問它。
import tensorflow from tensorflow import keras
Keras 函式式 API 有助於建立比使用順序 API 建立的模型更靈活的模型。函式式 API 可以處理具有非線性拓撲的模型,可以共享層並處理多個輸入和輸出。深度學習模型通常是一個包含多個層的定向無環圖 (DAG)。函式式 API 有助於構建層圖。
我們正在使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 有助於透過瀏覽器執行 Python 程式碼,並且無需任何配置即可免費訪問 GPU(圖形處理單元)。Colaboratory 構建在 Jupyter Notebook 之上。以下是程式碼片段:
示例
print("Load the MNIST data")
print("Split data into training and test data")
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print("Reshape the data for better training")
x_train = x_train.reshape(60000, 784).astype("float32") / 255
x_test = x_test.reshape(10000, 784).astype("float32") / 255
print("Compile the model")
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.RMSprop(),
metrics=["accuracy"],
)
print("Fit the data to the model")
history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)
test_scores = model.evaluate(x_test, y_test, verbose=2)
print("The loss associated with model:", test_scores[0])
print("The accuracy of the model:", test_scores[1])程式碼來源 - https://www.tensorflow.org/guide/keras/functional
輸出
Load the MNIST data Split data into training and test data Reshape the data for better training Compile the model Fit the data to the model Epoch 1/2 750/750 [==============================] - 3s 3ms/step - loss: 0.5768 - accuracy: 0.8394 - val_loss: 0.2015 - val_accuracy: 0.9405 Epoch 2/2 750/750 [==============================] - 2s 3ms/step - loss: 0.1720 - accuracy: 0.9495 - val_loss: 0.1462 - val_accuracy: 0.9580 313/313 - 0s - loss: 0.1433 - accuracy: 0.9584 The loss associated with model: 0.14328785240650177 The accuracy of the model: 0.9584000110626221
解釋
輸入資料(MNIST 資料)載入到環境中。
資料被分成訓練集和測試集。
資料被重新整形,使其準確性得到提高。
模型被構建和編譯。
然後將其擬合到訓練資料。
與訓練相關的準確性和損失顯示在控制檯上。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP