圖像分類是計算機視覺中的基礎任務,本實例使用 TensorFlow 和 Keras 庫對 MNIST 手寫數字數據集進行分類。

import tensorflow as tffrom tensorflow.keras.datasets import mnistfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattenfrom tensorflow.keras.utils import to_categorical# 加載MNIST數據集(train_images, train_labels), (test_images, test_labels) = mnist.load_data()# 數據預處理train_images = train_images.reshape((-1, 28 * 28)).astype('float32') / 255.0test_images = test_images.reshape((-1, 28 * 28)).astype('float32') / 255.0train_labels = to_categorical(train_labels)test_labels = to_categorical(test_labels)# 構建模型model = Sequential([ Flatten(input_shape=(28, 28)), Dense(128, activation='relu'), Dense(10, activation='softmax')])# 編譯模型model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# 訓練模型model.fit(train_images, train_labels, epochs=5, batch_size=64)# 評估模型test_loss, test_acc = model.evaluate(test_images, test_labels)print(f"Test accuracy: {test_acc}") 1. 代碼解釋:

導入必要的庫,包括 TensorFlow、Keras 相關模塊以及用於數據處理的函數。 加載 MNIST 數據集,該數據集包含手寫數字的圖像和對應的標籤。 對數據進行預處理,將圖像數據展平為一維向量,並將像素值歸一化到 0 - 1 範圍。同時,將標籤轉換為獨熱編碼形式。 使用 Sequential 模型構建一個簡單的神經網絡,包含一個 Flatten 層將二維圖像數據轉換為一維,一個具有 128 個神經元的全連接層(使用 ReLU 激活函數),以及一個輸出層,有 10 個神經元(對應 10 個數字類別),使用 softmax 激活函數進行分類。 編譯模型,指定優化器為 Adam,損失函數為交叉熵損失,評估指標為準確率。 使用訓練數據對模型進行訓練,指定訓練輪數為 5,每批數據大小為 64。 最後使用測試數據評估模型的性能,打印出測試準確率。圖像分類是計算機視覺中的基礎任務,本實例使用 TensorFlow 和 Keras 庫對 MNIST 手寫數字數據集進行分類。

import tensorflow as tffrom tensorflow.keras.datasets import mnistfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattenfrom tensorflow.keras.utils import to_categorical# 加載MNIST數據集(train_images, train_labels), (test_images, test_labels) = mnist.load_data()# 數據預處理train_images = train_images.reshape((-1, 28 * 28)).astype('float32') / 255.0test_images = test_images.reshape((-1, 28 * 28)).astype('float32') / 255.0train_labels = to_categorical(train_labels)test_labels = to_categorical(test_labels)# 構建模型model = Sequential([ Flatten(input_shape=(28, 28)), Dense(128, activation='relu'), Dense(10, activation='softmax')])# 編譯模型model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# 訓練模型model.fit(train_images, train_labels, epochs=5, batch_size=64)# 評估模型test_loss, test_acc = model.evaluate(test_images, test_labels)print(f"Test accuracy: {test_acc}") 1. 代碼解釋:

導入必要的庫,包括 TensorFlow、Keras 相關模塊以及用於數據處理的函數。 加載 MNIST 數據集,該數據集包含手寫數字的圖像和對應的標籤。 對數據進行預處理,將圖像數據展平為一維向量,並將像素值歸一化到 0 - 1 範圍。同時,將標籤轉換為獨熱編碼形式。 使用 Sequential 模型構建一個簡單的神經網絡,包含一個 Flatten 層將二維圖像數據轉換為一維,一個具有 128 個神經元的全連接層(使用 ReLU 激活函數),以及一個輸出層,有 10 個神經元(對應 10 個數字類別),使用 softmax 激活函數進行分類。 編譯模型,指定優化器為 Adam,損失函數為交叉熵損失,評估指標為準確率。 使用訓練數據對模型進行訓練,指定訓練輪數為 5,每批數據大小為 64。 最後使用測試數據評估模型的性能,打印出測試準確率。