# import system libs
import os
import time
import shutil
import pathlib
import itertools
# import data handling tools
import cv2
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style('darkgrid')
import [Link] as plt
from sklearn.model_selection import train_test_split
from [Link] import confusion_matrix, classification_report
# import Deep learning Libraries
import tensorflow as tf
from tensorflow import keras
from [Link] import Sequential
from [Link] import Adam, Adamax
from [Link] import categorical_crossentropy
from [Link] import ImageDataGenerator
from [Link] import layers, models
from [Link] import Conv2D, MaxPooling2D, Flatten,
Dense, Activation, Dropout, BatchNormalization
from [Link] import regularizers
# Ignore Warnings
import warnings
[Link]("ignore")
print ('modules loaded')
# System Handling
import os
import cv2
from collections import Counter
import numpy as np # Data Preprocess
from [Link] import hog # Extract Features
from sklearn.model_selection import train_test_split # Split Data X,y
from [Link] import RandomForestClassifier # ML Model
from [Link] import classification_report, accuracy_score,
confusion_matrix # Final Report after train
from [Link] import LabelEncoder # Encoding
Features ,Category
import joblib # To save the model
from xgboost import XGBClassifier #xgb model
# For Vasulization
import seaborn as sns
import [Link] as plt
# Ignore Warnings
import warnings
[Link]("ignore")
# files Path
data_dir = '/kaggle/input/eye-diseases-classification/dataset'
def load_dataset(data_dir):
X = []
y = []
for class_label in [Link](data_dir):
class_folder = [Link](data_dir, class_label)
if not [Link](class_folder):
continue
for fname in [Link](class_folder):
fpath = [Link](class_folder, fname)
feat = extract_hog_features(fpath)
if feat is not None:
[Link](feat)
[Link](class_label)
return [Link](X), [Link](y)
# Feature we will use pixels (6,6) bes
# Images have very fine details (vessels, small spots, slight color variations)
def extract_hog_features(img_path, resize=(128, 128)):
img = [Link](img_path)
if img is None:
return None
img = [Link](img, resize)
gray = [Link](img, cv2.COLOR_BGR2GRAY)
features, _ = hog(gray, orientations=9, pixels_per_cell=(6, 6),
cells_per_block=(2, 2), block_norm='L2-Hys',
visualize=True)
return features
X,y= load_dataset(data_dir)
print("Number of samples:", len(X))
print("Number of labels:", len(y))
print("Shape of first image:", X[0].shape)
print("First 10 labels:", y[:10])
print("Unique labels:", set(y))
print("Label distribution:")
print(Counter(y))
label_counts = Counter(y)
labels = list(label_counts.keys())
counts = list(label_counts.values())
print("Label Distribution:")
for label, count in zip(labels, counts):
print(f"{label}: {count}")
[Link](figsize=(8,5))
[Link](x=labels, y=counts, palette='viridis')
[Link]("📊 Label Distribution in Eye Diseases Dataset", fontsize=14)
[Link]("Disease Class", fontsize=12)
[Link]("Number of Images", fontsize=12)
[Link](rotation=25)
[Link](axis='y', linestyle='--', alpha=0.7)
[Link]()
le = LabelEncoder()
y_encoded = le.fit_transform(y)
X_train, X_temp, y_train, y_temp = train_test_split(X, y_encoded,
test_size=0.3, stratify=y_encoded, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp,
test_size=0.5, stratify=y_temp, random_state=42)
print("Train:", X_train.shape, "Val:", X_val.shape, "Test:",
X_test.shape)
print("Classes:", le.classes_)
rf = RandomForestClassifier(n_estimators=200, random_state=42,
n_jobs=-1)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=le.classes_))
cm = confusion_matrix(y_test, y_pred)
[Link](figsize=(8,6))
[Link](cm, annot=True, fmt='d', xticklabels=le.classes_,
yticklabels=le.classes_, cmap='Blues')
[Link]("Predicted")
[Link]("True")
[Link]("Confusion Matrix")
[Link]()
[Link](rf, "rf_eye_model.pkl")
[Link](le, "label_encoder.pkl")
print("Model and LabelEncoder saved.")