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

397 lines
15 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": [
"## مرحله ۱: وارد کردن کتابخانه‌های مورد نیاز\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": [
"## مرحله ۲: بارگذاری مدل از پیش آموزش‌دیده\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": [
"## مرحله ۴: آزمایش روی تصاویر نمونه\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",
" - کلیک راست کنید → \"Copy image address\" برای دریافت URL\n",
"\n",
"2. **آزمایش کنید:**\n",
" - با هنر انتزاعی چه اتفاقی می‌افتد؟\n",
" - آیا می‌تواند اشیاء را از زوایای مختلف تشخیص دهد؟\n",
" - چگونه با اشیاء متعدد برخورد می‌کند؟\n",
"\n",
"3. **بیشتر یاد بگیرید:**\n",
" - [درس‌های بینایی کامپیوتر](../lessons/4-ComputerVision/README.md) را بررسی کنید\n",
" - یاد بگیرید چگونه یک طبقه‌بند تصویر خودتان را آموزش دهید\n",
" - بفهمید شبکه‌های عصبی پیچشی (CNNs) چگونه کار می‌کنند\n",
"\n",
"---\n",
"\n",
"## 🎉 تبریک!\n",
"\n",
"شما به تازگی یک طبقه‌بند تصویر با استفاده از یک شبکه عصبی پیشرفته ساختید!\n",
"\n",
"همین تکنیک قدرت‌بخش موارد زیر است:\n",
"- Google Photos (سازماندهی عکس‌های شما)\n",
"- خودروهای خودران (تشخیص اشیاء)\n",
"- تشخیص پزشکی (تحلیل تصاویر اشعه ایکس)\n",
"- کنترل کیفیت (شناسایی نقص‌ها)\n",
"\n",
"به یادگیری و کشف ادامه دهید! 🚀\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n---\n\n**سلب مسئولیت**: \nاین سند با استفاده از سرویس ترجمه هوش مصنوعی [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:38:43+00:00",
"source_file": "examples/03-image-classifier.ipynb",
"language_code": "fa"
}
},
"nbformat": 4,
"nbformat_minor": 4
}