Spaces:
Sleeping
Sleeping
Commit ·
4a1f0f7
1
Parent(s): 5d7a83f
Update models evaluation and rewrite report
Browse files- REPORT.md +19 -4
- app/app.py +14 -13
- app/templates/index.html +2 -2
- notebooks_knowledge&presentation/{alternative_models_reference.md → alternative_Transfer learning models_reference.md} +0 -0
- notebooks_knowledge&presentation/jupyter notebooks/3.Trained_Transfer_Learning_Colab_Models.ipynb +0 -0
- notebooks_knowledge&presentation/jupyter notebooks/Transfer_Learning_Colab_Models.ipynb +23 -15
- outputs/{transfer_learning_history.png → ResNet50_history.png} +2 -2
- outputs/mobilenetv2_history.png +3 -0
- outputs/mobilenetv2_tl_metrics.json +8 -0
- outputs/model_comparison_mobilenetv2_cnn.png +3 -0
- outputs/model_comparison_resnet50_cnn.png +3 -0
- outputs/{model_comparison.png → old_model_comparison(no work with it).png} +0 -0
- outputs/resnet50_tl_metrics.json +8 -0
- outputs/transfer_learning_metrics.json +0 -8
- test_images/test_CNN/airplane.png +2 -2
- test_images/test_CNN/bird.png +2 -2
- test_images/test_CNN/cat 444.png +2 -2
- test_images/test_CNN/cat.png +2 -2
- test_images/test_CNN/dog.png +2 -2
- test_images/test_CNN/frog.png +2 -2
- test_images/test_CNN/horse.png +2 -2
- test_images/test_CNN/{horse 21.png → ship.png} +2 -2
- test_images/test_CNN/truck.png +2 -2
- test_images/test_MobileNetV2/01_easy_automobile.png +2 -2
- test_images/test_MobileNetV2/02_easy_dog.png +2 -2
- test_images/test_MobileNetV2/03_easy_airplane.png +2 -2
- test_images/test_MobileNetV2/04_medium_ship.png +2 -2
- test_images/test_MobileNetV2/05_medium_frog.png +2 -2
- test_images/test_MobileNetV2/06_medium_deer.png +2 -2
- test_images/test_MobileNetV2/07_hard_cat.png +2 -2
- test_images/test_MobileNetV2/08_hard_bird.png +2 -2
- test_images/test_MobileNetV2/09_hard_truck.png +2 -2
- test_images/test_MobileNetV2/10_hard_horse.png +2 -2
REPORT.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
| 9 |
|
| 10 |
## 1. Introduction
|
| 11 |
|
| 12 |
-
|
| 13 |
|
| 14 |
**Models developed:**
|
| 15 |
1. **Custom CNN** — A purpose-built convolutional neural network
|
|
@@ -40,6 +40,9 @@ Applied real-time augmentation during training to reduce overfitting:
|
|
| 40 |
- **Validation:** 5,000 images (10% of train set)
|
| 41 |
- **Test:** 10,000 images (held-out)
|
| 42 |
|
|
|
|
|
|
|
|
|
|
| 43 |
---
|
| 44 |
|
| 45 |
## 3. Model Architectures
|
|
@@ -74,6 +77,9 @@ Input(32×32×3) → UpSampling2D(3×) → MobileNetV2(frozen, ImageNet weights)
|
|
| 74 |
- **Practical**: Faster to train than VGG16 (~138M params) or ResNet50 (~25M params)
|
| 75 |
- **Upscaling**: 32×32 images are upscaled to 96×96 via UpSampling2D to meet MobileNetV2's minimum input requirements
|
| 76 |
|
|
|
|
|
|
|
|
|
|
| 77 |
**Fine-tuning strategy:**
|
| 78 |
1. Phase 1: Train only the classification head (base frozen, lr=0.001)
|
| 79 |
2. Phase 2: Unfreeze top 20 layers of MobileNetV2, retrain with lr=0.0001
|
|
@@ -137,7 +143,12 @@ See `outputs/misclassified_examples.png` for a visual sample of misclassificatio
|
|
| 137 |
|
| 138 |
### 🏆 Winner: Custom CNN (85.3% accuracy)
|
| 139 |
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
## 7. Model Deployment
|
| 143 |
|
|
@@ -150,7 +161,11 @@ The best model is deployed via a **Flask web application**:
|
|
| 150 |
- Supports single and multiple image uploads
|
| 151 |
- Displays top-10 predictions with probability bars
|
| 152 |
- API endpoint at `/api/predict` for programmatic access
|
| 153 |
-
- **Preprocessing:** Uploaded images are resized to 32×32
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
---
|
| 156 |
|
|
@@ -241,7 +256,7 @@ python notebooks/01_data_exploration.py
|
|
| 241 |
# 3. Train the custom CNN
|
| 242 |
python notebooks/02_custom_cnn.py
|
| 243 |
|
| 244 |
-
# 4. Train with transfer learning (
|
| 245 |
python notebooks/03_transfer_learning_cpu.py
|
| 246 |
|
| 247 |
# 5. Compare both models
|
|
|
|
| 9 |
|
| 10 |
## 1. Introduction
|
| 11 |
|
| 12 |
+
In this project, I built and evaluated two deep learning models for classifying images from the CIFAR-10 dataset into 10 categories: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck.
|
| 13 |
|
| 14 |
**Models developed:**
|
| 15 |
1. **Custom CNN** — A purpose-built convolutional neural network
|
|
|
|
| 40 |
- **Validation:** 5,000 images (10% of train set)
|
| 41 |
- **Test:** 10,000 images (held-out)
|
| 42 |
|
| 43 |
+
> **📝 Note on Challenges Encountered - Test Image Resizing:**
|
| 44 |
+
> When preparing custom images from the `test_images/` directory outside the CIFAR-10 dataset, I encountered input shape mismatch errors. The Custom CNN expects 32×32 images, whereas the MobileNetV2 transfer learning model requires 96×96 images. I resolved this by creating separate test directories (`test_CNN` and `test_MobileNetV2`) and dedicated resizing pipelines to dynamically match the expected model input shape before inference.
|
| 45 |
+
|
| 46 |
---
|
| 47 |
|
| 48 |
## 3. Model Architectures
|
|
|
|
| 77 |
- **Practical**: Faster to train than VGG16 (~138M params) or ResNet50 (~25M params)
|
| 78 |
- **Upscaling**: 32×32 images are upscaled to 96×96 via UpSampling2D to meet MobileNetV2's minimum input requirements
|
| 79 |
|
| 80 |
+
> **📝 Note on Challenges Encountered - Model Selection:**
|
| 81 |
+
> I initially evaluated deeper transfer learning models like ResNet50 alongside MobileNetV2. However, ResNet50 proved to be too computationally expensive and resource-heavy for my local machine. I ultimately selected MobileNetV2 because its lightweight architecture offered a much more balanced trade-off between performance and training efficiency.
|
| 82 |
+
|
| 83 |
**Fine-tuning strategy:**
|
| 84 |
1. Phase 1: Train only the classification head (base frozen, lr=0.001)
|
| 85 |
2. Phase 2: Unfreeze top 20 layers of MobileNetV2, retrain with lr=0.0001
|
|
|
|
| 143 |
|
| 144 |
### 🏆 Winner: Custom CNN (85.3% accuracy)
|
| 145 |
|
| 146 |
+
I selected the Custom CNN as the final model for deployment for the following reasons:
|
| 147 |
+
|
| 148 |
+
1. **Accuracy Difference:** While it achieved a respectable test accuracy (85.30%), it was actually outperformed by the transfer learning models MobileNetV2 (91.79%) and ResNet50 (90.63%). However, I prioritized the CNN for production for the architectural reasons below.
|
| 149 |
+
2. **Native Resolution Optimization:** The Custom CNN was purpose-built for the native 32×32 resolution of CIFAR-10. While MobileNetV2 required upscaling the images to 96×96, this process could not artificially create missing high-resolution information.
|
| 150 |
+
3. **Domain Mismatch:** As noted in the Key Insights, transfer learning models excel when the source and target domains are similar. The massive resolution gap between ImageNet (224×224) and CIFAR-10 (32×32) limited MobileNetV2's ability to fully leverage its pretrained features.
|
| 151 |
+
4. **Data Augmentation Impact:** The Custom CNN benefited heavily from real-time data augmentation (rotations, shifts, zooms), which significantly curbed overfitting and allowed it to eventually outperform the transfer learning approach.
|
| 152 |
|
| 153 |
## 7. Model Deployment
|
| 154 |
|
|
|
|
| 161 |
- Supports single and multiple image uploads
|
| 162 |
- Displays top-10 predictions with probability bars
|
| 163 |
- API endpoint at `/api/predict` for programmatic access
|
| 164 |
+
- **Preprocessing:** Uploaded images are resized according to the active model's requirements (32×32 or 96×96) and normalized to [0,1].
|
| 165 |
+
|
| 166 |
+
> **📝 Note on Challenges Encountered - Deployment and Integration:**
|
| 167 |
+
> 1. **Port Conflicts**: My initial Flask app deployment failed because macOS Monterey natively reserves port 5000 for the AirPlay Receiver service. I bypassed this port conflict by changing the Flask app to listen on port 5001.
|
| 168 |
+
> 2. **MobileNetV2 Integration Error**: When integrating the `mobilenetv2_tl.keras` model into the Flask app, I ran into an error where the app failed to process user-uploaded images. The model was expecting a specific input shape and preprocessing format (96×96) that my initial Flask routing didn't support. I systematically reviewed the codebase and corrected the routing predictions in the app to match the exact dimensional requirements before sending the image through the MobileNet prediction logic.
|
| 169 |
|
| 170 |
---
|
| 171 |
|
|
|
|
| 256 |
# 3. Train the custom CNN
|
| 257 |
python notebooks/02_custom_cnn.py
|
| 258 |
|
| 259 |
+
# 4. Train with transfer learning (GPU version — pre-resizes images with cv2 )
|
| 260 |
python notebooks/03_transfer_learning_cpu.py
|
| 261 |
|
| 262 |
# 5. Compare both models
|
app/app.py
CHANGED
|
@@ -16,6 +16,7 @@ import sys
|
|
| 16 |
import json
|
| 17 |
import numpy as np
|
| 18 |
from flask import Flask, request, render_template, jsonify
|
|
|
|
| 19 |
from PIL import Image
|
| 20 |
import io
|
| 21 |
|
|
@@ -32,7 +33,7 @@ from keras.api.utils import img_to_array
|
|
| 32 |
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
|
| 33 |
|
| 34 |
# Try to load the best model (transfer learning first, then custom CNN)
|
| 35 |
-
TRANSFER_MODEL_PATH = os.path.join(PROJECT_ROOT, 'models', '
|
| 36 |
CUSTOM_MODEL_PATH = os.path.join(PROJECT_ROOT, 'models', 'custom_cnn.keras')
|
| 37 |
|
| 38 |
app = Flask(__name__)
|
|
@@ -87,13 +88,7 @@ def preprocess_image(image_bytes, target_size=(32, 32)):
|
|
| 87 |
"""
|
| 88 |
img = Image.open(io.BytesIO(image_bytes)).convert('RGB')
|
| 89 |
|
| 90 |
-
|
| 91 |
-
raise ValueError(
|
| 92 |
-
f"Please check the size of your image! The selected model strictly requires "
|
| 93 |
-
f"an image size of {target_size[0]}x{target_size[1]} pixels, but your image "
|
| 94 |
-
f"is {img.size[0]}x{img.size[1]} pixels. Kindly resize your image or try a different model."
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
img = img.resize(target_size)
|
| 98 |
img_array = img_to_array(img) / 255.0
|
| 99 |
img_array = np.expand_dims(img_array, axis=0)
|
|
@@ -159,6 +154,8 @@ def predict():
|
|
| 159 |
if file.filename == '':
|
| 160 |
continue
|
| 161 |
|
|
|
|
|
|
|
| 162 |
try:
|
| 163 |
image_bytes = file.read()
|
| 164 |
target_size = (96, 96) if model_choice == 'transfer' else (32, 32)
|
|
@@ -166,12 +163,12 @@ def predict():
|
|
| 166 |
predictions = get_predictions(img_array, model_choice, top_n=10)
|
| 167 |
|
| 168 |
all_results.append({
|
| 169 |
-
'filename':
|
| 170 |
'predictions': predictions
|
| 171 |
})
|
| 172 |
except Exception as e:
|
| 173 |
all_results.append({
|
| 174 |
-
'filename':
|
| 175 |
'error': str(e)
|
| 176 |
})
|
| 177 |
|
|
@@ -200,18 +197,21 @@ def api_predict():
|
|
| 200 |
for file in files:
|
| 201 |
if file.filename == '':
|
| 202 |
continue
|
|
|
|
|
|
|
|
|
|
| 203 |
try:
|
| 204 |
image_bytes = file.read()
|
| 205 |
target_size = (96, 96) if model_choice == 'transfer' else (32, 32)
|
| 206 |
img_array = preprocess_image(image_bytes, target_size=target_size)
|
| 207 |
predictions = get_predictions(img_array, model_choice, top_n=10)
|
| 208 |
all_results.append({
|
| 209 |
-
'filename':
|
| 210 |
'predictions': predictions
|
| 211 |
})
|
| 212 |
except Exception as e:
|
| 213 |
all_results.append({
|
| 214 |
-
'filename':
|
| 215 |
'error': str(e)
|
| 216 |
})
|
| 217 |
|
|
@@ -226,4 +226,5 @@ if __name__ == '__main__':
|
|
| 226 |
print(f"\n 🚀 Starting Flask app at http://localhost:{port}")
|
| 227 |
print(f" Available Models: {', '.join([m['name'] for m in models.values()])}")
|
| 228 |
print(f" Classes: {', '.join(CLASS_NAMES)}")
|
| 229 |
-
|
|
|
|
|
|
| 16 |
import json
|
| 17 |
import numpy as np
|
| 18 |
from flask import Flask, request, render_template, jsonify
|
| 19 |
+
from werkzeug.utils import secure_filename
|
| 20 |
from PIL import Image
|
| 21 |
import io
|
| 22 |
|
|
|
|
| 33 |
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
|
| 34 |
|
| 35 |
# Try to load the best model (transfer learning first, then custom CNN)
|
| 36 |
+
TRANSFER_MODEL_PATH = os.path.join(PROJECT_ROOT, 'models', 'mobilenetv2_tl.keras')
|
| 37 |
CUSTOM_MODEL_PATH = os.path.join(PROJECT_ROOT, 'models', 'custom_cnn.keras')
|
| 38 |
|
| 39 |
app = Flask(__name__)
|
|
|
|
| 88 |
"""
|
| 89 |
img = Image.open(io.BytesIO(image_bytes)).convert('RGB')
|
| 90 |
|
| 91 |
+
# Automatically resize the image to the required target size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
img = img.resize(target_size)
|
| 93 |
img_array = img_to_array(img) / 255.0
|
| 94 |
img_array = np.expand_dims(img_array, axis=0)
|
|
|
|
| 154 |
if file.filename == '':
|
| 155 |
continue
|
| 156 |
|
| 157 |
+
safe_name = secure_filename(file.filename) or 'unknown'
|
| 158 |
+
|
| 159 |
try:
|
| 160 |
image_bytes = file.read()
|
| 161 |
target_size = (96, 96) if model_choice == 'transfer' else (32, 32)
|
|
|
|
| 163 |
predictions = get_predictions(img_array, model_choice, top_n=10)
|
| 164 |
|
| 165 |
all_results.append({
|
| 166 |
+
'filename': safe_name,
|
| 167 |
'predictions': predictions
|
| 168 |
})
|
| 169 |
except Exception as e:
|
| 170 |
all_results.append({
|
| 171 |
+
'filename': safe_name,
|
| 172 |
'error': str(e)
|
| 173 |
})
|
| 174 |
|
|
|
|
| 197 |
for file in files:
|
| 198 |
if file.filename == '':
|
| 199 |
continue
|
| 200 |
+
|
| 201 |
+
safe_name = secure_filename(file.filename) or 'unknown'
|
| 202 |
+
|
| 203 |
try:
|
| 204 |
image_bytes = file.read()
|
| 205 |
target_size = (96, 96) if model_choice == 'transfer' else (32, 32)
|
| 206 |
img_array = preprocess_image(image_bytes, target_size=target_size)
|
| 207 |
predictions = get_predictions(img_array, model_choice, top_n=10)
|
| 208 |
all_results.append({
|
| 209 |
+
'filename': safe_name,
|
| 210 |
'predictions': predictions
|
| 211 |
})
|
| 212 |
except Exception as e:
|
| 213 |
all_results.append({
|
| 214 |
+
'filename': safe_name,
|
| 215 |
'error': str(e)
|
| 216 |
})
|
| 217 |
|
|
|
|
| 226 |
print(f"\n 🚀 Starting Flask app at http://localhost:{port}")
|
| 227 |
print(f" Available Models: {', '.join([m['name'] for m in models.values()])}")
|
| 228 |
print(f" Classes: {', '.join(CLASS_NAMES)}")
|
| 229 |
+
debug_mode = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
|
| 230 |
+
app.run(host='0.0.0.0', port=port, debug=debug_mode)
|
app/templates/index.html
CHANGED
|
@@ -171,9 +171,9 @@
|
|
| 171 |
|
| 172 |
function updateSizeInfo() {
|
| 173 |
if (modelChoice.value === 'transfer') {
|
| 174 |
-
modelSizeInfo.innerHTML = "ℹ️ Note:
|
| 175 |
} else {
|
| 176 |
-
modelSizeInfo.innerHTML = "ℹ️ Note:
|
| 177 |
}
|
| 178 |
}
|
| 179 |
|
|
|
|
| 171 |
|
| 172 |
function updateSizeInfo() {
|
| 173 |
if (modelChoice.value === 'transfer') {
|
| 174 |
+
modelSizeInfo.innerHTML = "ℹ️ Note: Images will be automatically resized to <strong>96x96 pixels</strong>.";
|
| 175 |
} else {
|
| 176 |
+
modelSizeInfo.innerHTML = "ℹ️ Note: Images will be automatically resized to <strong>32x32 pixels</strong>.";
|
| 177 |
}
|
| 178 |
}
|
| 179 |
|
notebooks_knowledge&presentation/{alternative_models_reference.md → alternative_Transfer learning models_reference.md}
RENAMED
|
File without changes
|
notebooks_knowledge&presentation/jupyter notebooks/3.Trained_Transfer_Learning_Colab_Models.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
notebooks_knowledge&presentation/jupyter notebooks/Transfer_Learning_Colab_Models.ipynb
CHANGED
|
@@ -5,11 +5,11 @@
|
|
| 5 |
"id": "aeb59df1",
|
| 6 |
"metadata": {},
|
| 7 |
"source": [
|
| 8 |
-
"#
|
| 9 |
"\n",
|
| 10 |
"In this notebook we will apply **Transfer Learning** to classify the CIFAR-10 dataset. We build on the concepts covered in `EXTRA Transfer Learning II.ipynb`.\n",
|
| 11 |
"\n",
|
| 12 |
-
"##
|
| 13 |
"Transfer Learning consists of taking a model that has already been pre-trained on a massive dataset and adapting it for our own problem.\n",
|
| 14 |
"\n",
|
| 15 |
"The process is divided into two main phases:\n",
|
|
@@ -92,7 +92,7 @@
|
|
| 92 |
"metadata": {},
|
| 93 |
"source": [
|
| 94 |
"---\n",
|
| 95 |
-
"##
|
| 96 |
]
|
| 97 |
},
|
| 98 |
{
|
|
@@ -181,12 +181,12 @@
|
|
| 181 |
"# Save plot locally (On Colab it will be in the environment files)\n",
|
| 182 |
"plt.tight_layout()\n",
|
| 183 |
"plt.savefig('mobilenetv2_history.png')\n",
|
| 184 |
-
"print(\"
|
| 185 |
"plt.show()\n",
|
| 186 |
"\n",
|
| 187 |
"# Save the trained model\n",
|
| 188 |
"model_mb.save('mobilenetv2_tl.keras')\n",
|
| 189 |
-
"print(\"
|
| 190 |
]
|
| 191 |
},
|
| 192 |
{
|
|
@@ -195,7 +195,7 @@
|
|
| 195 |
"metadata": {},
|
| 196 |
"source": [
|
| 197 |
"---\n",
|
| 198 |
-
"##
|
| 199 |
]
|
| 200 |
},
|
| 201 |
{
|
|
@@ -283,12 +283,12 @@
|
|
| 283 |
"\n",
|
| 284 |
"plt.tight_layout()\n",
|
| 285 |
"plt.savefig('resnet50_history.png')\n",
|
| 286 |
-
"print(\"
|
| 287 |
"plt.show()\n",
|
| 288 |
"\n",
|
| 289 |
"# Save the trained model\n",
|
| 290 |
"model_rn.save('resnet50_tl.keras')\n",
|
| 291 |
-
"print(\"
|
| 292 |
]
|
| 293 |
},
|
| 294 |
{
|
|
@@ -297,7 +297,7 @@
|
|
| 297 |
"metadata": {},
|
| 298 |
"source": [
|
| 299 |
"---\n",
|
| 300 |
-
"##
|
| 301 |
"\n",
|
| 302 |
"**IMPORTANT NOTE:** Run the cells below **after** training on Google Colab and downloading the models `mobilenetv2_tl.keras` and `resnet50_tl.keras` to your local machine, placing them inside the `models` folder (`/Users/sebastianlopez/Desktop/it-studies/ironhack/week_7/day_2/models`).\n",
|
| 303 |
"\n",
|
|
@@ -350,7 +350,7 @@
|
|
| 350 |
"\n",
|
| 351 |
"def evaluate_and_save(model_path, x_test_prep, model_name, file_suffix):\n",
|
| 352 |
" if not os.path.exists(model_path):\n",
|
| 353 |
-
" print(f\"
|
| 354 |
" return None\n",
|
| 355 |
" \n",
|
| 356 |
" print(f\"\\nLoading and evaluating {model_name}...\")\n",
|
|
@@ -384,7 +384,7 @@
|
|
| 384 |
" json_path = os.path.join(OUTPUT_DIR, f\"{file_suffix}_metrics.json\")\n",
|
| 385 |
" with open(json_path, 'w') as f:\n",
|
| 386 |
" json.dump(metrics, f, indent=2)\n",
|
| 387 |
-
" print(f\"
|
| 388 |
" \n",
|
| 389 |
" return metrics\n",
|
| 390 |
"\n",
|
|
@@ -447,7 +447,7 @@
|
|
| 447 |
" # Save locally\n",
|
| 448 |
" save_path = os.path.join(OUTPUT_DIR, save_filename)\n",
|
| 449 |
" plt.savefig(save_path, bbox_inches='tight')\n",
|
| 450 |
-
" print(f\"
|
| 451 |
" plt.show()\n",
|
| 452 |
"\n",
|
| 453 |
"# Run and plot the first comparison\n",
|
|
@@ -469,15 +469,23 @@
|
|
| 469 |
],
|
| 470 |
"metadata": {
|
| 471 |
"kernelspec": {
|
| 472 |
-
"display_name": "
|
| 473 |
"language": "python",
|
| 474 |
"name": "python3"
|
| 475 |
},
|
| 476 |
"language_info": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
"name": "python",
|
| 478 |
-
"
|
|
|
|
|
|
|
| 479 |
}
|
| 480 |
},
|
| 481 |
"nbformat": 4,
|
| 482 |
"nbformat_minor": 5
|
| 483 |
-
}
|
|
|
|
| 5 |
"id": "aeb59df1",
|
| 6 |
"metadata": {},
|
| 7 |
"source": [
|
| 8 |
+
"# 🧠 Transfer Learning in Deep Learning (MobileNetV2 & ResNet50)\n",
|
| 9 |
"\n",
|
| 10 |
"In this notebook we will apply **Transfer Learning** to classify the CIFAR-10 dataset. We build on the concepts covered in `EXTRA Transfer Learning II.ipynb`.\n",
|
| 11 |
"\n",
|
| 12 |
+
"## 📌 What is Transfer Learning?\n",
|
| 13 |
"Transfer Learning consists of taking a model that has already been pre-trained on a massive dataset and adapting it for our own problem.\n",
|
| 14 |
"\n",
|
| 15 |
"The process is divided into two main phases:\n",
|
|
|
|
| 92 |
"metadata": {},
|
| 93 |
"source": [
|
| 94 |
"---\n",
|
| 95 |
+
"## 🚀 Model 1: MobileNetV2"
|
| 96 |
]
|
| 97 |
},
|
| 98 |
{
|
|
|
|
| 181 |
"# Save plot locally (On Colab it will be in the environment files)\n",
|
| 182 |
"plt.tight_layout()\n",
|
| 183 |
"plt.savefig('mobilenetv2_history.png')\n",
|
| 184 |
+
"print(\"✅ History saved as mobilenetv2_history.png\")\n",
|
| 185 |
"plt.show()\n",
|
| 186 |
"\n",
|
| 187 |
"# Save the trained model\n",
|
| 188 |
"model_mb.save('mobilenetv2_tl.keras')\n",
|
| 189 |
+
"print(\"✅ MobileNetV2 model saved as mobilenetv2_tl.keras\")\n"
|
| 190 |
]
|
| 191 |
},
|
| 192 |
{
|
|
|
|
| 195 |
"metadata": {},
|
| 196 |
"source": [
|
| 197 |
"---\n",
|
| 198 |
+
"## 🚀 Model 2: ResNet50"
|
| 199 |
]
|
| 200 |
},
|
| 201 |
{
|
|
|
|
| 283 |
"\n",
|
| 284 |
"plt.tight_layout()\n",
|
| 285 |
"plt.savefig('resnet50_history.png')\n",
|
| 286 |
+
"print(\"✅ History saved as resnet50_history.png\")\n",
|
| 287 |
"plt.show()\n",
|
| 288 |
"\n",
|
| 289 |
"# Save the trained model\n",
|
| 290 |
"model_rn.save('resnet50_tl.keras')\n",
|
| 291 |
+
"print(\"✅ ResNet50 model saved as resnet50_tl.keras\")\n"
|
| 292 |
]
|
| 293 |
},
|
| 294 |
{
|
|
|
|
| 297 |
"metadata": {},
|
| 298 |
"source": [
|
| 299 |
"---\n",
|
| 300 |
+
"## 📊 Local Evaluation and Model Comparison\n",
|
| 301 |
"\n",
|
| 302 |
"**IMPORTANT NOTE:** Run the cells below **after** training on Google Colab and downloading the models `mobilenetv2_tl.keras` and `resnet50_tl.keras` to your local machine, placing them inside the `models` folder (`/Users/sebastianlopez/Desktop/it-studies/ironhack/week_7/day_2/models`).\n",
|
| 303 |
"\n",
|
|
|
|
| 350 |
"\n",
|
| 351 |
"def evaluate_and_save(model_path, x_test_prep, model_name, file_suffix):\n",
|
| 352 |
" if not os.path.exists(model_path):\n",
|
| 353 |
+
" print(f\"❌ Model not found at: {model_path}\")\n",
|
| 354 |
" return None\n",
|
| 355 |
" \n",
|
| 356 |
" print(f\"\\nLoading and evaluating {model_name}...\")\n",
|
|
|
|
| 384 |
" json_path = os.path.join(OUTPUT_DIR, f\"{file_suffix}_metrics.json\")\n",
|
| 385 |
" with open(json_path, 'w') as f:\n",
|
| 386 |
" json.dump(metrics, f, indent=2)\n",
|
| 387 |
+
" print(f\"✅ Metrics exported to {json_path}\")\n",
|
| 388 |
" \n",
|
| 389 |
" return metrics\n",
|
| 390 |
"\n",
|
|
|
|
| 447 |
" # Save locally\n",
|
| 448 |
" save_path = os.path.join(OUTPUT_DIR, save_filename)\n",
|
| 449 |
" plt.savefig(save_path, bbox_inches='tight')\n",
|
| 450 |
+
" print(f\"✅ Comparison saved at: {save_path}\")\n",
|
| 451 |
" plt.show()\n",
|
| 452 |
"\n",
|
| 453 |
"# Run and plot the first comparison\n",
|
|
|
|
| 469 |
],
|
| 470 |
"metadata": {
|
| 471 |
"kernelspec": {
|
| 472 |
+
"display_name": "ironhack.nn",
|
| 473 |
"language": "python",
|
| 474 |
"name": "python3"
|
| 475 |
},
|
| 476 |
"language_info": {
|
| 477 |
+
"codemirror_mode": {
|
| 478 |
+
"name": "ipython",
|
| 479 |
+
"version": 3
|
| 480 |
+
},
|
| 481 |
+
"file_extension": ".py",
|
| 482 |
+
"mimetype": "text/x-python",
|
| 483 |
"name": "python",
|
| 484 |
+
"nbconvert_exporter": "python",
|
| 485 |
+
"pygments_lexer": "ipython3",
|
| 486 |
+
"version": "3.10.18"
|
| 487 |
}
|
| 488 |
},
|
| 489 |
"nbformat": 4,
|
| 490 |
"nbformat_minor": 5
|
| 491 |
+
}
|
outputs/{transfer_learning_history.png → ResNet50_history.png}
RENAMED
|
File without changes
|
outputs/mobilenetv2_history.png
ADDED
|
Git LFS Details
|
outputs/mobilenetv2_tl_metrics.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "MobileNetV2",
|
| 3 |
+
"loss": 0.2742985486984253,
|
| 4 |
+
"accuracy": 0.917900025844574,
|
| 5 |
+
"precision": 0.9177803489627994,
|
| 6 |
+
"recall": 0.9179,
|
| 7 |
+
"f1_score": 0.9177929630252187
|
| 8 |
+
}
|
outputs/model_comparison_mobilenetv2_cnn.png
ADDED
|
Git LFS Details
|
outputs/model_comparison_resnet50_cnn.png
ADDED
|
Git LFS Details
|
outputs/{model_comparison.png → old_model_comparison(no work with it).png}
RENAMED
|
File without changes
|
outputs/resnet50_tl_metrics.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "ResNet50",
|
| 3 |
+
"loss": 0.3102489113807678,
|
| 4 |
+
"accuracy": 0.9063000082969666,
|
| 5 |
+
"precision": 0.9062836515503816,
|
| 6 |
+
"recall": 0.9063,
|
| 7 |
+
"f1_score": 0.9062575452054132
|
| 8 |
+
}
|
outputs/transfer_learning_metrics.json
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"model": "MobileNetV2 Transfer Learning",
|
| 3 |
-
"loss": 0.5526939630508423,
|
| 4 |
-
"accuracy": 0.8339999914169312,
|
| 5 |
-
"precision": 0.8353133287095834,
|
| 6 |
-
"recall": 0.834,
|
| 7 |
-
"f1_score": 0.8339057892820989
|
| 8 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_images/test_CNN/airplane.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/bird.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/cat 444.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/cat.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/dog.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/frog.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/horse.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_CNN/{horse 21.png → ship.png}
RENAMED
|
File without changes
|
test_images/test_CNN/truck.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/01_easy_automobile.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/02_easy_dog.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/03_easy_airplane.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/04_medium_ship.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/05_medium_frog.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/06_medium_deer.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/07_hard_cat.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/08_hard_bird.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/09_hard_truck.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|
test_images/test_MobileNetV2/10_hard_horse.png
CHANGED
|
Git LFS Details
|
|
Git LFS Details
|