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

# 機(jī)器學(xué)習(xí)框架
from tensorflow import keras # 模型構(gòu)建與訓(xùn)練
from tensorflow.keras import layers # 神經(jīng)網(wǎng)絡(luò)層組件

# 數(shù)據(jù)集
from tensorflow.keras.datasets import mnist # 經(jīng)典手寫數(shù)字?jǐn)?shù)據(jù)集

安裝依賴的命令:

pip install tensorflow matplotlib numpy pandas

1.3 開(kāi)發(fā)環(huán)境配置建議

二、數(shù)據(jù)處理:機(jī)器學(xué)習(xí)的基礎(chǔ)

2.1 數(shù)據(jù)集加載與探索

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

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

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

2.2 數(shù)據(jù)預(yù)處理的必要性

原始像素值范圍為0-255,直接輸入模型會(huì)導(dǎo)致數(shù)值不穩(wěn)定,歸一化(Normalization)是關(guān)鍵步驟:

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

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

# 標(biāo)簽轉(zhuǎn)換為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 數(shù)據(jù)可視化:理解輸入特征

通過(guò)可視化樣本,檢查數(shù)據(jù)質(zhì)量并直觀理解模型的學(xué)習(xí)目標(biāo):

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()

三、構(gòu)建神經(jīng)網(wǎng)絡(luò)模型

3.1 卷積神經(jīng)網(wǎng)絡(luò)(CNN)的設(shè)計(jì)原理

CNN通過(guò)局部感知和權(quán)值共享高效處理圖像數(shù)據(jù),核心組件包括:

3.2 模型架構(gòu)實(shí)現(xiàn)

model = keras.Sequential(
[
layers.Input(shape=(28, 28, 1)),
# 第一卷積塊:32個(gè)3x3卷積核,ReLU激活
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)), # 輸出形狀變?yōu)?13, 13, 32)
# 第二卷積塊:64個(gè)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), # 隨機(jī)丟棄50%神經(jīng)元,防止過(guò)擬合
layers.Dense(num_classes, activation="softmax") # 輸出10個(gè)類別的概率
]
)

model.summary() # 打印模型結(jié)構(gòu)

模型結(jié)構(gòu)輸出示例:

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

3.3 模型編譯:配置學(xué)習(xí)過(guò)程

model.compile(
loss="categorical_crossentropy", # 多分類交叉熵?fù)p失函數(shù)
optimizer="adam", # 自適應(yīng)學(xué)習(xí)率優(yōu)化器
metrics=["accuracy"] # 監(jiān)控準(zhǔn)確率
)

四、模型訓(xùn)練與評(píng)估

4.1 訓(xùn)練過(guò)程參數(shù)解析

batch_size = 128  # 每次迭代使用的樣本數(shù)
epochs = 15 # 遍歷整個(gè)訓(xùn)練集的次數(shù)

history = model.fit(
train_images,
train_labels,
batch_size=batch_size,
epochs=epochs,
validation_split=0.1 # 10%訓(xùn)練數(shù)據(jù)作為驗(yàn)證集
)

4.2 訓(xùn)練過(guò)程可視化

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

# 準(zhǔn)確率曲線
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 模型評(píng)估與過(guò)擬合判斷

score = model.evaluate(test_images, test_labels, verbose=0)
print("測(cè)試集損失:", score[0]) # 理想值應(yīng)接近驗(yàn)證損失
print("測(cè)試集準(zhǔn)確率:", score[1]) # 高于98%表明模型表現(xiàn)優(yōu)秀

五、模型應(yīng)用與部署

5.1 單樣本預(yù)測(cè)實(shí)現(xiàn)

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)

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

5.2 模型保存與加載

# 保存完整模型(包括結(jié)構(gòu)和權(quán)重)
model.save("mnist_cnn.h5")

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

5.3 使用Flask部署API服務(wù)

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') # 轉(zhuǎn)為灰度圖
img = img.resize((28, 28)) # 調(diào)整尺寸

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

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

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

測(cè)試API

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

六、模型優(yōu)化與進(jìn)階學(xué)習(xí)

6.1 性能優(yōu)化技巧

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 常見(jiàn)問(wèn)題解答(FAQ)

6.3 推薦學(xué)習(xí)路徑

  1. 基礎(chǔ)鞏固:學(xué)習(xí)線性代數(shù)、概率論基礎(chǔ)。
  2. 框架進(jìn)階:掌握TensorFlow的底層API和自定義訓(xùn)練循環(huán)。
  3. 項(xiàng)目實(shí)戰(zhàn):參加Kaggle競(jìng)賽(如Digit Recognizer)。
  4. 擴(kuò)展應(yīng)用:探索自然語(yǔ)言處理(NLP)或強(qiáng)化學(xué)習(xí)。

總結(jié)

通過(guò)本教程,你已掌握了使用Python和Keras開(kāi)發(fā)AI模型的完整流程。從數(shù)據(jù)預(yù)處理到模型部署,每個(gè)環(huán)節(jié)都至關(guān)重要。建議在實(shí)際項(xiàng)目中嘗試調(diào)整模型結(jié)構(gòu)(如增加LSTM處理時(shí)序數(shù)據(jù)),或探索更復(fù)雜的應(yīng)用場(chǎng)景(如目標(biāo)檢測(cè))。記住,持續(xù)實(shí)踐和參與開(kāi)源社區(qū)是提升技能的最佳途徑。

上一篇:

Gemini Pro 2.5 入門:構(gòu)建一個(gè)簡(jiǎn)單的 AI 代理

下一篇:

免費(fèi)強(qiáng)大的API開(kāi)發(fā)和調(diào)試工具——Reqable
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)