COMPUTER VISION / DEEP LEARNING

Nail Disease Classification

Transfer Learning with EfficientNet-B0

An image classification project using EfficientNet-B0 transfer learning to classify five nail conditions from digital images, with a focus on class imbalance, augmentation, and rigorous model evaluation.

ROLEMachine Learning / Deep Learning
TECHNOLOGYPyTorch · EfficientNet-B0 · Scikit-learn
DOMAINComputer Vision · Medical Imaging
DATASET & TASK2,205 Images · 5 Conditions · 70/15/15 Split
EFFICIENTNET-B0 · 5-CLASS INFERENCE PIPELINE
PyTorch · Torchvision
INPUT TENSOR224 × 224 × 3 RGBImageNet Normalized
BACKBONE MODELEfficientNet-B05.3M Params (Frozen Backbone)
VAL ACCURACY94.26%Early Stopped @ Epoch 67
INPUT
Digital Nail Image224 × 224 × 3
BACKBONE
EfficientNet-B0ImageNet Pretrained
HEAD
Dropout + Linear1280 → 5 Classes
OUTPUT
5-Class SoftmaxArgmax Prediction
SELECT CLASS TO INSPECT METRICS:
Severe Minority (0.95%)21 Total Samples (0.95% of dataset)

Acral Lentiginous Melanoma

PRECISION0.50
RECALL0.67
F1-SCORE0.57

Rare malignant melanoma variant affecting nail beds, palms, or soles. Extremely scarce in public datasets.

Critical clinical risk; false negatives are dangerous, making recall crucial despite tiny sample support.
01 — PROJECT OVERVIEW

Automated Image Classification for Imbalanced Medical Imaging

This project explores automated classification of five nail conditions using a convolutional neural network based on EfficientNet-B0.

THE CORE ML OBJECTIVE

Classification Under Severe Imbalance

The primary challenge is not simply image classification, but handling a highly imbalanced dataset where Acral Lentiginous Melanoma has only 21 images compared with hundreds of samples in the other classes. Standard deep learning classifiers trained on such distributions readily collapse into trivial majority-class predictors, achieving illusory high accuracy while failing entirely on the critical minority condition.

To overcome this challenge, the pipeline combines stratified dataset partitioning, targeted minority data augmentation, pretrained feature extraction via EfficientNet-B0, regularized dropout & early stopping, and multi-metric per-class evaluation.

Stratified Splitting70% Train, 15% Val, 15% Test ensuring identical class ratios across all subsets.
Targeted 10× AugmentationGenerated 10 realistic variations per ALM image, expanding train samples from 21 to 231.
EfficientNet-B0 BackboneLeveraged ImageNet feature transfer with frozen weights and a custom linear head.
Multi-Metric EvaluationAssessed Precision, Recall, F1, Macro-average, Confusion Matrix, and ROC-AUC curves.
02 — DATASET

2,205 Clinical Nail Images & Class Distribution

A comprehensive distribution audit illustrating the substantial disparity between majority dermatological classes and the extreme minority melanoma class.

DISTRIBUTION AUDIT

Class Frequency Disparity

2,205 TOTAL IMAGES
Acral Lentiginous Melanoma21 images (0.95%)
Blue Finger612 images (27.76%)
Healthy Nail343 images (15.56%)
Onychogryphosis600 images (27.21%)
Pitting629 images (28.53%)
Severe Disparity: Acral Lentiginous Melanoma accounts for only 0.95% (21 images) of the entire collection, compared to Pitting with 629 images (28.53%).
TRAINING SET70%
1,543
Images used for model gradient updates
Stratified across all 5 classes
VALIDATION SET15%
331
Images for epoch monitoring & early stopping
94.26% best validation accuracy
TEST SET15%
331
Completely unseen holdout test partition
Evaluated for final generalization metrics
03 — THE CHALLENGE

Key Technical Obstacles in Medical Nail Classification

Beyond standard computer vision benchmarks, clinical nail pathology presents distinct computer vision hurdles.

EXTREME CLASS IMBALANCE
21ALM Images0.95%
vs
629Pitting Images28.53%

The dataset contains a severe imbalance between classes, with Acral Lentiginous Melanoma represented by only 21 images. Standard unweighted optimization would cause the model to ignore this minority class without incurring a significant loss penalty.

01

Class Imbalance

Risk of majority-class bias where a naive classifier achieves 99% overall accuracy while failing 100% of minority melanoma cases.

02

Visual Similarity Between Conditions

Subtle color nuances and overlapping discoloration patterns between subungual hematomas, melanomas, and severe cyanosis.

03

Intra-Class Variation

Significant variations in photographic angles, patient skin tones, lighting conditions, background clutter, and disease stage.

04

Limited Medical Imaging Data

Clinical scarcity and ethical privacy constraints restrict the volume of labeled digital dermatology datasets.

04 — DATA PIPELINE

Preprocessing, Stratified Splitting & Targeted Augmentation

A robust transformation pipeline engineered to preserve label proportions and synthesize controlled variations for the minority class.

01RAW IMAGES2,205 JPEGs
02STRATIFIED SPLIT70 / 15 / 15 Ratio
0310× AUGMENTATIONTargeted on ALM
04224 × 224 TENSORRGB Normalization
05MODEL INPUTEfficientNet-B0
ACTUAL REPOSITORY ASSET

Data Augmentation Visual Inspection (Notebook Cell 10)

Data Augmentation Samples

Visual comparison from the Jupyter notebook showing original sample images alongside 4 randomized augmentations per row.

transforms.RandomRotation(30)Random Rotation ±30°

Simulates varying camera angles and finger orientations during clinical mobile photography.

transforms.RandomHorizontalFlip()Horizontal & Vertical Flips

Provides mirror-invariance so left vs right hand digit anatomy does not bias feature extraction.

transforms.ColorJitter(b=0.2, c=0.2)Color Jitter

Alters brightness and contrast to simulate different hospital lighting and ambient environments.

transforms.RandomResizedCrop(224)Random Resized Crop

Crops patches at scales 0.8–1.0 to enforce scale invariance and focus on localized lesions.

05 — MODEL ARCHITECTURE

EfficientNet-B0 Transfer Learning Architecture

EfficientNet-B0 was selected as a compact transfer-learning backbone that provides a practical balance between model capacity and computational efficiency.

INPUT LAYER
224 × 224 × 3 RGBImageNet Mean/Std Normalized
FEATURE EXTRACTOR BACKBONE (FROZEN)
EfficientNet-B0 Backbone (Pretrained on ImageNet)MBConv (Inverted Residual + Squeeze-and-Excitation Blocks)
16 MBConv BlocksSwish ActivationCompound Scaling (d=1, w=1, r=1)requires_grad = False
SPATIAL POOLING
AdaptiveAvgPool2d(output_size=1)Collapses 7×7 feature map → 1,280 feature vector
CUSTOM CLASSIFIER HEAD (TRAINABLE)
Dropoutnn.Dropout(p=0.2, inplace=True)Prevents co-adaptation and regularizes dense weights
Linearnn.Linear(in_features=1280, out_features=5)Maps 1280 latent representation to 5 condition logits
SOFTMAX OUTPUT
5-Class Probability DistributionAcral Melanoma · Blue Finger · Healthy · Onychogryphosis · Pitting

Architectural Rationale

Pretrained convolutional weights from ImageNet encode rich universal representations (edges, textures, gradients) that transfer effectively to medical pathology. By freezing the convolutional backbone (requires_grad = False) and only fine-tuning the classification head, the network avoids catastrophic forgetting and prevents overfitting on the small dataset.

Parameters~5.3 Million
Input Size224 × 224 px
Backbone FreezeFrozen (Features)
Classifier Dropoutp = 0.2
06 — TRAINING STRATEGY

Optimization & Regularization Protocol

Detailed parameters and stabilization mechanics employed during model convergence.

Optimization Hyperparameters

OptimizerAdam (lr = 0.001)
Loss Criterionnn.CrossEntropyLoss()
Max Epochs100 Epochs
Early StoppingPatience = 10 (Stopped @ Epoch 67)
Best Val Loss0.1851 (Epoch 57) / 0.1942 (Final)

Imbalance & Regularization Defense

10× Targeted OversamplingGenerated 10 augmented instances per original Acral Lentiginous Melanoma image to ensure balanced feature exposure during gradient descent.
Dropout Regularization (p = 0.2)Randomly deactivates 20% of classifier neurons during training passes, preventing dependence on single dominant weights.
Validation Patience MonitorMonitors validation loss each epoch, resetting a 10-step patience counter whenever a new minimum loss is achieved to halt overfitting.
07 — MODEL EVALUATION

Empirical Results & Test Set Performance

Comprehensive multi-metric evaluation across 331 completely unseen test images, utilizing verified plots and classification metrics from the repository.

BEST VAL ACCURACY94.26%Epoch 67 Convergence
TEST ACCURACY94.00%331 Unseen Test Images
MACRO F1-SCORE0.88Unweighted Class Average
WEIGHTED F1-SCORE0.94Support-Weighted Average
TEST SET EVALUATION

Detailed Per-Class Classification Report

N = 331 Holdout Images
CLASS NAMEPRECISIONRECALLF1-SCORETEST SUPPORTPERFORMANCE NOTE
Acral Lentiginous MelanomaMinority
0.500.670.573Minority class with 2 of 3 test cases correctly classified
Healthy Nail
1.000.980.9951Exceptional differentiation from all pathological states
Onychogryphosis
0.970.960.9690Strong identification of severe nail thickening
Blue Finger
0.920.950.9392Robust cyanotic color space recognition
Pitting
0.940.920.9395High accuracy on punctate textural depressions
Overall Accuracy311 / 331 correct0.9433194.00% overall test accuracy
Macro Average0.860.890.88331Unweighted mean reflecting minority class challenge
Weighted Average0.940.940.94331Sample-weighted score across all classes
Training & Validation Loss / Accuracy (67 Epochs)
EfficientNet-B0 Loss & Accuracy Curves
Confusion Matrix (Test Set N=331)
EfficientNet-B0 Confusion Matrix
Multi-Class ROC Curves & Area Under Curve (AUC)
EfficientNet-B0 ROC Curves
08 — WHAT THE MODEL REVEALED

Why 94% Overall Accuracy Is Not the Whole Story

An analytical breakdown of model behavior across majority vs. minority conditions in imbalanced medical imaging.

CRITICAL ML TAKEAWAY

The Disparity Between Overall Accuracy & Minority Recall

While headline metrics indicate a strong 94.00% test accuracy and 0.94 weighted F1, examining unweighted per-class performance reveals that the minority Acral Lentiginous Melanoma class achieved an F1-score of 0.57 (Precision: 0.50, Recall: 0.67).

In clinical settings, false negatives on melanoma represent high diagnostic risk. This experiment underscores why relying solely on accuracy in medical machine learning creates false confidence. Reporting Macro F1 (0.88), per-class confusion matrices, and precision-recall trade-offs is essential for transparent model auditing.

01
Transfer Learning Was Essential

Training from scratch on 2,205 images caused severe feature degradation. ImageNet feature reuse provided the invariant textural descriptors necessary to distinguish nail dystrophies.

02
Augmentation Mitigated Total Collapse

Without 10× targeted augmentation, the model predicted zero ALM cases. Synthetic perturbation expanded the decision boundary sufficiently to achieve 0.67 recall on unseen test data.

03
Textural Boundary Nuances

Healthy nail was effortlessly classified (0.99 F1), whereas micro-indentation conditions (Pitting) exhibited minor confusion with early Onychogryphosis.

09 — END-TO-END WORKFLOW

Complete Machine Learning Lifecycle

A structured 8-stage pipeline from raw image ingestion to analytical metric interpretation.

01PHASE 1

Data Loading

Ingested 2,205 digital nail photographs across 5 clinical directory classes.

02PHASE 2

Imbalance Auditing

Identified severe 0.95% minority proportion in Acral Lentiginous Melanoma (21 images).

03PHASE 3

Stratified Splitting

Partitioned data into 70% Train (1,543), 15% Val (331), and 15% Test (331) sets.

04PHASE 4

Targeted Augmentation

Synthesized 10 variations per ALM image (rotations, flips, color jitter, crops).

05PHASE 5

EfficientNet-B0 Setup

Loaded ImageNet weights, froze convolutional feature extractor, attached custom head.

06PHASE 6

Regularized Training

Trained using Adam optimizer (lr=0.001), CrossEntropyLoss, and Early Stopping @ 67 epochs.

07PHASE 7

Test Set Evaluation

Computed per-class confusion matrix, ROC curves, macro/weighted F1 on 331 test images.

08PHASE 8

Result Interpretation

Analyzed minority recall dynamics and documented clinical trade-offs transparently.

10 — TECHNOLOGY

Tools & Technologies Used

Clean, modern deep learning stack utilized throughout experimentation and model evaluation.

DEEP LEARNING

PyTorch & Torchvision

Model architecture definition, tensor operations, EfficientNet-B0 pretrained weights, and custom DataLoader pipelines.

EVALUATION & METRICS

Scikit-learn

Stratified train/val/test splitting, confusion matrix calculation, classification report generation, and multi-class ROC-AUC computation.

DATA & NUMERICAL

NumPy & Pandas

Dataset distribution indexing, class frequency calculations, and metric array aggregation.

IMAGE PROCESSING

PIL / Pillow

Image loading, color space verification (EnsureRGB), and dynamic image transform pipelines.

DATA VISUALIZATION

Matplotlib & Seaborn

Training loss/accuracy progression plotting, confusion matrix heatmaps, and multi-class ROC curve charting.

CORE TECHNIQUES

Transfer Learning & Augmentation

Pretrained compound scaling backbones, frozen feature extraction, random affine transformations, and early stopping regularization.

11 — WHAT I BUILT

Individual Engineering Contributions

Core technical areas architected and executed in this computer vision case study.

01

Deep Learning Pipeline

Engineered the complete computer vision workflow in PyTorch from raw image loading, preprocessing, and normalization through batch evaluation.

02

Transfer Learning Backbone

Implemented EfficientNet-B0 with ImageNet pretrained weights, freezing feature layers and tuning custom Dropout (0.2) + Linear classifier layers.

03

Class Imbalance Handling

Engineered stratified 70/15/15 data partitioning and targeted 10× augmentation transforms to expand the extreme 21-sample minority class.

04

Multi-Metric Model Evaluation

Evaluated performance using per-class precision, recall, F1-scores, confusion matrices, and ROC-AUC curves on a 331-image holdout test partition.

05

ML Analysis & Insight

Interpreted model behavior beyond headline accuracy, demonstrating the trade-offs of severe imbalance on rare condition detection.

Academic Research & Portfolio Disclaimer

This project is an academic computer vision and deep learning case study exploring transfer learning and class imbalance in medical image classification. It is not a clinically validated diagnostic system and is not intended for clinical diagnosis, patient screening, or treatment guidance. It demonstrates machine learning classification methodology, data augmentation techniques, and empirical evaluation practices.

Inspect the Nail Disease Classification Repository

Explore the complete Jupyter notebook with PyTorch implementation, training curves, confusion matrix generation, and evaluation pipelines.