import numpy as np # 高性能數組運算
import pandas as pd # 數據表格處理(雖然本例未使用,但在其他場景常用)
import matplotlib.pyplot as plt # 數據可視化

# 機器學習框架
from tensorflow import keras # 模型構建與訓練
from tensorflow.keras import layers # 神經網絡層組件

# 數據集
from tensorflow.keras.datasets import mnist # 經典手寫數字數據集

安裝依賴的命令:

pip install tensorflow matplotlib numpy pandas

1.3 開發環境配置建議

二、數據處理:機器學習的基礎

2.1 數據集加載與探索

MNIST數據集包含60,000張訓練圖像和10,000張測試圖像,每張為28×28像素的手寫數字灰度圖。加載數據后,建議先了解數據分布:

# 加載數據集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 輸出基本信息
print(f"訓練集維度: {train_images.shape}") # (60000, 28, 28)
print(f"標簽類別數: {len(np.unique(train_labels))}") # 10(0-9)

2.2 數據預處理的必要性

原始像素值范圍為0-255,直接輸入模型會導致數值不穩定,歸一化(Normalization)是關鍵步驟:

# 將像素值縮放到0-1之間
train_images = train_images.astype("float32") / 255
test_images = test_images.astype("float32") / 255

# 添加通道維度(CNN要求輸入形狀為[高度, 寬度, 通道數])
train_images = np.expand_dims(train_images, -1) # 形狀變為(60000, 28, 28, 1)
test_images = np.expand_dims(test_images, -1)

# 標簽轉換為One-Hot編碼
num_classes = 10
train_labels = keras.utils.to_categorical(train_labels, num_classes)
test_labels = keras.utils.to_categorical(test_labels, num_classes)

2.3 數據可視化:理解輸入特征

通過可視化樣本,檢查數據質量并直觀理解模型的學習目標:

plt.figure(figsize=(10,5))
for i in range(15):
plt.subplot(3,5,i+1)
plt.imshow(train_images[i].squeeze(), cmap='gray') # 移除通道維度顯示圖像
plt.title(f"Label: {np.argmax(train_labels[i])}")
plt.axis('off')
plt.tight_layout()
plt.show()

三、構建神經網絡模型

3.1 卷積神經網絡(CNN)的設計原理

CNN通過局部感知和權值共享高效處理圖像數據,核心組件包括:

3.2 模型架構實現

model = keras.Sequential(
[
layers.Input(shape=(28, 28, 1)),
# 第一卷積塊:32個3x3卷積核,ReLU激活
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)), # 輸出形狀變為(13, 13, 32)
# 第二卷積塊:64個3x3卷積核
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)), # 輸出形狀(5, 5, 64)
# 全連接層
layers.Flatten(), # 將3D特征展平為1D向量(5*5*64=1600)
layers.Dropout(0.5), # 隨機丟棄50%神經元,防止過擬合
layers.Dense(num_classes, activation="softmax") # 輸出10個類別的概率
]
)

model.summary() # 打印模型結構

模型結構輸出示例:

Total params: 34,826
Trainable params: 34,826
Non-trainable params: 0

3.3 模型編譯:配置學習過程

model.compile(
loss="categorical_crossentropy", # 多分類交叉熵損失函數
optimizer="adam", # 自適應學習率優化器
metrics=["accuracy"] # 監控準確率
)

四、模型訓練與評估

4.1 訓練過程參數解析

batch_size = 128  # 每次迭代使用的樣本數
epochs = 15 # 遍歷整個訓練集的次數

history = model.fit(
train_images,
train_labels,
batch_size=batch_size,
epochs=epochs,
validation_split=0.1 # 10%訓練數據作為驗證集
)

4.2 訓練過程可視化

# 繪制訓練曲線
plt.figure(figsize=(12, 5))

# 準確率曲線
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy Evolution')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

# 損失曲線
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss Evolution')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.tight_layout()
plt.show()

4.3 模型評估與過擬合判斷

score = model.evaluate(test_images, test_labels, verbose=0)
print("測試集損失:", score[0]) # 理想值應接近驗證損失
print("測試集準確率:", score[1]) # 高于98%表明模型表現優秀

五、模型應用與部署

5.1 單樣本預測實現

def predict_sample(model, image):
img = image.astype("float32") / 255
img = np.expand_dims(img, axis=0) # 添加批次維度
img = np.expand_dims(img, axis=-1) # 添加通道維度
prediction = model.predict(img)
return np.argmax(prediction)

# 隨機測試樣本預測
sample_index = np.random.randint(0, len(test_images))
plt.imshow(test_images[sample_index].squeeze(), cmap='gray')
plt.title(f"預測: {predict_sample(model, test_images[sample_index])}\n真實: {np.argmax(test_labels[sample_index])}")
plt.axis('off')
plt.show()

5.2 模型保存與加載

# 保存完整模型(包括結構和權重)
model.save("mnist_cnn.h5")

# 加載模型進行推理
loaded_model = keras.models.load_model("mnist_cnn.h5")

5.3 使用Flask部署API服務

from flask import Flask, request, jsonify
import numpy as np
from PIL import Image
import io

app = Flask(__name__)
model = keras.models.load_model("mnist_cnn.h5")

@app.route('/predict', methods=['POST'])
def predict():
# 接收上傳的圖像文件
file = request.files['image']
img = Image.open(io.BytesIO(file.read())).convert('L') # 轉為灰度圖
img = img.resize((28, 28)) # 調整尺寸

# 預處理
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=(0, -1)) # 添加批次和通道維度

# 預測并返回結果
prediction = model.predict(img_array)
return jsonify({'prediction': int(np.argmax(prediction))})

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

測試API

curl -X POST -F "image=@test_image.png" http://localhost:5000/predict
# 預期返回:{"prediction": 7}

六、模型優化與進階學習

6.1 性能優化技巧

from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(rotation_range=10, zoom_range=0.1)
model.fit(datagen.flow(train_images, train_labels, batch_size=32))

6.2 常見問題解答(FAQ)

6.3 推薦學習路徑

  1. 基礎鞏固:學習線性代數、概率論基礎。
  2. 框架進階:掌握TensorFlow的底層API和自定義訓練循環。
  3. 項目實戰:參加Kaggle競賽(如Digit Recognizer)。
  4. 擴展應用:探索自然語言處理(NLP)或強化學習。

總結

通過本教程,你已掌握了使用Python和Keras開發AI模型的完整流程。從數據預處理到模型部署,每個環節都至關重要。建議在實際項目中嘗試調整模型結構(如增加LSTM處理時序數據),或探索更復雜的應用場景(如目標檢測)。記住,持續實踐和參與開源社區是提升技能的最佳途徑。

上一篇:

Gemini Pro 2.5 入門:構建一個簡單的 AI 代理

下一篇:

免費強大的API開發和調試工具——Reqable
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費