Skip to content

mehranmushtaq/ml-scikit-scratch

Repository files navigation

🧠Machine Learning with Scikit-Learn & From Scratch

Python Scikit-Learn XGBoost Pandas NumPy Matplotlib Jupyter Streamlit

End-to-End Machine Learning Repository β€” From Theory to Deployment

πŸ† 94.89% accuracy on Disease Prediction Β |Β  πŸ“ˆ F1: 0.6485 on E-Commerce (+18% above benchmark) Β |Β  πŸ›’ 4 customer segments uncovered in SmartCart Β |Β  🧬 89% Precision@K on Thyroid Outlier Detection Β |Β  πŸš€ 2 Projects Deployed to Production


Mehran Mushtaq Β· Data Science & Machine Learning Track Β· Python Β· Scikit-Learn


What Is This Repository?

This isn’t just a collection of notebooks.

It’s a complete learning journey β€” from implementing algorithms by hand to deploying production-ready ML pipelines β€” built over the course of an intensive internship.

Every folder tells a chapter of that story: understanding why an algorithm works before trusting a library to do it. Writing clean pipelines. Tuning models properly. Building real projects that solve real problems β€” and then shipping them.


What Makes This Different

Approach What Was Done
From Scratch Core algorithms implemented in pure Python/NumPy β€” no sklearn shortcuts
Pipelines Clean, reproducible workflows using sklearn.Pipeline to prevent data leakage
GridSearchCV Systematic hyperparameter tuning on real datasets
Cross-Validation Robust evaluation using k-fold CV with stratification
Unsupervised Learning Clustering, anomaly detection, and dimensionality reduction on real data
End-to-End Projects Full pipelines from raw data β†’ feature engineering β†’ model β†’ evaluation β†’ insight
πŸš€ Deployed Projects shipped beyond notebooks β€” live demos accessible online

πŸš€ Live Deployments

These projects have been fully deployed and are accessible as interactive web applications.

Project Domain Live Demo
🏠 House Price Prediction Real Estate Live Demo
πŸ’³ CreditWise Loan Approval Finance Live Demo Β· Repo

Projects At a Glance

Project Domain Technique Key Result Status
🏠 House Price Prediction Real Estate Linear Regression + Feature Engineering Deployed to production πŸš€ Live
πŸ’³ CreditWise Loan Approval Finance Classification Pipeline Deployed to production πŸš€ Live
πŸ₯ Disease Prediction Pipeline Healthcare Voting Classifier Ensemble 94.89% accuracy βœ… Complete
πŸ›’ E-Commerce Purchase Prediction Retail Decision Tree F1: 0.6485 (+18% benchmark) βœ… Complete
πŸ”¬ SmartCart Customer Segmentation Retail K-Means + Agglomerative + PCA 4 actionable customer personas βœ… Complete
🧬 Thyroid Outlier Detection Healthcare Isolation Forest + LOF 89% Precision@K βœ… Complete

πŸ—‚οΈ Repository Structure

ml-scikit-scratch/
β”‚
β”œβ”€β”€ πŸ“ Datasets/                              # Shared datasets across experiments
β”‚   β”œβ”€β”€ Emotion_classify_Data.csv
β”‚   β”œβ”€β”€ Iris.csv
β”‚   β”œβ”€β”€ Social_Network_Ads.csv
β”‚   β”œβ”€β”€ house_prices_practice.csv
β”‚   └── insurance.csv
β”‚
β”œβ”€β”€ πŸ“ linear_regression/
β”‚   β”œβ”€β”€ Linear_regression.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Logistic Regression/
β”‚   β”œβ”€β”€ Logistic_Regressor.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ KNN/
β”‚   β”œβ”€β”€ Knn.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Decision tree/
β”‚   β”œβ”€β”€ decision_tree_classifier.ipynb
β”‚   β”œβ”€β”€ decision_tree_regressor.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Naive bayes/
β”‚   β”œβ”€β”€ naive_bayes.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Support Vector Machine/
β”‚   β”œβ”€β”€ svc.ipynb
β”‚   β”œβ”€β”€ svr.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Regularizaton(Lasso:Ridge)/
β”‚   β”œβ”€β”€ lasso_ridge.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ ensemble learning/
β”‚   β”œβ”€β”€ bagging/                              # Random Forest
β”‚   β”‚   β”œβ”€β”€ Random_forest.ipynb
β”‚   β”‚   └── README.md
β”‚   └── boosting/                             # AdaBoost, Gradient Boosting, XGBoost
β”‚       β”œβ”€β”€ ada_boosting.ipynb
β”‚       β”œβ”€β”€ gradient_boosting.ipynb
β”‚       β”œβ”€β”€ xgboost.ipynb
β”‚       └── README.md
β”‚
β”œβ”€β”€ πŸ“ ml-from-scratch/                      
β”‚   β”œβ”€β”€ linear_reg.ipynb
β”‚   β”œβ”€β”€ logistic_reg.ipynb
β”‚   └── knn_regressor.ipynb
β”‚
β”œβ”€β”€ πŸ“ unsupervised ml/
β”‚   β”œβ”€β”€ k_means.ipynb
β”‚   β”œβ”€β”€ hiearchichal_clustering.ipynb
β”‚   β”œβ”€β”€ dbscan.ipynb
β”‚   └── README.md
β”‚
β”œβ”€β”€ πŸ“ Projects/                              
β”‚   β”œβ”€β”€ πŸ“ house-price-prediction/            #  DEPLOYED
β”‚   β”œβ”€β”€ πŸ“ customer-segmentation-smartcart/
β”‚   β”œβ”€β”€ πŸ“ CreditWise Loan System/            #  DEPLOYED (separate repo)
β”‚   β”œβ”€β”€ πŸ“ ecommerce-purchase-prediction/
β”‚   β”œβ”€β”€ πŸ“ thyroid_outlier_detection/
β”‚   └── πŸ“ disease_prediction_pipeline/
β”‚
β”œβ”€β”€ notebook_vs_production.md
β”œβ”€β”€ requirements.txt
└── README.md

What This Repository Covers

Supervised Learning

Ensemble Methods

  • Bagging β€” Random Forest with feature importance analysis
  • Boosting β€” AdaBoost, Gradient Boosting, and XGBoost

Unsupervised Learning

ML From Scratch (Pure Python / NumPy)


Featured Projects


🏠 House Price Prediction β€” Deployed

Domain: Real Estate Β· Type: Supervised Regression Β· Dataset: house_prices_practice.csv Β· πŸš€ Live Demo

The Problem: Predict residential property sale prices from structural and neighbourhood features β€” a classic, high-value regression problem.

Approach & Key Decisions:

  • Exploratory Data Analysis: Identified key drivers of price β€” GrLivArea, OverallQual, TotalBsmtSF, and neighbourhood β€” through correlation analysis and visualisations
  • Feature Engineering: Created interaction features (e.g. total floor area), handled missing values with domain-aware imputation, and log-transformed the skewed target variable to improve model fit
  • Preprocessing Pipeline: ColumnTransformer applied scaling to numerical features and one-hot encoding to categorical ones inside a single sklearn.Pipeline
  • Model Selection: Evaluated Linear Regression, Ridge, and Lasso β€” tuned regularisation strength via GridSearchCV
  • Deployment: Exported the trained pipeline and built an interactive Streamlit web app so anyone can input house features and receive an instant price estimate

Highlights:

Aspect Detail
Target Sale price (log-transformed)
Key Features Living area, overall quality, basement size, year built, neighbourhood
Preprocessing Median imputation, OneHot encoding, StandardScaler
Deployment Streamlit web application

Tech: pandas, numpy, matplotlib, seaborn, sklearn (Pipeline, Ridge, Lasso, GridSearchCV), streamlit


πŸ’³ CreditWise Loan Approval System β€” Deployed

Domain: Finance Β· Type: Supervised Classification Β· Deliverable: Notebook + Production .py script + Live App Β· πŸš€ Live Demo Β· πŸ“ Repository

The Problem: Manual loan approval is slow, inconsistent, and prone to bias. CreditWise needed an automated classification system to assess applicant risk from financial and demographic data β€” consistently, at scale.

Approach & Key Decisions:

  • Feature Engineering: Derived risk signals β€” debt-to-income proxies, employment stability indicators, and interaction terms between credit history and income band
  • Preprocessing Pipeline: ColumnTransformer applied different strategies to numerical (imputation + scaling) and categorical (encoding) features simultaneously
  • Model Selection: Logistic Regression, Random Forest, and Gradient Boosting evaluated; best model tuned with GridSearchCV
  • Production Delivery: Final model exported as a standalone .py script and deployed as an interactive Streamlit application β€” accessible via the live demo link above

Highlights:

Aspect Detail
Input features Income, loan amount, credit history, employment, dependents, property area
Preprocessing Median imputation, OneHot encoding, StandardScaler
Evaluation Accuracy, Precision, Recall, F1, Confusion Matrix
Deployment Streamlit web application (separate repo)

Tech: pandas, sklearn (Pipeline, ColumnTransformer, GridSearchCV, RandomForestClassifier, GradientBoostingClassifier, LogisticRegression), matplotlib, streamlit


πŸ₯ Disease Prediction Pipeline

Domain: Healthcare Β· Type: Supervised Classification Β· Dataset: 9,800 patients (NovaGen Research Labs)

The Problem: NovaGen Research Labs needed a reliable automated system to classify patients as healthy or at risk based on clinical features β€” to streamline clinical trial participant selection and reduce manual screening time.

Approach & Key Decisions:

  • Pipeline-first design: Entire workflow (imputation β†’ encoding β†’ scaling β†’ model) encapsulated in a single sklearn.Pipeline β€” zero data leakage guaranteed
  • Ensemble strategy: Hard-voting classifier combining Logistic Regression, Random Forest, and NaΓ―ve Bayes β€” majority vote reduces the variance of any single model
  • Stratified K-Fold CV: Class proportions preserved across every fold β€” critical for a medical dataset
  • Evaluation focus: Optimised for recall alongside accuracy β€” in clinical settings, false negatives are the higher-risk failure mode

Results:

Metric Score
Accuracy 94.89%
CV Recall 95.46%
Validation Strategy Stratified K-Fold Cross-Validation
Model Hard-Voting Ensemble (LR + RF + NB)

Tech: pandas, sklearn (Pipeline, VotingClassifier, LogisticRegression, RandomForestClassifier, GaussianNB, StratifiedKFold, cross_val_score)


πŸ›’ E-Commerce Purchase Prediction

Domain: Retail Β· Type: Supervised Classification Β· Dataset: 12,330 browsing sessions (ShopSmart)

The Problem: Only ~15% of ShopSmart’s 12,330 recorded browsing sessions ended in a purchase. The marketing team needed a model to identify which visitors were likely to convert.

Approach & Key Decisions:

  • Class imbalance handling: class_weight='balanced' in the Decision Tree forces attention on the minority (purchase) class
  • Depth pruning: max_depth tuned via GridSearchCV to prevent overfitting on the majority class
  • Evaluation: Prioritised F1-Score as the primary metric β€” the harmonic mean of precision and recall

Results:

Metric Score
F1-Score 0.6485
Benchmark F1 0.55
Improvement +18% above benchmark
Class Imbalance 85% non-purchase / 15% purchase

Tech: pandas, sklearn (DecisionTreeClassifier, GridSearchCV, classification_report, train_test_split), matplotlib, seaborn


πŸ”¬ SmartCart Customer Segmentation

Domain: Retail Β· Type: Unsupervised Learning Β· Dataset: 2,240 customers Γ— 22 features

The Problem: SmartCart was treating all customers the same β€” one message, one offer, one strategy. The goal was to discover natural groupings so marketing, product, and retention teams could act with precision.

Approach & Key Decisions:

  • Feature engineering: Age, Customer_Tenure_Days, Total_Spending, Total_Children derived from raw columns
  • Outlier removal: Customers aged 90+ and income above $600k dropped
  • Dimensionality reduction: PCA reduced the feature space to 4 principal components (~55% variance explained)
  • K selection: Elbow Method + Silhouette Score both converged on k = 4
  • Final model: Agglomerative Clustering (Ward linkage) selected over K-Means for deterministic, tighter cluster boundaries

Results β€” Discovered Customer Segments:

Cluster Avg Income Avg Spending Profile
0 ~$42,706 ~$327 Budget-conscious, larger families
1 ~$66,279 ~$1,055 Affluent loyalists, catalog-heavy
2 ~$35,326 ~$110 Low-income, high web visits
3 ~$74,727 ~$1,271 Premium spenders, fewest children

Tech: pandas, numpy, seaborn, matplotlib, sklearn (PCA, KMeans, AgglomerativeClustering, silhouette_score), kneed


🧬 Thyroid Outlier Detection

Domain: Healthcare Β· Type: Unsupervised Anomaly Detection Β· Dataset: 1,000 patient lab records

The Problem: In 1,000 thyroid hormone lab results, a small number of patients had clinically abnormal profiles β€” but no labels indicated which ones. The system had to find anomalies without any ground truth.

Approach & Key Decisions:

  • Dual-detector approach: Isolation Forest (global anomalies) + LOF (local outliers) β€” agreement between both increases confidence in flagged cases
  • No labels required: System learns the β€œnormal” distribution from the data itself
  • Validation: Flagged patients cross-checked against clinical reference ranges for hypo/hyperthyroid conditions

Results:

Metric Score
Precision@K 89%
Detectors Used Isolation Forest + LOF
Labels Required None (fully unsupervised)

Tech: pandas, numpy, sklearn (IsolationForest, LocalOutlierFactor, StandardScaler), matplotlib, seaborn


Setup & Installation

# Clone the repository
git clone https://github.com/mehranmushtaq/ml-scikit-scratch.git

# Navigate into the repo
cd ml-scikit-scratch

# (Recommended) Create a virtual environment
python -m venv venv
source venv/bin/activate        # macOS/Linux
venv\Scripts\activate           # Windows

# Install dependencies
pip install -r requirements.txt

# Launch Jupyter
jupyter notebook

Key Concepts Practiced

Data Preprocessing & Feature Engineering
Encoding (LabelEncoder, One-Hot, ColumnTransformer)
Train/Test Split with Stratification
StandardScaler inside Pipelines (zero data leakage)
GridSearchCV for Hyperparameter Tuning
Cross-Validation (k-fold, stratified)
Class Imbalance Handling (class_weight, resampling)
Dimensionality Reduction via PCA
Unsupervised Validation (Elbow Method, Silhouette Score)
Anomaly Detection (Isolation Forest, LOF)
Model Evaluation (Accuracy, F1, Precision, Recall, AUC)
Confusion Matrix Analysis
Feature Importance Visualisation
Algorithms Implemented From Scratch (NumPy only)
Model Deployment (Streamlit)

Author

Mehran Mushtaq Β· Data Science & Machine Learning Track

GitHub


β€œFirst, solve the problem. Then, write the code.” β€” John Johnson

About

End-to-end Machine Learning repository showcasing implementations of core algorithms using Scikit-Learn and from scratch, along with real-world projects, data analysis, and model evaluation techniques

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages