Skip to content

Latest commit

 

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KNN Classification Visualizer

KNN Classification Visualizer is a full-stack machine learning project that helps users explore how the K-Nearest Neighbours (KNN) algorithm behaves on classification data. The app supports both built-in scikit-learn datasets and user-uploaded CSV/TSV files, making it easy to compare how different K values perform and inspect the resulting model through charts, confusion matrices, and neighbour-level explanations.

This repository combines:

  • a FastAPI backend for dataset loading, preprocessing, model evaluation, and structured result delivery
  • a React + TypeScript + Vite frontend for a guided, step-by-step visual workflow
  • a Python virtual environment for backend dependency isolation
  • a Node.js setup for frontend development and local build tooling

1. Project Overview

The app is designed to help users understand KNN classification in an interactive way.

What the project does

  • Lets the user choose between two dataset sources:
    • Standard built-in scikit-learn datasets:
      • iris
      • digits
      • wine
      • breast_cancer
    • An uploaded dataset from the user’s own machine
  • Accepts uploaded data in CSV or TSV format only.
  • Uses the last column as the target/class label and all earlier columns as numeric feature inputs.
  • Splits each dataset into training and testing subsets.
  • Standardizes the features using StandardScaler after splitting to avoid information leakage.
  • Evaluates candidate odd K values across a cross-validation search.
  • Selects the best K based on mean cross-validation accuracy.
  • Produces a final performance report including:
    • accuracy metrics
    • confusion matrix
    • classification report
    • PCA-based visualization of training and test points
    • nearest-neighbour explanations for test cases

Why it matters

This project is useful for learning and demonstrating:

  • how K affects model performance
  • how train/test splitting works in practice
  • how feature scaling influences distance-based algorithms
  • how cross-validation helps estimate generalisation quality
  • how a production-style frontend can connect to a Python ML backend

2. Internship Context

This repository is the second project created during the DecodeLabs Internship.

The focus of the project is not just to build a working model, but to present machine learning concepts in a visually interactive and educational way. The frontend acts as the storytelling layer, while the backend provides the actual analytical computation. This gives the project a strong learning-and-demonstration value, especially for internships or portfolio purposes.


3. Technical Stack

Frontend

The frontend is a modern Vite-powered React application written in TypeScript.

Core technologies:

  • React 19
  • TypeScript
  • Vite 8
  • Tailwind CSS 4
  • Framer Motion
  • Recharts
  • Lucide React

Why these are used:

  • React provides the UI component model.
  • TypeScript adds strong typing and easier maintenance.
  • Vite provides fast development startup and build performance.
  • Tailwind CSS handles layout and styling.
  • Framer Motion creates transitions and polished UI animations.
  • Recharts powers the K-accuracy charts.
  • Lucide React provides iconography for the workflow UI.

Backend

The backend is a FastAPI service that exposes an API for analysis and dataset retrieval.

Core technologies:

  • FastAPI
  • Uvicorn
  • Pydantic
  • NumPy
  • scikit-learn

Why these are used:

  • FastAPI offers a high-performance API framework with automatic validation.
  • Uvicorn runs the ASGI server for development and production-like local execution.
  • Pydantic validates request payloads.
  • NumPy is used for array operations and model data preparation.
  • scikit-learn supplies the datasets, preprocessing, evaluation metrics, PCA, and KNN classifier.

4. Project Architecture

The application follows a simple client-server architecture.

Frontend responsibilities

The frontend:

  • displays a source-selection screen with two options: standard datasets or uploaded data
  • lets the user browse the built-in scikit-learn dataset list or choose a local CSV/TSV file
  • shows a loading phase with animated progress
  • allows configuration of train ratio and maximum K
  • triggers the appropriate analysis request for either standard or uploaded datasets
  • renders the K-search chart, fit/predict view, and final results panel
  • displays confusion matrix, classification details, and PCA-based visualizations

Backend responsibilities

The backend:

  • loads built-in datasets from scikit-learn
  • validates and parses uploaded CSV/TSV files
  • returns metadata about available standard datasets and their class distribution
  • splits the selected dataset into train and test sets
  • scales the features using StandardScaler
  • performs K-fold cross-validation for odd K values
  • computes the optimal K and the final model predictions
  • returns all structured output needed by the frontend

Data flow

  1. The user chooses either a standard dataset or an uploaded dataset in the frontend.
  2. The frontend sends a POST request to either the standard analysis endpoint or the uploaded-data analysis endpoint.
  3. The backend loads or parses the dataset, performs preprocessing and model evaluation.
  4. The backend returns metrics and visualization payloads.
  5. The frontend renders the results step by step.

5. Dependency Breakdown

Backend dependencies

These are defined in backend/requirements.txt:

  • fastapi
  • uvicorn[standard]
  • pydantic
  • numpy
  • scikit-learn
  • python-multipart

Purpose of each

  • fastapi: API framework and request handling.
  • uvicorn[standard]: ASGI server with production-ready support.
  • pydantic: schema validation and request model definitions.
  • numpy: numerical data operations needed by the KNN workflow.
  • scikit-learn: dataset loading, scaling, PCA, classifier logic, and metrics.
  • python-multipart: enables FastAPI file upload handling for the CSV/TSV analysis route.

Frontend dependencies

These are defined in frontend/package.json:

Runtime dependencies

  • @tailwindcss/vite
  • framer-motion
  • lucide-react
  • react
  • react-dom
  • recharts
  • tailwindcss

Development dependencies

  • @eslint/js
  • @types/node
  • @types/react
  • @types/react-dom
  • @vitejs/plugin-react
  • eslint
  • eslint-plugin-react-hooks
  • eslint-plugin-react-refresh
  • globals
  • typescript
  • typescript-eslint
  • vite

6. Virtual Environment Setup

A clean Python virtual environment is strongly recommended for the backend.

Recommended backend environment location

The project is configured to use:

  • backend/.venv

This keeps the ML dependencies isolated from the system Python installation.

Create the environment

From the project root:

python3 -m venv backend/.venv

Activate the environment

On Linux or macOS / Git Bash / WSL

source backend/.venv/bin/activate

On Windows PowerShell

backend\.venv\Scripts\Activate.ps1

On Command Prompt

backend\.venv\Scripts\activate.bat

Install backend requirements

pip install --upgrade pip
pip install -r backend/requirements.txt

The project Makefile already handles this setup automatically when you use the root-level commands.


7. Frontend Setup

Install the frontend dependencies from the project root:

cd frontend
npm install

If you prefer the root Makefile workflow, run:

make install-frontend

8. Running the Project

The project is configured to run the backend and frontend separately, or together.

Option A: Install everything using the Makefile

From the project root:

make install

This will:

  • create the backend virtual environment
  • install backend Python packages
  • install frontend Node packages

Option B: Run the backend only

make backend

This starts the API on:

The backend entrypoint is the FastAPI application in backend/Main.py.

Option C: Run the frontend only

make frontend

This starts the Vite dev server on:

Option D: Run both together

make dev

This launches both services simultaneously using background processes and stops both when the terminal is interrupted.


9. Manual Run Commands

If you do not want to use Make, the backend and frontend can be started directly.

Backend

source backend/.venv/bin/activate
cd backend
uvicorn Main:app --reload --port 8000

Frontend

cd frontend
npm run dev

Production build for the frontend

cd frontend
npm run build

Preview production build

cd frontend
npm run preview

Lint the frontend

cd frontend
npm run lint

10. API Documentation

The backend uses FastAPI, which also exposes interactive OpenAPI documentation automatically.

Swagger UI

ReDoc


11. Backend API Endpoints

GET /api/health

Returns the service health status.

Example response:

{
  "status": "ok"
}

GET /api/datasets

Returns a list of all supported datasets, including dataset metadata, sample count, feature count, and class distribution.

POST /api/analyse

Runs the full KNN analysis pipeline for a built-in standard dataset.

Request body

{
  "dataset": "iris",
  "train_ratio": 0.8,
  "max_k": 25
}

Fields

  • dataset: one of iris, digits, wine, or breast_cancer
  • train_ratio: train/test split ratio, must be between 0.5 and 0.95
  • max_k: maximum candidate K value to evaluate, between 3 and 99

POST /api/analyse-upload

Runs the full KNN analysis pipeline for a user-uploaded dataset.

Upload requirements

  • file type must be CSV or TSV
  • file size must be 10 MB or smaller
  • file must use UTF-8 text encoding
  • the first row must contain column names
  • the last column is treated as the target/class label
  • all preceding columns must be numeric feature values
  • the dataset must contain at least two numeric feature columns and one target column
  • the target column must contain at least two classes
  • every class must have at least three samples so the stratified split remains valid
  • uploaded datasets are limited to 10,000 data rows

Form fields

  • file: uploaded CSV/TSV file
  • train_ratio: train/test split ratio, must be between 0.5 and 0.95
  • max_k: maximum candidate K value to evaluate, between 3 and 99

Response contains

  • dataset metadata
  • train/test split summary
  • optimal model configuration
  • K-search accuracy data
  • confusion matrix
  • classification report
  • PCA-based visualization payload for the frontend

12. Frontend Workflow

The frontend is structured as a guided multi-step experience.

Step flow

  1. Choose data source
    • Standard datasets
    • Upload your own CSV or TSV file
  2. If using a standard dataset, choose one of the built-in dataset cards
  3. Loading animation
  4. Configuration panel
  5. K-search visualization
  6. Fit and prediction visualization
  7. Results panel

This step-by-step flow is implemented in frontend/src/App.tsx and the supporting components under frontend/src/components.


13. Environment Variables

The frontend is configured to optionally use an API URL from the environment.

Variable

  • VITE_API_URL

Default behavior

If not set, the frontend uses:

This is defined in frontend/src/api.ts.

Example

VITE_API_URL=http://localhost:8000

14. Root-Level Makefile Commands

The root Makefile is the main convenience interface for local setup and development.

Available commands

  • make install
  • make install-backend
  • make install-frontend
  • make backend
  • make frontend
  • make dev
  • make clean

What clean does

make clean

Removes:

  • the backend virtual environment
  • frontend Node modules
  • frontend build output

15. Project Structure

KNN Classification/
├── Makefile
├── README.md
├── backend/
│   ├── Main.py
│   └── requirements.txt
└── frontend/
    ├── package.json
    ├── public/
    ├── src/
    ├── index.html
    ├── tsconfig.json
    ├── tsconfig.app.json
    ├── tsconfig.node.json
    ├── vite.config.ts
    └── eslint.config.js

Important files


16. Notes on ML Behaviour

This project uses KNN with standardization and repeated evaluation across odd K values.

Key design choices

  • K values are evaluated as odd integers only.
  • StandardScaler is fit only on the training portion.
  • PCA is used only for 2D visualization of data geometry.
  • Model evaluation is performed in the scaled feature space, not in PCA-projected space.
  • The frontend visualizations are designed to show the real neighbour relationship, not a simplified approximation.

Important implications

  • KNN is a distance-based algorithm, so scaling matters.
  • Odd K avoids tied voting outcomes in binary-style decision comparison.
  • Cross-validation helps better estimate which K generalizes well on held-out data.

17. Troubleshooting

Backend import or dependency issues

If the backend shows missing package errors:

source backend/.venv/bin/activate
pip install -r backend/requirements.txt

Frontend dependency issues

If the frontend cannot start:

cd frontend
rm -rf node_modules package-lock.json
npm install

CORS issues

The backend is configured to allow requests from:

If you change the frontend dev server origin, you may need to update the allowed origin list in backend/Main.py.

Backend fails to start

Ensure:

  • the virtual environment is active
  • the Python packages are installed
  • the current working directory and module path are correct

18. Development Summary

This repository demonstrates:

  • Python backend engineering with FastAPI
  • frontend integration with React + TypeScript
  • interactive machine learning visualization
  • backend dependency isolation using a virtual environment
  • practical full-stack development for an ML-focused internship project

19. Recommended Quick Start

If you want the fastest local setup:

make install
make dev

Then open:


20. Conclusion

KNN Classification Visualizer is a practical, educational, and visually rich machine learning project that combines backend intelligence with frontend usability. It is especially well suited to portfolio, internship, and demonstration use because it highlights:

  • data science workflow design
  • API development
  • frontend UI design
  • machine learning evaluation
  • environment and dependency management

This README provides the setup, architecture, running instructions, dependency notes, and overall project context needed to work with the repository effectively.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages