Upload 13 files
Browse filesFiles changed (14)
- .gitattributes+2
- README.mdAdded
- evaluation_results/classification_report_20260211_155639.txtAdded+70
- evaluation_results/confusion_matrix.pngAdded
- evaluation_results/confusion_matrix_20260211_155639.csvAdded+36
- evaluation_results/confusion_pairs_20260211_155639.csvAdded+3
- evaluation_results/evaluation_metrics_20260211_155639.jsonAdded+21
- evaluation_results/per_class_metrics_20260211_155639.csvAdded+36
- isl_model_advanced.tfliteAdded+3
- landmark_dataset_with_orientation.csvAdded+3
- optimize_sign_assets.pyAdded+113
- prepare_local_sign_assets.pyAdded+119
- test_full_model.pyAdded+586
- train_advanced_model.pyAdded+1093
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textevaluation_results/confusion_matrix.png filter=lfs diff=lfs merge=lfs -textlandmark_dataset_with_orientation.csv filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970======================================================================
KAIROAI MODEL EVALUATION REPORT
Generated: 2026-02-11 15:56:39
======================================================================
OVERALL METRICS
----------------------------------------------------------------------
TRAINING SET:
Accuracy: 99.94%
Precision: 99.94%
Recall: 99.94%
F1-Score: 99.94%
VALIDATION SET:
Accuracy: 99.97%
Precision: 99.97%
Recall: 99.97%
F1-Score: 99.97%
TEST SET:
Accuracy: 99.96%
Precision: 99.96%
Recall: 99.96%
F1-Score: 99.96%
DETAILED CLASSIFICATION REPORT (Test Set)
----------------------------------------------------------------------
precision recall f1-score support
A 1.000 1.000 1.000 240
B 1.000 1.000 1.000 237
C 1.000 1.000 1.000 266
D 1.000 1.000 1.000 240
E 1.000 1.000 1.000 240
F 1.000 1.000 1.000 240
G 1.000 1.000 1.000 240
H 0.992 1.000 0.996 240
I 1.000 1.000 1.000 276
J 1.000 1.000 1.000 240
K 1.000 1.000 1.000 240
L 1.000 1.000 1.000 240
M 1.000 0.992 0.996 240
N 1.000 1.000 1.000 240
O 1.000 1.000 1.000 262
P 1.000 1.000 1.000 226
Q 1.000 1.000 1.000 148
R 1.000 1.000 1.000 240
S 1.000 0.996 0.998 234
T 1.000 1.000 1.000 240
U 1.000 1.000 1.000 240
V 1.000 1.000 1.000 257
W 1.000 1.000 1.000 240
X 1.000 1.000 1.000 240
Y 1.000 1.000 1.000 240
Z 1.000 1.000 1.000 240
1 1.000 1.000 1.000 240
2 1.000 1.000 1.000 240
3 1.000 1.000 1.000 240
4 1.000 1.000 1.000 240
5 1.000 1.000 1.000 240
6 0.996 1.000 0.998 240
7 1.000 1.000 1.000 240
8 1.000 1.000 1.000 240
9 1.000 1.000 1.000 240
accuracy 1.000 8386
macro avg 1.000 1.000 1.000 8386
weighted avg 1.000 1.000 1.000 8386123456789101112131415161718192021222324252627282930313233343536,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9
A,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
B,0,237,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
C,0,0,266,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
D,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
E,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
F,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
G,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
H,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
I,0,0,0,0,0,0,0,0,276,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
J,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
K,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
L,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
M,0,0,0,0,0,0,0,2,0,0,0,0,238,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
N,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
O,0,0,0,0,0,0,0,0,0,0,0,0,0,0,262,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
P,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,226,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Q,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,148,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
R,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
S,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,233,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0
T,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
U,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0
V,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,257,0,0,0,0,0,0,0,0,0,0,0,0,0
W,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0
X,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0
Y,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0
Z,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0
4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0
5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0
6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0
7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0
8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0
9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240123Pair,Total_Count,Combined_Rate
H ↔ M,2,0.8333333333333334
6 ↔ S,1,0.4273504273504274123456789101112131415161718192021{
"timestamp": "20260211_155639",
"training": {
"accuracy": 99.94037637413825,
"precision": 99.94248078852188,
"recall": 99.93982979971115,
"f1_score": 99.94106788684324
},
"validation": {
"accuracy": 99.97018929795797,
"precision": 99.97165518959099,
"recall": 99.97170523138831,
"f1_score": 99.97160969501877
},
"test": {
"accuracy": 99.96422609110422,
"precision": 99.96453188456206,
"recall": 99.96398046398046,
"f1_score": 99.96413197796029
}
}123456789101112131415161718192021222324252627282930313233343536Class,Precision,Recall,F1-Score,Support
A,100.0,100.0,100.0,240
B,100.0,100.0,100.0,237
C,100.0,100.0,100.0,266
D,100.0,100.0,100.0,240
E,100.0,100.0,100.0,240
F,100.0,100.0,100.0,240
G,100.0,100.0,100.0,240
H,99.17355371900827,100.0,99.5850622406639,240
I,100.0,100.0,100.0,276
J,100.0,100.0,100.0,240
K,100.0,100.0,100.0,240
L,100.0,100.0,100.0,240
M,100.0,99.16666666666667,99.581589958159,240
N,100.0,100.0,100.0,240
O,100.0,100.0,100.0,262
P,100.0,100.0,100.0,226
Q,100.0,100.0,100.0,148
R,100.0,100.0,100.0,240
S,100.0,99.57264957264957,99.78586723768737,234
T,100.0,100.0,100.0,240
U,100.0,100.0,100.0,240
V,100.0,100.0,100.0,257
W,100.0,100.0,100.0,240
X,100.0,100.0,100.0,240
Y,100.0,100.0,100.0,240
Z,100.0,100.0,100.0,240
1,100.0,100.0,100.0,240
2,100.0,100.0,100.0,240
3,100.0,100.0,100.0,240
4,100.0,100.0,100.0,240
5,100.0,100.0,100.0,240
6,99.5850622406639,100.0,99.7920997920998,240
7,100.0,100.0,100.0,240
8,100.0,100.0,100.0,240
9,100.0,100.0,100.0,240123version https://git-lfs.github.com/spec/v1oid sha256:914c7609950af5e7cf97da31b9542f3b7b98af9b3b8af3c3e8196cf6cd0cf697size 494372123version https://git-lfs.github.com/spec/v1oid sha256:12d66a842ea865885f43c78f735f63cff65ca1f4d7178ccecca7b9fc8d48b65csize 77254059123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""
Optimize bundled sign images in-place to reduce Flutter app size.
Default behavior:
- Scans assets/signs/**/image.*
- Resizes images to max 960px on the longest side (if larger)
- Converts to RGB palette PNG (256 colors) and saves optimized
- Keeps existing file names and paths unchanged
Usage:
e:/KairoAI/.venv/Scripts/python.exe optimize_sign_assets.py
e:/KairoAI/.venv/Scripts/python.exe optimize_sign_assets.py --max-size 768 --quality 80
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
from PIL import Image
SUPPORTED = {".png", ".jpg", ".jpeg", ".webp"}
ASSET_ROOT = Path(__file__).parent / "assets" / "signs"
@dataclass
class FileStat:
path: Path
before: int
after: int
def iter_image_files(root: Path) -> Iterable[Path]:
if not root.exists():
return []
return sorted(
[p for p in root.rglob("image.*") if p.is_file() and p.suffix.lower() in SUPPORTED]
)
def optimize_file(path: Path, max_size: int, quality: int) -> FileStat:
before = path.stat().st_size
with Image.open(path) as img:
img = img.convert("RGB")
# Resize only when needed, preserving aspect ratio.
longest = max(img.width, img.height)
if longest > max_size:
scale = max_size / float(longest)
new_size = (max(1, int(img.width * scale)), max(1, int(img.height * scale)))
img = img.resize(new_size, Image.Resampling.LANCZOS)
# Keep original extension so existing asset paths remain valid.
ext = path.suffix.lower()
if ext == ".png":
pal = img.quantize(colors=256, method=Image.Quantize.MEDIANCUT)
pal.save(path, format="PNG", optimize=True)
elif ext in {".jpg", ".jpeg"}:
img.save(path, format="JPEG", optimize=True, quality=quality)
elif ext == ".webp":
img.save(path, format="WEBP", quality=quality, method=6)
after = path.stat().st_size
return FileStat(path=path, before=before, after=after)
def fmt_size(num_bytes: int) -> str:
mb = num_bytes / (1024 * 1024)
return f"{mb:.2f} MB"
def main() -> int:
parser = argparse.ArgumentParser(description="Optimize local sign assets in-place")
parser.add_argument("--max-size", type=int, default=960, help="Longest image side after resize")
parser.add_argument("--quality", type=int, default=82, help="JPEG/WEBP quality")
args = parser.parse_args()
files = list(iter_image_files(ASSET_ROOT))
if not files:
print(f"No supported image files found under: {ASSET_ROOT}")
return 1
stats: list[FileStat] = []
for file_path in files:
stat = optimize_file(file_path, max_size=args.max_size, quality=args.quality)
stats.append(stat)
total_before = sum(s.before for s in stats)
total_after = sum(s.after for s in stats)
saved = total_before - total_after
pct = (saved / total_before * 100.0) if total_before else 0.0
print(f"Processed: {len(stats)} file(s)")
print(f"Before: {fmt_size(total_before)}")
print(f"After: {fmt_size(total_after)}")
print(f"Saved: {fmt_size(saved)} ({pct:.1f}%)")
# Print top 5 biggest savings for quick visibility.
top = sorted(stats, key=lambda s: (s.before - s.after), reverse=True)[:5]
print("Top savings:")
for s in top:
delta = s.before - s.after
print(f"- {s.path.as_posix()}: {fmt_size(delta)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""
Copy local sign images into Flutter assets using canonical structure:
assets/signs/{LABEL}/image.{ext}
Default behavior also optimizes copied images in-place to reduce app size.
Usage:
python prepare_local_sign_assets.py "D:\\Downloads\\all the images - 2"
"""
from pathlib import Path
import shutil
import sys
from PIL import Image
SOURCE_DEFAULT = Path(r"D:\Downloads\all the images - 2")
DEST_ROOT = Path(__file__).parent / "assets" / "signs"
SUPPORTED = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
def normalize_label(name: str) -> str:
return name.strip().upper()
def optimize_image(path: Path, max_size: int = 960, quality: int = 82) -> None:
with Image.open(path) as img:
img = img.convert("RGB")
longest = max(img.width, img.height)
if longest > max_size:
scale = max_size / float(longest)
new_size = (max(1, int(img.width * scale)), max(1, int(img.height * scale)))
img = img.resize(new_size, Image.Resampling.LANCZOS)
ext = path.suffix.lower()
if ext == ".png":
pal = img.quantize(colors=256, method=Image.Quantize.MEDIANCUT)
pal.save(path, format="PNG", optimize=True)
elif ext in {".jpg", ".jpeg"}:
img.save(path, format="JPEG", optimize=True, quality=quality)
elif ext == ".webp":
img.save(path, format="WEBP", quality=quality, method=6)
elif ext == ".gif":
img.save(path, format="GIF", optimize=True)
def main() -> int:
source = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE_DEFAULT
if not source.exists() or not source.is_dir():
print(f"Source folder not found: {source}")
return 1
copied = 0
# Mode 1: nested dataset folders (e.g. E:/ISL_Model_Training/Indian/A/*.jpg)
subdirs = [p for p in source.iterdir() if p.is_dir()]
if subdirs:
for subdir in sorted(subdirs, key=lambda p: p.name.lower()):
label = normalize_label(subdir.name)
if not label:
continue
candidates = [
p for p in subdir.iterdir()
if p.is_file() and p.suffix.lower() in SUPPORTED
]
if not candidates:
continue
# Prefer numerically-small file names such as 0.jpg, 1.jpg.
def _sort_key(path: Path) -> tuple[int, str]:
stem = path.stem.strip()
if stem.isdigit():
return (0, f"{int(stem):08d}")
return (1, stem.lower())
candidates.sort(key=_sort_key)
chosen = candidates[0]
dest_dir = DEST_ROOT / label
dest_dir.mkdir(parents=True, exist_ok=True)
dest_file = dest_dir / f"image{chosen.suffix.lower()}"
shutil.copy2(chosen, dest_file)
optimize_image(dest_file)
copied += 1
print(f"{subdir.name}/{chosen.name} -> {dest_file}")
# Mode 2: flat folder of files (legacy behavior).
else:
files = [
p for p in source.iterdir() if p.is_file() and p.suffix.lower() in SUPPORTED
]
files.sort(key=lambda p: p.name.lower())
if not files:
print("No supported image files found.")
return 1
for file_path in files:
label = normalize_label(file_path.stem)
dest_dir = DEST_ROOT / label
dest_dir.mkdir(parents=True, exist_ok=True)
dest_file = dest_dir / f"image{file_path.suffix.lower()}"
shutil.copy2(file_path, dest_file)
optimize_image(dest_file)
copied += 1
print(f"{file_path.name} -> {dest_file}")
if copied == 0:
print("No supported image files found.")
return 1
print(f"Copied {copied} file(s) to {DEST_ROOT}")
return 0
if __name__ == "__main__":
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586"""
================================================================================
TEST ISL MODEL WITH MEDIAPIPE - WEBCAM REAL-TIME INFERENCE
================================================================================
This script tests the trained model (isl_model_full.tflite) using MediaPipe
for hand landmark detection and orientation calculation.
Features:
- Real-time webcam hand detection
- Extracts 130 features (126 landmarks + 4 orientation)
- Runs TFLite inference
- Displays prediction with confidence
Controls:
- Press 'q' to quit
- Press 's' to save screenshot
- Press 'c' to toggle confidence threshold
Author: KairoAI
================================================================================
"""
import cv2
import numpy as np
import mediapipe as mp
import tensorflow as tf
import json
import os
from collections import deque
# ============================================================================
# CONFIGURATION
# ============================================================================
MODEL_PATH = "isl_model_full.tflite"
LABELS_PATH = "labels_full.json"
# Fallback paths if full model not found
FALLBACK_MODEL = "isl_model.tflite"
FALLBACK_LABELS = "labels.json"
# Display settings
CONFIDENCE_THRESHOLD = 0.5
SMOOTHING_WINDOW = 5 # Number of frames to average predictions
SHOW_LANDMARKS = True
SHOW_ORIENTATION = True
# Colors (BGR)
COLOR_PALM = (0, 255, 0) # Green for palm
COLOR_BACK = (0, 165, 255) # Orange for back of hand
COLOR_TEXT = (255, 255, 255) # White
COLOR_BOX = (50, 50, 50) # Dark gray
# Labels (fallback if json not found)
DEFAULT_LABELS = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4',
'5', '6', '7', '8', '9'
]
# ============================================================================
# HAND ORIENTATION CALCULATOR
# ============================================================================
class HandOrientationCalculator:
"""
Calculate whether palm or back of hand is facing the camera.
Uses the cross product of vectors on the hand plane.
"""
# Landmark indices
WRIST = 0
INDEX_MCP = 5
PINKY_MCP = 17
MIDDLE_MCP = 9
@staticmethod
def calculate_orientation(landmarks, handedness):
"""
Calculate hand orientation.
Returns: (is_palm_facing: float, is_left_hand: float)
- is_palm_facing: 1.0 = palm facing camera, 0.0 = back facing camera
- is_left_hand: 1.0 = left hand, 0.0 = right hand
"""
if landmarks is None:
return -1.0, -1.0
# Get key points
wrist = np.array([
landmarks[HandOrientationCalculator.WRIST].x,
landmarks[HandOrientationCalculator.WRIST].y,
landmarks[HandOrientationCalculator.WRIST].z
])
index_mcp = np.array([
landmarks[HandOrientationCalculator.INDEX_MCP].x,
landmarks[HandOrientationCalculator.INDEX_MCP].y,
landmarks[HandOrientationCalculator.INDEX_MCP].z
])
pinky_mcp = np.array([
landmarks[HandOrientationCalculator.PINKY_MCP].x,
landmarks[HandOrientationCalculator.PINKY_MCP].y,
landmarks[HandOrientationCalculator.PINKY_MCP].z
])
# Calculate vectors on the palm plane
v1 = index_mcp - wrist # Wrist to index
v2 = pinky_mcp - wrist # Wrist to pinky
# Cross product gives normal to palm plane
normal = np.cross(v1, v2)
# Z component of normal indicates palm orientation
# Positive = palm facing camera, Negative = back facing
z_component = normal[2]
# Determine handedness
is_left = 1.0 if handedness == "Left" else 0.0
# For left hand, the normal direction is reversed
if is_left:
z_component = -z_component
# Convert to 0/1 (back/palm)
is_palm_facing = 1.0 if z_component > 0 else 0.0
return is_palm_facing, is_left
# ============================================================================
# LANDMARK PROCESSOR
# ============================================================================
class LandmarkProcessor:
"""Process MediaPipe hand landmarks into model input features."""
def __init__(self, input_size=130):
self.input_size = input_size
self.has_orientation = input_size == 130
def normalize_landmarks(self, landmarks):
"""
Normalize landmarks relative to wrist position and hand size.
Returns 63 values (21 landmarks × 3 coords) for one hand.
"""
if landmarks is None:
return [0.0] * 63
coords = []
for lm in landmarks:
coords.extend([lm.x, lm.y, lm.z])
coords = np.array(coords, dtype=np.float32)
# Normalize relative to wrist (first landmark)
wrist = coords[:3].copy()
for i in range(21):
coords[i*3:i*3+3] -= wrist
# Scale by hand size (distance from wrist to middle finger MCP)
middle_mcp = coords[9*3:9*3+3] # Landmark 9
hand_size = np.linalg.norm(middle_mcp)
if hand_size > 0.001:
coords /= hand_size
return coords.tolist()
def process_hands(self, results):
"""
Process MediaPipe results into model input.
Returns: (features, hand_info)
- features: numpy array of shape (input_size,)
- hand_info: dict with orientation info for display
"""
features = [0.0] * self.input_size
hand_info = {
'hand1': None,
'hand2': None,
'hand1_orientation': None,
'hand2_orientation': None
}
if results.multi_hand_landmarks is None:
return np.array(features, dtype=np.float32), hand_info
hands_data = []
for i, (hand_landmarks, handedness) in enumerate(
zip(results.multi_hand_landmarks, results.multi_handedness)
):
hand_label = handedness.classification[0].label
landmarks = hand_landmarks.landmark
# Normalize landmarks
normalized = self.normalize_landmarks(landmarks)
# Calculate orientation
is_palm, is_left = HandOrientationCalculator.calculate_orientation(
landmarks, hand_label
)
hands_data.append({
'landmarks': normalized,
'is_palm': is_palm,
'is_left': is_left,
'label': hand_label,
'raw_landmarks': landmarks
})
# Sort by x position (left to right in image)
if len(hands_data) > 0:
hands_data.sort(
key=lambda h: h['raw_landmarks'][0].x
)
# Fill features for hand 1
if len(hands_data) >= 1:
h1 = hands_data[0]
features[0:63] = h1['landmarks']
hand_info['hand1'] = h1['label']
hand_info['hand1_orientation'] = 'Palm' if h1['is_palm'] == 1.0 else 'Back'
if self.has_orientation:
features[126] = h1['is_palm']
features[127] = h1['is_left']
# Fill features for hand 2
if len(hands_data) >= 2:
h2 = hands_data[1]
features[63:126] = h2['landmarks']
hand_info['hand2'] = h2['label']
hand_info['hand2_orientation'] = 'Palm' if h2['is_palm'] == 1.0 else 'Back'
if self.has_orientation:
features[128] = h2['is_palm']
features[129] = h2['is_left']
elif self.has_orientation:
features[128] = -1.0
features[129] = -1.0
return np.array(features, dtype=np.float32), hand_info
# ============================================================================
# PREDICTION SMOOTHER
# ============================================================================
class PredictionSmoother:
"""Smooth predictions over multiple frames to reduce flickering."""
def __init__(self, window_size=5, num_classes=35):
self.window_size = window_size
self.num_classes = num_classes
self.predictions = deque(maxlen=window_size)
def add_prediction(self, probs):
"""Add a new prediction probability distribution."""
self.predictions.append(probs)
def get_smoothed_prediction(self):
"""Get averaged prediction over the window."""
if len(self.predictions) == 0:
return None, 0.0
avg_probs = np.mean(list(self.predictions), axis=0)
pred_class = np.argmax(avg_probs)
confidence = avg_probs[pred_class]
return pred_class, confidence
def clear(self):
"""Clear prediction history."""
self.predictions.clear()
# ============================================================================
# MAIN TESTER CLASS
# ============================================================================
class ISLModelTester:
"""Main class for testing the ISL model with webcam."""
def __init__(self):
self.model_path = MODEL_PATH
self.labels = DEFAULT_LABELS
self.input_size = 130
# Try to load model and labels
self._load_model()
self._load_labels()
# Initialize components
self.processor = LandmarkProcessor(self.input_size)
self.smoother = PredictionSmoother(SMOOTHING_WINDOW, len(self.labels))
# Initialize MediaPipe
self.mp_hands = mp.solutions.hands
self.mp_draw = mp.solutions.drawing_utils
self.hands = self.mp_hands.Hands(
static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.7,
min_tracking_confidence=0.5
)
# State
self.confidence_threshold = CONFIDENCE_THRESHOLD
self.show_landmarks = SHOW_LANDMARKS
def _load_model(self):
"""Load TFLite model."""
# Try full model first
if os.path.exists(MODEL_PATH):
self.model_path = MODEL_PATH
elif os.path.exists(FALLBACK_MODEL):
print(f"⚠️ {MODEL_PATH} not found, using {FALLBACK_MODEL}")
self.model_path = FALLBACK_MODEL
else:
raise FileNotFoundError(f"No model found! Train the model first.")
print(f"📦 Loading model: {self.model_path}")
self.interpreter = tf.lite.Interpreter(model_path=self.model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
# Get input size from model
self.input_size = self.input_details[0]['shape'][1]
print(f" Input size: {self.input_size}")
def _load_labels(self):
"""Load labels from JSON."""
labels_path = LABELS_PATH if os.path.exists(LABELS_PATH) else FALLBACK_LABELS
if os.path.exists(labels_path):
with open(labels_path, 'r') as f:
config = json.load(f)
self.labels = config.get('labels', DEFAULT_LABELS)
print(f" Labels loaded: {len(self.labels)} classes")
else:
print(f" Using default labels: {len(self.labels)} classes")
def predict(self, features):
"""Run inference on features."""
input_data = features.reshape(1, -1).astype(np.float32)
self.interpreter.set_tensor(self.input_details[0]['index'], input_data)
self.interpreter.invoke()
output = self.interpreter.get_tensor(self.output_details[0]['index'])
return output[0]
def draw_info_box(self, frame, prediction, confidence, hand_info):
"""Draw prediction info box on frame."""
h, w = frame.shape[:2]
# Draw semi-transparent background
overlay = frame.copy()
cv2.rectangle(overlay, (10, 10), (300, 150), COLOR_BOX, -1)
cv2.addWeighted(overlay, 0.7, frame, 0.3, 0, frame)
# Draw prediction
if prediction is not None and confidence >= self.confidence_threshold:
label = self.labels[prediction]
color = (0, 255, 0) if confidence > 0.8 else (0, 255, 255)
cv2.putText(frame, f"Sign: {label}", (20, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, color, 3)
cv2.putText(frame, f"Confidence: {confidence*100:.1f}%", (20, 85),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, COLOR_TEXT, 2)
else:
cv2.putText(frame, "No sign detected", (20, 50),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (100, 100, 100), 2)
# Draw hand info
y_offset = 115
if hand_info['hand1']:
orient = hand_info['hand1_orientation'] or "?"
cv2.putText(frame, f"Hand 1: {hand_info['hand1']} ({orient})",
(20, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT, 1)
y_offset += 20
if hand_info['hand2']:
orient = hand_info['hand2_orientation'] or "?"
cv2.putText(frame, f"Hand 2: {hand_info['hand2']} ({orient})",
(20, y_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLOR_TEXT, 1)
# Draw controls hint
cv2.putText(frame, "Q: Quit | S: Screenshot | L: Toggle landmarks",
(10, h - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (150, 150, 150), 1)
return frame
def draw_landmarks(self, frame, results, hand_info):
"""Draw hand landmarks with orientation-based coloring."""
if results.multi_hand_landmarks is None:
return frame
for i, hand_landmarks in enumerate(results.multi_hand_landmarks):
# Choose color based on orientation
if i == 0 and hand_info['hand1_orientation']:
color = COLOR_PALM if hand_info['hand1_orientation'] == 'Palm' else COLOR_BACK
elif i == 1 and hand_info['hand2_orientation']:
color = COLOR_PALM if hand_info['hand2_orientation'] == 'Palm' else COLOR_BACK
else:
color = (200, 200, 200)
# Draw connections
self.mp_draw.draw_landmarks(
frame, hand_landmarks, self.mp_hands.HAND_CONNECTIONS,
self.mp_draw.DrawingSpec(color=color, thickness=2, circle_radius=2),
self.mp_draw.DrawingSpec(color=color, thickness=2)
)
return frame
def run(self):
"""Main loop for webcam testing."""
print("\n" + "=" * 60)
print("ISL MODEL TEST WITH MEDIAPIPE")
print("=" * 60)
print("\n📷 Opening webcam...")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("❌ Error: Could not open webcam!")
return
# Set camera properties
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 30)
print("✅ Webcam opened successfully")
print("\n🎮 Controls:")
print(" Press 'q' to quit")
print(" Press 's' to save screenshot")
print(" Press 'l' to toggle landmarks")
print(" Press 'c' to cycle confidence threshold")
print(" Press 'r' to reset smoother")
print("\n" + "=" * 60 + "\n")
screenshot_count = 0
while True:
ret, frame = cap.read()
if not ret:
print("❌ Error reading frame")
break
# Flip for mirror effect
frame = cv2.flip(frame, 1)
# Convert to RGB for MediaPipe
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Process with MediaPipe
results = self.hands.process(rgb_frame)
# Extract features
features, hand_info = self.processor.process_hands(results)
# Run inference if hand detected
prediction = None
confidence = 0.0
if hand_info['hand1'] is not None:
probs = self.predict(features)
self.smoother.add_prediction(probs)
prediction, confidence = self.smoother.get_smoothed_prediction()
else:
self.smoother.clear()
# Draw landmarks if enabled
if self.show_landmarks:
frame = self.draw_landmarks(frame, results, hand_info)
# Draw info box
frame = self.draw_info_box(frame, prediction, confidence, hand_info)
# Show frame
cv2.imshow('ISL Model Test', frame)
# Handle key presses
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
print("\n👋 Exiting...")
break
elif key == ord('s'):
filename = f"screenshot_{screenshot_count}.png"
cv2.imwrite(filename, frame)
print(f"📸 Screenshot saved: {filename}")
screenshot_count += 1
elif key == ord('l'):
self.show_landmarks = not self.show_landmarks
print(f"🎯 Landmarks: {'ON' if self.show_landmarks else 'OFF'}")
elif key == ord('c'):
# Cycle threshold: 0.5 -> 0.7 -> 0.9 -> 0.3 -> 0.5
thresholds = [0.3, 0.5, 0.7, 0.9]
idx = thresholds.index(self.confidence_threshold) if self.confidence_threshold in thresholds else 0
self.confidence_threshold = thresholds[(idx + 1) % len(thresholds)]
print(f"📊 Confidence threshold: {self.confidence_threshold}")
elif key == ord('r'):
self.smoother.clear()
print("🔄 Smoother reset")
cap.release()
cv2.destroyAllWindows()
print("\n✅ Test complete!")
# ============================================================================
# BATCH TEST MODE
# ============================================================================
def test_on_images(image_folder):
"""Test model on a folder of images."""
print("\n" + "=" * 60)
print("BATCH IMAGE TEST")
print("=" * 60)
tester = ISLModelTester()
results = []
for filename in os.listdir(image_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
filepath = os.path.join(image_folder, filename)
# Load image
frame = cv2.imread(filepath)
if frame is None:
continue
# Process
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
mp_results = tester.hands.process(rgb_frame)
features, hand_info = tester.processor.process_hands(mp_results)
if hand_info['hand1'] is not None:
probs = tester.predict(features)
pred_class = np.argmax(probs)
confidence = probs[pred_class]
results.append({
'file': filename,
'prediction': tester.labels[pred_class],
'confidence': confidence
})
print(f" {filename}: {tester.labels[pred_class]} ({confidence*100:.1f}%)")
else:
print(f" {filename}: No hand detected")
return results
# ============================================================================
# MAIN
# ============================================================================
def main():
import sys
if len(sys.argv) > 1:
# Batch mode on folder
folder = sys.argv[1]
if os.path.isdir(folder):
test_on_images(folder)
else:
print(f"❌ Folder not found: {folder}")
else:
# Webcam mode
tester = ISLModelTester()
tester.run()
if __name__ == "__main__":
main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093"""
================================================================================
ADVANCED ISL MODEL TRAINING - MAXIMUM ACCURACY
================================================================================
State-of-the-art techniques for achieving 9-10/10 accuracy:
1. Attention Mechanism - Focus on important landmarks
2. Focal Loss - Better handling of hard examples
3. Advanced Augmentation - Realistic variations
4. Residual Connections - Better gradient flow
5. Class Balancing - Handle imbalanced classes
6. Hard Example Mining - Focus on confused pairs
7. Multi-Scale Features - Capture different patterns
8. Test-Time Augmentation (TTA) - Better inference
9. Ensemble Ready - Can combine multiple models
10. Gradual Unfreezing with Warmup
Target: 99.5%+ validation accuracy with real-world robustness
Author: KairoAI
================================================================================
"""
import os
import numpy as np
import json
import csv
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, regularizers, Model
from tensorflow.keras.callbacks import Callback
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.utils.class_weight import compute_class_weight
from sklearn.metrics import classification_report, confusion_matrix
import math
# Suppress warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# ============================================================================
# CONFIGURATION
# ============================================================================
INPUT_CSV = "landmark_dataset_with_orientation.csv"
OUTPUT_MODEL = "isl_model_advanced.tflite"
OUTPUT_H5 = "isl_model_advanced.h5"
OUTPUT_LABELS = "labels_advanced.json"
NUM_CLASSES = 35
# Training config
EPOCHS = 200
BATCH_SIZE = 64
VALIDATION_SPLIT = 0.15 # Smaller val split = more training data
# Advanced config
USE_FOCAL_LOSS = True
FOCAL_ALPHA = 0.25
FOCAL_GAMMA = 2.0
USE_CLASS_WEIGHTS = True
USE_ATTENTION = True
USE_RESIDUAL = True
# Augmentation strength
AUG_NOISE_STD = 0.03
AUG_SCALE_RANGE = (0.85, 1.15)
AUG_ROTATION_RANGE = 20 # degrees
AUG_SHIFT_RANGE = 0.1
MIXUP_ALPHA = 0.3
CUTMIX_ALPHA = 0.3
# Learning rate
INITIAL_LR = 0.002
MIN_LR = 1e-7
WARMUP_EPOCHS = 10
LABELS = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4',
'5', '6', '7', '8', '9'
]
# Commonly confused pairs - will get extra training attention
CONFUSED_PAIRS = [
('V', '2'), ('K', 'V'), ('U', 'V'), ('M', 'N'), ('5', 'H'),
('G', 'H'), ('I', 'J'), ('1', 'D'), ('6', 'W'), ('3', 'W'),
('B', 'E'), ('A', 'S'), ('O', 'C')
]
# ============================================================================
# FOCAL LOSS - Better for hard examples
# ============================================================================
class FocalLoss(keras.losses.Loss):
"""
Focal Loss focuses training on hard examples.
Reduces loss contribution from easy examples.
"""
def __init__(self, alpha=0.25, gamma=2.0, **kwargs):
super().__init__(**kwargs)
self.alpha = alpha
self.gamma = gamma
def call(self, y_true, y_pred):
# Clip predictions to prevent log(0)
y_pred = tf.clip_by_value(y_pred, 1e-7, 1 - 1e-7)
# Calculate focal loss
cross_entropy = -y_true * tf.math.log(y_pred)
weight = self.alpha * y_true * tf.pow(1 - y_pred, self.gamma)
focal_loss = weight * cross_entropy
return tf.reduce_sum(focal_loss, axis=-1)
def get_config(self):
config = super().get_config()
config.update({'alpha': self.alpha, 'gamma': self.gamma})
return config
# ============================================================================
# ATTENTION LAYER - Focus on important features
# ============================================================================
class SelfAttention(layers.Layer):
"""Self-attention layer to focus on important landmarks."""
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
def build(self, input_shape):
self.W_q = self.add_weight(
shape=(input_shape[-1], self.units),
initializer='glorot_uniform',
trainable=True,
name='query_weight'
)
self.W_k = self.add_weight(
shape=(input_shape[-1], self.units),
initializer='glorot_uniform',
trainable=True,
name='key_weight'
)
self.W_v = self.add_weight(
shape=(input_shape[-1], self.units),
initializer='glorot_uniform',
trainable=True,
name='value_weight'
)
def call(self, x):
q = tf.matmul(x, self.W_q)
k = tf.matmul(x, self.W_k)
v = tf.matmul(x, self.W_v)
# Scaled dot-product attention
d_k = tf.cast(tf.shape(k)[-1], tf.float32)
attention_scores = tf.matmul(q, k, transpose_b=True) / tf.sqrt(d_k)
attention_weights = tf.nn.softmax(attention_scores, axis=-1)
output = tf.matmul(attention_weights, v)
return output
def get_config(self):
config = super().get_config()
config.update({'units': self.units})
return config
class ChannelAttention(layers.Layer):
"""Channel attention - learns which features are important."""
def __init__(self, reduction_ratio=8, **kwargs):
super().__init__(**kwargs)
self.reduction_ratio = reduction_ratio
def build(self, input_shape):
channels = input_shape[-1]
self.dense1 = layers.Dense(channels // self.reduction_ratio, activation='relu')
self.dense2 = layers.Dense(channels, activation='sigmoid')
def call(self, x):
# Global average pooling
avg_pool = tf.reduce_mean(x, axis=-1, keepdims=True)
max_pool = tf.reduce_max(x, axis=-1, keepdims=True)
# Shared MLP
avg_out = self.dense2(self.dense1(avg_pool))
max_out = self.dense2(self.dense1(max_pool))
attention = avg_out + max_out
return x * attention
def get_config(self):
config = super().get_config()
config.update({'reduction_ratio': self.reduction_ratio})
return config
# ============================================================================
# RESIDUAL BLOCK
# ============================================================================
class ResidualBlock(layers.Layer):
"""Residual block with skip connection for better gradient flow."""
def __init__(self, units, dropout_rate=0.3, l2_reg=0.001, **kwargs):
super().__init__(**kwargs)
self.units = units
self.dropout_rate = dropout_rate
self.l2_reg = l2_reg
def build(self, input_shape):
self.dense1 = layers.Dense(
self.units,
kernel_regularizer=regularizers.l2(self.l2_reg)
)
self.bn1 = layers.BatchNormalization()
self.dropout1 = layers.Dropout(self.dropout_rate)
self.dense2 = layers.Dense(
self.units,
kernel_regularizer=regularizers.l2(self.l2_reg)
)
self.bn2 = layers.BatchNormalization()
self.dropout2 = layers.Dropout(self.dropout_rate)
# Skip connection projection if dimensions don't match
if input_shape[-1] != self.units:
self.skip_proj = layers.Dense(self.units, use_bias=False)
else:
self.skip_proj = None
def call(self, x, training=False):
# Main path
h = self.dense1(x)
h = self.bn1(h, training=training)
h = tf.nn.gelu(h) # GELU activation (better than ReLU)
h = self.dropout1(h, training=training)
h = self.dense2(h)
h = self.bn2(h, training=training)
# Skip connection
if self.skip_proj is not None:
x = self.skip_proj(x)
# Add and activate
out = tf.nn.gelu(h + x)
out = self.dropout2(out, training=training)
return out
def get_config(self):
config = super().get_config()
config.update({
'units': self.units,
'dropout_rate': self.dropout_rate,
'l2_reg': self.l2_reg
})
return config
# ============================================================================
# ADVANCED DATA AUGMENTATION
# ============================================================================
class AdvancedAugmenter:
"""Advanced augmentation for landmark data."""
def __init__(self, noise_std=0.03, scale_range=(0.85, 1.15),
rotation_range=20, shift_range=0.1):
self.noise_std = noise_std
self.scale_range = scale_range
self.rotation_range = rotation_range
self.shift_range = shift_range
def add_noise(self, X):
"""Add Gaussian noise."""
noise = np.random.normal(0, self.noise_std, X.shape)
# Don't add noise to orientation features
if X.shape[1] > 126:
noise[:, 126:] = 0
return X + noise
def random_scale(self, X):
"""Random scaling of landmarks."""
scale = np.random.uniform(*self.scale_range, size=(len(X), 1))
X_scaled = X.copy()
X_scaled[:, :126] *= scale
return X_scaled
def random_shift(self, X):
"""Random translation of landmarks."""
shift = np.random.uniform(-self.shift_range, self.shift_range,
size=(len(X), 3))
X_shifted = X.copy()
# Apply same shift to all landmarks (x, y, z)
for i in range(21):
X_shifted[:, i*3:(i+1)*3] += shift
# Second hand if present
for i in range(21, 42):
X_shifted[:, i*3:(i+1)*3] += shift
return X_shifted
def random_rotation_2d(self, X):
"""Random 2D rotation around z-axis."""
angles = np.random.uniform(-self.rotation_range, self.rotation_range,
size=len(X)) * np.pi / 180
X_rotated = X.copy()
for i, angle in enumerate(angles):
cos_a, sin_a = np.cos(angle), np.sin(angle)
# Rotate each landmark (x, y only)
for j in range(42): # 21 landmarks × 2 hands
if j * 3 + 2 < 126:
x = X_rotated[i, j*3]
y = X_rotated[i, j*3 + 1]
X_rotated[i, j*3] = x * cos_a - y * sin_a
X_rotated[i, j*3 + 1] = x * sin_a + y * cos_a
return X_rotated
def random_mirror(self, X):
"""Randomly mirror hands (swap left/right)."""
X_mirrored = X.copy()
mask = np.random.random(len(X)) < 0.3 # 30% chance
for i in np.where(mask)[0]:
# Mirror x coordinates
for j in range(42):
if j * 3 < 126:
X_mirrored[i, j*3] = -X_mirrored[i, j*3]
# Swap hand orientation if present
if X.shape[1] > 126:
# Swap is_left flags
X_mirrored[i, 127] = 1.0 - X_mirrored[i, 127] if X_mirrored[i, 127] >= 0 else -1.0
X_mirrored[i, 129] = 1.0 - X_mirrored[i, 129] if X_mirrored[i, 129] >= 0 else -1.0
return X_mirrored
def random_finger_jitter(self, X):
"""Add extra jitter to finger tips (most variable landmarks)."""
X_jittered = X.copy()
finger_tips = [4, 8, 12, 16, 20] # Thumb, index, middle, ring, pinky tips
for tip in finger_tips:
jitter = np.random.normal(0, self.noise_std * 2, (len(X), 3))
X_jittered[:, tip*3:(tip+1)*3] += jitter
# Second hand
if (tip + 21) * 3 + 3 <= 126:
X_jittered[:, (tip+21)*3:(tip+22)*3] += jitter
return X_jittered
def augment_batch(self, X, p=0.5):
"""Apply random augmentations to batch."""
X_aug = X.copy()
# Apply each augmentation with probability p
if np.random.random() < p:
X_aug = self.add_noise(X_aug)
if np.random.random() < p * 0.7:
X_aug = self.random_scale(X_aug)
if np.random.random() < p * 0.5:
X_aug = self.random_rotation_2d(X_aug)
if np.random.random() < p * 0.3:
X_aug = self.random_shift(X_aug)
if np.random.random() < p * 0.3:
X_aug = self.random_finger_jitter(X_aug)
if np.random.random() < p * 0.2:
X_aug = self.random_mirror(X_aug)
return X_aug
# ============================================================================
# MIXUP AND CUTMIX
# ============================================================================
def mixup(X, y, alpha=0.3):
"""Mixup augmentation."""
if alpha <= 0:
return X, y
batch_size = len(X)
lam = np.random.beta(alpha, alpha)
indices = np.random.permutation(batch_size)
X_mixed = lam * X + (1 - lam) * X[indices]
y_mixed = lam * y + (1 - lam) * y[indices]
return X_mixed, y_mixed
def cutmix(X, y, alpha=0.3):
"""CutMix augmentation - mix portions of features."""
if alpha <= 0:
return X, y
batch_size = len(X)
lam = np.random.beta(alpha, alpha)
indices = np.random.permutation(batch_size)
# Determine cut size
feature_size = X.shape[1]
cut_size = int(feature_size * (1 - lam))
cut_start = np.random.randint(0, feature_size - cut_size + 1)
X_mixed = X.copy()
X_mixed[:, cut_start:cut_start+cut_size] = X[indices, cut_start:cut_start+cut_size]
# Adjust lambda based on actual cut
lam = 1 - cut_size / feature_size
y_mixed = lam * y + (1 - lam) * y[indices]
return X_mixed, y_mixed
# ============================================================================
# ADVANCED DATA GENERATOR
# ============================================================================
class AdvancedDataGenerator(keras.utils.Sequence):
"""Advanced data generator with multiple augmentation techniques."""
def __init__(self, X, y, batch_size, augmenter, num_classes,
use_mixup=True, use_cutmix=True, shuffle=True,
hard_example_indices=None, hard_example_ratio=0.3):
self.X = X
self.y = y
self.batch_size = batch_size
self.augmenter = augmenter
self.num_classes = num_classes
self.use_mixup = use_mixup
self.use_cutmix = use_cutmix
self.shuffle = shuffle
self.hard_example_indices = hard_example_indices
self.hard_example_ratio = hard_example_ratio
self.indices = np.arange(len(X))
self.on_epoch_end()
def __len__(self):
return int(np.ceil(len(self.X) / self.batch_size))
def __getitem__(self, idx):
batch_indices = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
# Optionally include hard examples
if self.hard_example_indices is not None and len(self.hard_example_indices) > 0:
n_hard = int(len(batch_indices) * self.hard_example_ratio)
hard_sample = np.random.choice(self.hard_example_indices,
size=min(n_hard, len(self.hard_example_indices)),
replace=False)
batch_indices = np.concatenate([batch_indices[:-n_hard], hard_sample])
X_batch = self.X[batch_indices].copy()
y_batch = self.y[batch_indices].copy()
# Apply augmentation
X_batch = self.augmenter.augment_batch(X_batch, p=0.7)
# Convert to one-hot
y_one_hot = keras.utils.to_categorical(y_batch, self.num_classes)
# Apply mixup or cutmix (not both at same time)
if self.use_mixup and self.use_cutmix:
if np.random.random() < 0.5:
X_batch, y_one_hot = mixup(X_batch, y_one_hot, MIXUP_ALPHA)
else:
X_batch, y_one_hot = cutmix(X_batch, y_one_hot, CUTMIX_ALPHA)
elif self.use_mixup:
X_batch, y_one_hot = mixup(X_batch, y_one_hot, MIXUP_ALPHA)
elif self.use_cutmix:
X_batch, y_one_hot = cutmix(X_batch, y_one_hot, CUTMIX_ALPHA)
return X_batch.astype(np.float32), y_one_hot.astype(np.float32)
def on_epoch_end(self):
if self.shuffle:
np.random.shuffle(self.indices)
# ============================================================================
# CREATE ADVANCED MODEL
# ============================================================================
def create_advanced_model(input_size):
"""
Create an advanced model with attention and residual connections.
"""
print("\n" + "=" * 60)
print("CREATING ADVANCED MODEL")
print("=" * 60)
l2_reg = regularizers.l2(0.001)
# Input
inputs = layers.Input(shape=(input_size,), name='input')
# Split landmarks and orientation
landmarks = layers.Lambda(lambda x: x[:, :126], name='landmarks')(inputs)
if input_size > 126:
orientation = layers.Lambda(lambda x: x[:, 126:], name='orientation')(inputs)
# ===== LANDMARK PROCESSING PATH =====
# Reshape for multi-scale processing (treat as 42 landmarks × 3 coords)
lm_reshaped = layers.Reshape((42, 3))(landmarks)
# Multi-scale feature extraction
# Scale 1: Per-landmark features
scale1 = layers.Dense(16, activation='gelu', kernel_regularizer=l2_reg)(lm_reshaped)
scale1 = layers.Flatten()(scale1)
# Scale 2: Landmark group features (fingers)
scale2 = layers.Conv1D(32, kernel_size=5, activation='gelu', padding='same',
kernel_regularizer=l2_reg)(lm_reshaped)
scale2 = layers.GlobalAveragePooling1D()(scale2)
# Scale 3: Global hand features
scale3 = layers.Dense(64, activation='gelu', kernel_regularizer=l2_reg)(landmarks)
# Combine scales
lm_features = layers.Concatenate()([scale1, scale2, scale3])
lm_features = layers.BatchNormalization()(lm_features)
lm_features = layers.Dropout(0.3)(lm_features)
# Channel attention
if USE_ATTENTION:
lm_features = ChannelAttention(reduction_ratio=4)(lm_features)
# Residual blocks
if USE_RESIDUAL:
x = ResidualBlock(256, dropout_rate=0.4, l2_reg=0.001)(lm_features)
x = ResidualBlock(128, dropout_rate=0.3, l2_reg=0.001)(x)
x = ResidualBlock(64, dropout_rate=0.3, l2_reg=0.001)(x)
else:
x = layers.Dense(256, activation='gelu', kernel_regularizer=l2_reg)(lm_features)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.4)(x)
x = layers.Dense(128, activation='gelu', kernel_regularizer=l2_reg)(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.3)(x)
x = layers.Dense(64, activation='gelu', kernel_regularizer=l2_reg)(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.3)(x)
# ===== ORIENTATION PATH (if available) =====
if input_size > 126:
orient_x = layers.Dense(16, activation='gelu', kernel_regularizer=l2_reg)(orientation)
orient_x = layers.BatchNormalization()(orient_x)
orient_x = layers.Dense(8, activation='gelu', kernel_regularizer=l2_reg)(orient_x)
# Combine with main path
x = layers.Concatenate()([x, orient_x])
# ===== CLASSIFICATION HEAD =====
x = layers.Dense(64, activation='gelu', kernel_regularizer=l2_reg)(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.2)(x)
x = layers.Dense(32, activation='gelu', kernel_regularizer=l2_reg)(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.2)(x)
# Output
outputs = layers.Dense(NUM_CLASSES, activation='softmax', name='output')(x)
model = Model(inputs=inputs, outputs=outputs)
# Compile with focal loss or standard loss
if USE_FOCAL_LOSS:
loss = FocalLoss(alpha=FOCAL_ALPHA, gamma=FOCAL_GAMMA)
else:
loss = keras.losses.CategoricalCrossentropy(label_smoothing=0.1)
# Use Adam with weight decay (compatible with TF 2.x)
try:
# TensorFlow 2.11+
optimizer = keras.optimizers.Adam(
learning_rate=INITIAL_LR,
)
except:
optimizer = keras.optimizers.Adam(learning_rate=INITIAL_LR)
model.compile(
optimizer=optimizer,
loss=loss,
metrics=['accuracy']
)
print(f"\n📐 Model Summary:")
model.summary()
print(f"\n Total parameters: {model.count_params():,}")
print(f" Using Focal Loss: {USE_FOCAL_LOSS}")
print(f" Using Attention: {USE_ATTENTION}")
print(f" Using Residual: {USE_RESIDUAL}")
return model
# ============================================================================
# LEARNING RATE SCHEDULE
# ============================================================================
class WarmupCosineDecay(Callback):
"""Warmup + Cosine decay with restarts."""
def __init__(self, max_lr, min_lr, warmup_epochs, total_epochs, restarts=2):
super().__init__()
self.max_lr = max_lr
self.min_lr = min_lr
self.warmup_epochs = warmup_epochs
self.total_epochs = total_epochs
self.restarts = restarts
self.cycle_length = (total_epochs - warmup_epochs) // (restarts + 1)
def on_epoch_begin(self, epoch, logs=None):
if epoch < self.warmup_epochs:
lr = self.max_lr * (epoch + 1) / self.warmup_epochs
else:
epoch_in_cycle = (epoch - self.warmup_epochs) % self.cycle_length
# Cosine decay within cycle
lr = self.min_lr + 0.5 * (self.max_lr - self.min_lr) * \
(1 + math.cos(math.pi * epoch_in_cycle / self.cycle_length))
# Reduce max_lr after each restart
cycle_num = (epoch - self.warmup_epochs) // self.cycle_length
lr *= (0.8 ** cycle_num)
keras.backend.set_value(self.model.optimizer.learning_rate, lr)
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
logs['lr'] = float(keras.backend.get_value(self.model.optimizer.learning_rate))
# ============================================================================
# LOAD DATA
# ============================================================================
def load_data():
"""Load and prepare data."""
print("\n" + "=" * 60)
print("LOADING DATA")
print("=" * 60)
if not os.path.exists(INPUT_CSV):
print(f"❌ ERROR: {INPUT_CSV} not found!")
return None, None, None
X, y = [], []
with open(INPUT_CSV, 'r') as f:
reader = csv.reader(f)
next(reader) # Skip header
for row in reader:
features = [float(val) for val in row[:-1]]
label_str = row[-1]
if label_str in LABELS:
X.append(features)
y.append(LABELS.index(label_str))
X = np.array(X, dtype=np.float32)
y = np.array(y, dtype=np.int32)
print(f"✅ Loaded {len(X)} samples")
print(f" Feature shape: {X.shape}")
# Find hard examples (confused pairs)
hard_indices = []
for sign_a, sign_b in CONFUSED_PAIRS:
if sign_a in LABELS and sign_b in LABELS:
idx_a, idx_b = LABELS.index(sign_a), LABELS.index(sign_b)
hard_indices.extend(np.where((y == idx_a) | (y == idx_b))[0].tolist())
hard_indices = list(set(hard_indices))
print(f" Hard examples (confused pairs): {len(hard_indices)}")
# Class distribution
unique, counts = np.unique(y, return_counts=True)
print(f"\n📊 Class distribution:")
min_count = min(counts)
max_count = max(counts)
print(f" Min samples: {min_count} ({LABELS[unique[np.argmin(counts)]]})")
print(f" Max samples: {max_count} ({LABELS[unique[np.argmax(counts)]]})")
print(f" Imbalance ratio: {max_count/min_count:.2f}")
return X, y, hard_indices
# ============================================================================
# TRAINING
# ============================================================================
def train_model(model, X, y, hard_indices):
"""Train with advanced techniques."""
print("\n" + "=" * 60)
print(f"TRAINING FOR {EPOCHS} EPOCHS")
print("=" * 60)
# Split data
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=VALIDATION_SPLIT, random_state=42, stratify=y
)
print(f"\n📊 Data split:")
print(f" Training: {len(X_train)} samples")
print(f" Validation: {len(X_val)} samples")
# Compute class weights
class_weights = None
if USE_CLASS_WEIGHTS:
weights = compute_class_weight('balanced', classes=np.unique(y_train), y=y_train)
class_weights = dict(enumerate(weights))
print(f" Using class weights: min={min(weights):.2f}, max={max(weights):.2f}")
# Find hard examples in training set
train_hard_indices = []
if hard_indices is not None:
train_indices_set = set(range(len(X_train)))
# Map original indices to training indices (approximation)
for h_idx in hard_indices:
if h_idx < len(X_train):
train_hard_indices.append(h_idx)
# Create augmenter and generator
augmenter = AdvancedAugmenter(
noise_std=AUG_NOISE_STD,
scale_range=AUG_SCALE_RANGE,
rotation_range=AUG_ROTATION_RANGE,
shift_range=AUG_SHIFT_RANGE
)
train_gen = AdvancedDataGenerator(
X_train, y_train, BATCH_SIZE, augmenter, NUM_CLASSES,
use_mixup=True, use_cutmix=True,
hard_example_indices=train_hard_indices,
hard_example_ratio=0.2
)
# Validation data
y_val_one_hot = keras.utils.to_categorical(y_val, NUM_CLASSES)
# Callbacks
callbacks = [
WarmupCosineDecay(INITIAL_LR, MIN_LR, WARMUP_EPOCHS, EPOCHS, restarts=3),
keras.callbacks.ModelCheckpoint(
OUTPUT_H5,
monitor='val_accuracy',
save_best_only=True,
verbose=1
),
keras.callbacks.ModelCheckpoint(
'isl_model_advanced_latest.h5',
save_best_only=False,
verbose=0
),
# Reduce LR if stuck (backup scheduler)
keras.callbacks.ReduceLROnPlateau(
monitor='val_loss',
factor=0.5,
patience=15,
min_lr=MIN_LR,
verbose=1
),
# Progress logging
keras.callbacks.LambdaCallback(
on_epoch_end=lambda epoch, logs: print(
f"\n 📈 Epoch {epoch+1}/{EPOCHS} - "
f"acc: {logs.get('accuracy', 0)*100:.2f}% - "
f"val_acc: {logs.get('val_accuracy', 0)*100:.2f}% - "
f"lr: {logs.get('lr', 0):.6f}"
) if (epoch + 1) % 10 == 0 else None
)
]
# Train
print(f"\n🚀 Starting training...")
print(f" Techniques: Focal Loss, Attention, Residual, Mixup, CutMix")
print(f" Augmentation: Noise, Scale, Rotation, Shift, Mirror\n")
history = model.fit(
train_gen,
validation_data=(X_val, y_val_one_hot),
epochs=EPOCHS,
callbacks=callbacks,
class_weight=class_weights,
verbose=1
)
# Load best model
print("\n📂 Loading best model...")
model = keras.models.load_model(
OUTPUT_H5,
custom_objects={
'FocalLoss': FocalLoss,
'ChannelAttention': ChannelAttention,
'ResidualBlock': ResidualBlock
}
)
return history, model, X_val, y_val
# ============================================================================
# TEST-TIME AUGMENTATION
# ============================================================================
def predict_with_tta(model, X, n_augments=5):
"""Prediction with test-time augmentation."""
augmenter = AdvancedAugmenter(noise_std=0.01, scale_range=(0.95, 1.05))
predictions = []
# Original prediction
predictions.append(model.predict(X, verbose=0))
# Augmented predictions
for _ in range(n_augments - 1):
X_aug = augmenter.augment_batch(X, p=0.5)
predictions.append(model.predict(X_aug, verbose=0))
# Average predictions
avg_pred = np.mean(predictions, axis=0)
return avg_pred
# ============================================================================
# EVALUATION
# ============================================================================
def evaluate_model(model, X_val, y_val, use_tta=True):
"""Comprehensive evaluation."""
print("\n" + "=" * 60)
print("EVALUATION")
print("=" * 60)
# Standard prediction
y_val_one_hot = keras.utils.to_categorical(y_val, NUM_CLASSES)
val_loss, val_acc = model.evaluate(X_val, y_val_one_hot, verbose=0)
print(f"\n📈 Standard Evaluation:")
print(f" Validation Accuracy: {val_acc*100:.2f}%")
print(f" Validation Loss: {val_loss:.4f}")
# TTA prediction
if use_tta:
print(f"\n🔄 Test-Time Augmentation (TTA):")
tta_pred = predict_with_tta(model, X_val, n_augments=5)
tta_classes = np.argmax(tta_pred, axis=1)
tta_acc = np.mean(tta_classes == y_val)
print(f" TTA Accuracy: {tta_acc*100:.2f}%")
else:
tta_pred = model.predict(X_val, verbose=0)
tta_classes = np.argmax(tta_pred, axis=1)
# Classification report
print("\n" + "-" * 60)
print("CLASSIFICATION REPORT")
print("-" * 60)
print(classification_report(y_val, tta_classes, target_names=LABELS, digits=3))
# Confusion analysis for hard pairs
print("\n" + "-" * 60)
print("CONFUSED PAIRS ANALYSIS")
print("-" * 60)
total_confusion = 0
for sign_a, sign_b in CONFUSED_PAIRS:
if sign_a in LABELS and sign_b in LABELS:
idx_a, idx_b = LABELS.index(sign_a), LABELS.index(sign_b)
mask_a = y_val == idx_a
mask_b = y_val == idx_b
a_as_b = np.sum((tta_classes == idx_b) & mask_a)
b_as_a = np.sum((tta_classes == idx_a) & mask_b)
if a_as_b > 0 or b_as_a > 0:
print(f" ⚠️ {sign_a} ↔ {sign_b}: {sign_a}→{sign_b}={a_as_b}, {sign_b}→{sign_a}={b_as_a}")
total_confusion += a_as_b + b_as_a
else:
print(f" ✅ {sign_a} ↔ {sign_b}: Perfect!")
print(f"\n Total confusions in pairs: {total_confusion}")
return val_acc
# ============================================================================
# CONVERT TO TFLITE
# ============================================================================
def convert_to_tflite(model):
"""Convert to optimized TFLite."""
print("\n" + "=" * 60)
print("CONVERTING TO TFLITE")
print("=" * 60)
# Save a version without custom objects for TFLite conversion
# Re-create model with standard layers
print(" Creating export-friendly model...")
input_size = model.input_shape[1]
# Simple export model (without custom layers)
export_model = keras.Sequential([
layers.Input(shape=(input_size,)),
layers.Dense(512, activation='gelu'),
layers.BatchNormalization(),
layers.Dropout(0.4),
layers.Dense(256, activation='gelu'),
layers.BatchNormalization(),
layers.Dropout(0.3),
layers.Dense(128, activation='gelu'),
layers.BatchNormalization(),
layers.Dropout(0.3),
layers.Dense(64, activation='gelu'),
layers.BatchNormalization(),
layers.Dropout(0.2),
layers.Dense(32, activation='gelu'),
layers.BatchNormalization(),
layers.Dropout(0.2),
layers.Dense(NUM_CLASSES, activation='softmax')
])
export_model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Knowledge distillation: train export model on advanced model's predictions
print(" Performing knowledge distillation...")
# Load training data for distillation
X_all, y_all, _ = load_data()
if X_all is not None:
# Get soft labels from advanced model
soft_labels = model.predict(X_all, verbose=0)
# Train export model
export_model.fit(
X_all, soft_labels,
epochs=20,
batch_size=64,
verbose=1
)
# Convert to TFLite
print("\n Converting to TFLite...")
converter = tf.lite.TFLiteConverter.from_keras_model(export_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# Quantization for smaller size
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.convert()
with open(OUTPUT_MODEL, 'wb') as f:
f.write(tflite_model)
print(f"\n✅ TFLite model saved: {OUTPUT_MODEL}")
print(f" Size: {os.path.getsize(OUTPUT_MODEL) / 1024:.2f} KB")
# Verify
print("\n📋 Verifying TFLite model...")
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print(f" Input shape: {input_details[0]['shape']}")
print(f" Output shape: {output_details[0]['shape']}")
return tflite_model
# ============================================================================
# SAVE CONFIG
# ============================================================================
def save_config(val_acc):
"""Save configuration."""
config = {
'labels': LABELS,
'num_classes': NUM_CLASSES,
'input_size': 130,
'validation_accuracy': float(val_acc),
'training_config': {
'epochs': EPOCHS,
'batch_size': BATCH_SIZE,
'focal_loss': USE_FOCAL_LOSS,
'attention': USE_ATTENTION,
'residual': USE_RESIDUAL,
'augmentation': {
'noise_std': AUG_NOISE_STD,
'scale_range': list(AUG_SCALE_RANGE),
'rotation_range': AUG_ROTATION_RANGE,
'mixup_alpha': MIXUP_ALPHA,
'cutmix_alpha': CUTMIX_ALPHA
}
},
'model_files': {
'h5': OUTPUT_H5,
'tflite': OUTPUT_MODEL
}
}
with open(OUTPUT_LABELS, 'w') as f:
json.dump(config, f, indent=2)
print(f"✅ Config saved: {OUTPUT_LABELS}")
# ============================================================================
# MAIN
# ============================================================================
def main():
print("\n" + "=" * 70)
print("🚀 ADVANCED ISL MODEL TRAINING - MAXIMUM ACCURACY")
print("=" * 70)
print("\nTarget: 9-10/10 accuracy with real-world robustness")
print("\nAdvanced Techniques:")
print(" ✓ Focal Loss - Focus on hard examples")
print(" ✓ Attention Mechanism - Important features")
print(" ✓ Residual Connections - Better gradients")
print(" ✓ Multi-Scale Features - Different patterns")
print(" ✓ Advanced Augmentation - Realistic variations")
print(" ✓ Mixup + CutMix - Better generalization")
print(" ✓ Class Balancing - Handle imbalance")
print(" ✓ Hard Example Mining - Confused pairs")
print(" ✓ Test-Time Augmentation - Better inference")
print(" ✓ Knowledge Distillation - Better TFLite")
# Load data
X, y, hard_indices = load_data()
if X is None:
return
input_size = X.shape[1]
# Create model
model = create_advanced_model(input_size)
# Train
history, model, X_val, y_val = train_model(model, X, y, hard_indices)
# Evaluate
val_acc = evaluate_model(model, X_val, y_val, use_tta=True)
# Convert to TFLite
convert_to_tflite(model)
# Save config
save_config(val_acc)
# Final summary
print("\n" + "=" * 70)
print("✅ TRAINING COMPLETE!")
print("=" * 70)
print(f"\n🎯 Final Validation Accuracy: {val_acc*100:.2f}%")
print(f"\n📁 Output files:")
print(f" 📄 {OUTPUT_H5} - Best Keras model")
print(f" 📄 {OUTPUT_MODEL} - TFLite for Android")
print(f" 📄 {OUTPUT_LABELS} - Configuration")
print("\n💡 Tips for even better results:")
print(" 1. Collect more data for underperforming classes")
print(" 2. Add more augmented samples for confused pairs")
print(" 3. Use ensemble of multiple models")
print(" 4. Fine-tune on real webcam data")
if __name__ == "__main__":
main().gitattributes+2
README.mdAdded
evaluation_results/classification_report_20260211_155639.txtAdded+70
evaluation_results/confusion_matrix.pngAdded

Large File Pointer Details
- SHA256: 9f9c6559112b6e9f884148f8048e74f6e01ea0e15510fdab91037818fa4f0a31
- Pointer size: 131 Bytes
- Size of remote file: 358 kB
evaluation_results/confusion_matrix_20260211_155639.csvAdded+36
evaluation_results/confusion_pairs_20260211_155639.csvAdded+3
evaluation_results/evaluation_metrics_20260211_155639.jsonAdded+21
evaluation_results/per_class_metrics_20260211_155639.csvAdded+36
isl_model_advanced.tfliteAdded+3
landmark_dataset_with_orientation.csvAdded+3
optimize_sign_assets.pyAdded+113
prepare_local_sign_assets.pyAdded+119
test_full_model.pyAdded+586
train_advanced_model.pyAdded+1093