397 lines
12 KiB
Plaintext
397 lines
12 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"# 簡單的圖像分類器\n",
|
||
"\n",
|
||
"此筆記本將教您如何使用預訓練的神經網絡進行圖像分類。\n",
|
||
"\n",
|
||
"**您將學到:**\n",
|
||
"- 如何載入並使用預訓練模型\n",
|
||
"- 圖像預處理\n",
|
||
"- 對圖像進行預測\n",
|
||
"- 理解信心分數\n",
|
||
"\n",
|
||
"**使用案例:** 識別圖像中的物體(例如「貓」、「狗」、「車」等)\n",
|
||
"\n",
|
||
"---\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 第一步:匯入所需的函式庫\n",
|
||
"\n",
|
||
"讓我們匯入所需的工具。不用擔心,如果你現在還不完全理解這些!\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Core libraries\n",
|
||
"import numpy as np\n",
|
||
"from PIL import Image\n",
|
||
"import requests\n",
|
||
"from io import BytesIO\n",
|
||
"\n",
|
||
"# TensorFlow for deep learning\n",
|
||
"try:\n",
|
||
" import tensorflow as tf\n",
|
||
" from tensorflow.keras.applications import MobileNetV2\n",
|
||
" from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions\n",
|
||
" print(\"✅ TensorFlow loaded successfully!\")\n",
|
||
" print(f\" Version: {tf.__version__}\")\n",
|
||
"except ImportError:\n",
|
||
" print(\"❌ Please install TensorFlow: pip install tensorflow\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 步驟 2:載入預訓練模型\n",
|
||
"\n",
|
||
"我們將使用 **MobileNetV2**,這是一個已經在數百萬張圖片上訓練過的神經網絡。\n",
|
||
"\n",
|
||
"這被稱為 **遷移學習**——使用別人訓練好的模型!\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"print(\"📦 Loading pre-trained MobileNetV2 model...\")\n",
|
||
"print(\" This may take a minute on first run (downloading weights)...\")\n",
|
||
"\n",
|
||
"# Load the model\n",
|
||
"# include_top=True means we use the classification layer\n",
|
||
"# weights='imagenet' means it was trained on ImageNet dataset\n",
|
||
"model = MobileNetV2(weights='imagenet', include_top=True)\n",
|
||
"\n",
|
||
"print(\"✅ Model loaded!\")\n",
|
||
"print(f\" The model can recognize 1000 different object categories\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 第三步:輔助函數\n",
|
||
"\n",
|
||
"讓我們建立一些函數來載入並準備模型所需的圖片。\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def load_image_from_url(url):\n",
|
||
" \"\"\"\n",
|
||
" Load an image from a URL.\n",
|
||
" \n",
|
||
" Args:\n",
|
||
" url: Web address of the image\n",
|
||
" \n",
|
||
" Returns:\n",
|
||
" PIL Image object\n",
|
||
" \"\"\"\n",
|
||
" response = requests.get(url)\n",
|
||
" img = Image.open(BytesIO(response.content))\n",
|
||
" return img\n",
|
||
"\n",
|
||
"\n",
|
||
"def prepare_image(img):\n",
|
||
" \"\"\"\n",
|
||
" Prepare an image for the model.\n",
|
||
" \n",
|
||
" Steps:\n",
|
||
" 1. Resize to 224x224 (model's expected size)\n",
|
||
" 2. Convert to array\n",
|
||
" 3. Add batch dimension\n",
|
||
" 4. Preprocess for MobileNetV2\n",
|
||
" \n",
|
||
" Args:\n",
|
||
" img: PIL Image\n",
|
||
" \n",
|
||
" Returns:\n",
|
||
" Preprocessed image array\n",
|
||
" \"\"\"\n",
|
||
" # Resize to 224x224 pixels\n",
|
||
" img = img.resize((224, 224))\n",
|
||
" \n",
|
||
" # Convert to numpy array\n",
|
||
" img_array = np.array(img)\n",
|
||
" \n",
|
||
" # Add batch dimension (model expects multiple images)\n",
|
||
" img_array = np.expand_dims(img_array, axis=0)\n",
|
||
" \n",
|
||
" # Preprocess for MobileNetV2\n",
|
||
" img_array = preprocess_input(img_array)\n",
|
||
" \n",
|
||
" return img_array\n",
|
||
"\n",
|
||
"\n",
|
||
"def classify_image(img):\n",
|
||
" \"\"\"\n",
|
||
" Classify an image and return top predictions.\n",
|
||
" \n",
|
||
" Args:\n",
|
||
" img: PIL Image\n",
|
||
" \n",
|
||
" Returns:\n",
|
||
" List of (class_name, confidence) tuples\n",
|
||
" \"\"\"\n",
|
||
" # Prepare the image\n",
|
||
" img_array = prepare_image(img)\n",
|
||
" \n",
|
||
" # Make prediction\n",
|
||
" predictions = model.predict(img_array, verbose=0)\n",
|
||
" \n",
|
||
" # Decode predictions to human-readable labels\n",
|
||
" # top=5 means we get the top 5 most likely classes\n",
|
||
" decoded = decode_predictions(predictions, top=5)[0]\n",
|
||
" \n",
|
||
" # Convert to simpler format\n",
|
||
" results = [(label, float(confidence)) for (_, label, confidence) in decoded]\n",
|
||
" \n",
|
||
" return results\n",
|
||
"\n",
|
||
"\n",
|
||
"print(\"✅ Helper functions ready!\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 步驟 4:使用範例圖片進行測試\n",
|
||
"\n",
|
||
"讓我們試著分類一些來自網路的圖片吧!\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Sample images to classify\n",
|
||
"# These are from Unsplash (free stock photos)\n",
|
||
"test_images = [\n",
|
||
" {\n",
|
||
" \"url\": \"https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=400\",\n",
|
||
" \"description\": \"A cat\"\n",
|
||
" },\n",
|
||
" {\n",
|
||
" \"url\": \"https://images.unsplash.com/photo-1552053831-71594a27632d?w=400\",\n",
|
||
" \"description\": \"A dog\"\n",
|
||
" },\n",
|
||
" {\n",
|
||
" \"url\": \"https://images.unsplash.com/photo-1511919884226-fd3cad34687c?w=400\",\n",
|
||
" \"description\": \"A car\"\n",
|
||
" },\n",
|
||
"]\n",
|
||
"\n",
|
||
"print(f\"🧪 Testing on {len(test_images)} images...\")\n",
|
||
"print(\"=\" * 70)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### 將每張圖片分類\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"for i, img_data in enumerate(test_images, 1):\n",
|
||
" print(f\"\\n📸 Image {i}: {img_data['description']}\")\n",
|
||
" print(\"-\" * 70)\n",
|
||
" \n",
|
||
" try:\n",
|
||
" # Load image\n",
|
||
" img = load_image_from_url(img_data['url'])\n",
|
||
" \n",
|
||
" # Display image\n",
|
||
" display(img.resize((200, 200))) # Show smaller version\n",
|
||
" \n",
|
||
" # Classify\n",
|
||
" results = classify_image(img)\n",
|
||
" \n",
|
||
" # Show predictions\n",
|
||
" print(\"\\n🎯 Top 5 Predictions:\")\n",
|
||
" for rank, (label, confidence) in enumerate(results, 1):\n",
|
||
" # Create a visual bar\n",
|
||
" bar_length = int(confidence * 50)\n",
|
||
" bar = \"█\" * bar_length\n",
|
||
" \n",
|
||
" print(f\" {rank}. {label:20s} {confidence*100:5.2f}% {bar}\")\n",
|
||
" \n",
|
||
" except Exception as e:\n",
|
||
" print(f\"❌ Error: {e}\")\n",
|
||
"\n",
|
||
"print(\"\\n\" + \"=\" * 70)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 第五步:嘗試使用自己的圖片!\n",
|
||
"\n",
|
||
"將下面的 URL 替換為您想要分類的任何圖片 URL。\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Try your own image!\n",
|
||
"# Replace this URL with any image URL\n",
|
||
"custom_image_url = \"https://images.unsplash.com/photo-1472491235688-bdc81a63246e?w=400\" # A flower\n",
|
||
"\n",
|
||
"print(\"🖼️ Classifying your custom image...\")\n",
|
||
"print(\"=\" * 70)\n",
|
||
"\n",
|
||
"try:\n",
|
||
" # Load and show image\n",
|
||
" img = load_image_from_url(custom_image_url)\n",
|
||
" display(img.resize((300, 300)))\n",
|
||
" \n",
|
||
" # Classify\n",
|
||
" results = classify_image(img)\n",
|
||
" \n",
|
||
" # Show results\n",
|
||
" print(\"\\n🎯 Top 5 Predictions:\")\n",
|
||
" print(\"-\" * 70)\n",
|
||
" for rank, (label, confidence) in enumerate(results, 1):\n",
|
||
" bar_length = int(confidence * 50)\n",
|
||
" bar = \"█\" * bar_length\n",
|
||
" print(f\" {rank}. {label:20s} {confidence*100:5.2f}% {bar}\")\n",
|
||
" \n",
|
||
" # Highlight top prediction\n",
|
||
" top_label, top_confidence = results[0]\n",
|
||
" print(\"\\n\" + \"=\" * 70)\n",
|
||
" print(f\"\\n🏆 Best guess: {top_label} ({top_confidence*100:.2f}% confident)\")\n",
|
||
" \n",
|
||
"except Exception as e:\n",
|
||
" print(f\"❌ Error: {e}\")\n",
|
||
" print(\" Make sure the URL points to a valid image!\")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 💡 剛剛發生了什麼?\n",
|
||
"\n",
|
||
"1. **我們載入了一個預訓練模型** - MobileNetV2 已經在數百萬張圖片上進行過訓練 \n",
|
||
"2. **我們對圖片進行了預處理** - 將圖片調整大小並格式化以適配模型 \n",
|
||
"3. **模型進行了預測** - 輸出了對 1000 個物件類別的概率 \n",
|
||
"4. **我們解碼了結果** - 將數字轉換為人類可讀的標籤 \n",
|
||
"\n",
|
||
"### 理解信心分數\n",
|
||
"\n",
|
||
"- **90-100%**:非常有信心(幾乎肯定正確) \n",
|
||
"- **70-90%**:有信心(可能正確) \n",
|
||
"- **50-70%**:有些信心(可能正確) \n",
|
||
"- **低於 50%**:信心不足(不確定) \n",
|
||
"\n",
|
||
"### 為什麼預測可能會出錯?\n",
|
||
"\n",
|
||
"- **不尋常的角度或光線** - 模型是在典型照片上訓練的 \n",
|
||
"- **多個物件** - 模型預期只有一個主要物件 \n",
|
||
"- **罕見物件** - 模型只認識 1000 個類別 \n",
|
||
"- **低品質圖片** - 模糊或像素化的圖片更難辨識 \n",
|
||
"\n",
|
||
"---\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## 🚀 下一步\n",
|
||
"\n",
|
||
"1. **嘗試不同的圖片:**\n",
|
||
" - 在 [Unsplash](https://unsplash.com) 上尋找圖片\n",
|
||
" - 右鍵點擊 → 選擇「複製圖片地址」以獲取 URL\n",
|
||
"\n",
|
||
"2. **進行實驗:**\n",
|
||
" - 使用抽象藝術會發生什麼?\n",
|
||
" - 它能否識別不同角度的物體?\n",
|
||
" - 它如何處理多個物體?\n",
|
||
"\n",
|
||
"3. **深入學習:**\n",
|
||
" - 探索 [電腦視覺課程](../lessons/4-ComputerVision/README.md)\n",
|
||
" - 學習如何訓練自己的圖像分類器\n",
|
||
" - 理解 CNN(卷積神經網絡)的工作原理\n",
|
||
"\n",
|
||
"---\n",
|
||
"\n",
|
||
"## 🎉 恭喜!\n",
|
||
"\n",
|
||
"你剛剛使用最先進的神經網絡構建了一個圖像分類器!\n",
|
||
"\n",
|
||
"這種技術同樣應用於:\n",
|
||
"- Google Photos(整理你的照片)\n",
|
||
"- 自駕車(識別物體)\n",
|
||
"- 醫學診斷(分析 X 光片)\n",
|
||
"- 品質控制(檢測缺陷)\n",
|
||
"\n",
|
||
"繼續探索和學習吧!🚀\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"\n---\n\n**免責聲明**: \n本文件已使用 AI 翻譯服務 [Co-op Translator](https://github.com/Azure/co-op-translator) 進行翻譯。儘管我們致力於提供準確的翻譯,請注意自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於關鍵資訊,建議使用專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋不承擔責任。\n"
|
||
]
|
||
}
|
||
],
|
||
"metadata": {
|
||
"kernelspec": {
|
||
"display_name": "Python 3",
|
||
"language": "python",
|
||
"name": "python3"
|
||
},
|
||
"language_info": {
|
||
"codemirror_mode": {
|
||
"name": "ipython",
|
||
"version": 3
|
||
},
|
||
"file_extension": ".py",
|
||
"mimetype": "text/x-python",
|
||
"name": "python",
|
||
"nbconvert_exporter": "python",
|
||
"pygments_lexer": "ipython3",
|
||
"version": "3.8.0"
|
||
},
|
||
"coopTranslator": {
|
||
"original_hash": "1d472141d9df46b751542b3c29f88677",
|
||
"translation_date": "2025-10-03T11:40:39+00:00",
|
||
"source_file": "examples/03-image-classifier.ipynb",
|
||
"language_code": "tw"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 4
|
||
} |