AI-For-Beginners/translations/ja/examples/03-image-classifier.ipynb

397 lines
13 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# シンプルな画像分類器\n",
"\n",
"このノートブックでは、事前学習済みのニューラルネットワークを使用して画像を分類する方法を紹介します。\n",
"\n",
"**学べること:**\n",
"- 事前学習済みモデルの読み込みと使用方法\n",
"- 画像の前処理\n",
"- 画像に対する予測の実行\n",
"- 信頼度スコアの理解\n",
"\n",
"**ユースケース:** 画像内のオブジェクトを識別する(例:「猫」、「犬」、「車」など)\n",
"\n",
"---\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ステップ 1: 必要なライブラリをインポートする\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": [
"## ステップ3: ヘルパー関数\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": [
"## ステップ5: 自分の画像を試してみよう!\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",
"- **複数のオブジェクト** - モデルは主なオブジェクト1つを想定しています\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フォト写真の整理\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:41:04+00:00",
"source_file": "examples/03-image-classifier.ipynb",
"language_code": "ja"
}
},
"nbformat": 4,
"nbformat_minor": 4
}