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
The app is designed to help users understand KNN classification in an interactive way.
- 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
- Standard built-in scikit-learn datasets:
- 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
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
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.
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.
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.
The application follows a simple client-server architecture.
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
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
- The user chooses either a standard dataset or an uploaded dataset in the frontend.
- The frontend sends a POST request to either the standard analysis endpoint or the uploaded-data analysis endpoint.
- The backend loads or parses the dataset, performs preprocessing and model evaluation.
- The backend returns metrics and visualization payloads.
- The frontend renders the results step by step.
These are defined in backend/requirements.txt:
- fastapi
- uvicorn[standard]
- pydantic
- numpy
- scikit-learn
- python-multipart
- 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.
These are defined in frontend/package.json:
- @tailwindcss/vite
- framer-motion
- lucide-react
- react
- react-dom
- recharts
- tailwindcss
- @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
A clean Python virtual environment is strongly recommended for the backend.
The project is configured to use:
- backend/.venv
This keeps the ML dependencies isolated from the system Python installation.
From the project root:
python3 -m venv backend/.venvsource backend/.venv/bin/activatebackend\.venv\Scripts\Activate.ps1backend\.venv\Scripts\activate.batpip install --upgrade pip
pip install -r backend/requirements.txtThe project Makefile already handles this setup automatically when you use the root-level commands.
Install the frontend dependencies from the project root:
cd frontend
npm installIf you prefer the root Makefile workflow, run:
make install-frontendThe project is configured to run the backend and frontend separately, or together.
From the project root:
make installThis will:
- create the backend virtual environment
- install backend Python packages
- install frontend Node packages
make backendThis starts the API on:
The backend entrypoint is the FastAPI application in backend/Main.py.
make frontendThis starts the Vite dev server on:
make devThis launches both services simultaneously using background processes and stops both when the terminal is interrupted.
If you do not want to use Make, the backend and frontend can be started directly.
source backend/.venv/bin/activate
cd backend
uvicorn Main:app --reload --port 8000cd frontend
npm run devcd frontend
npm run buildcd frontend
npm run previewcd frontend
npm run lintThe backend uses FastAPI, which also exposes interactive OpenAPI documentation automatically.
Returns the service health status.
Example response:
{
"status": "ok"
}Returns a list of all supported datasets, including dataset metadata, sample count, feature count, and class distribution.
Runs the full KNN analysis pipeline for a built-in standard dataset.
{
"dataset": "iris",
"train_ratio": 0.8,
"max_k": 25
}- 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
Runs the full KNN analysis pipeline for a user-uploaded dataset.
- 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
- 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
- dataset metadata
- train/test split summary
- optimal model configuration
- K-search accuracy data
- confusion matrix
- classification report
- PCA-based visualization payload for the frontend
The frontend is structured as a guided multi-step experience.
- Choose data source
- Standard datasets
- Upload your own CSV or TSV file
- If using a standard dataset, choose one of the built-in dataset cards
- Loading animation
- Configuration panel
- K-search visualization
- Fit and prediction visualization
- Results panel
This step-by-step flow is implemented in frontend/src/App.tsx and the supporting components under frontend/src/components.
The frontend is configured to optionally use an API URL from the environment.
- VITE_API_URL
If not set, the frontend uses:
This is defined in frontend/src/api.ts.
VITE_API_URL=http://localhost:8000The root Makefile is the main convenience interface for local setup and development.
- make install
- make install-backend
- make install-frontend
- make backend
- make frontend
- make dev
- make clean
make cleanRemoves:
- the backend virtual environment
- frontend Node modules
- frontend build output
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
- Makefile: local automation for environment setup and development workflows.
- backend/Main.py: FastAPI app, ML analysis pipeline, and API routes.
- backend/requirements.txt: Python server dependencies.
- frontend/package.json: frontend scripts and dependency manifest.
- frontend/src/App.tsx: main application flow.
- frontend/src/api.ts: frontend API client to the backend.
- frontend/src/components: modular UI panels and visualization components.
This project uses KNN with standardization and repeated evaluation across odd K values.
- 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.
- 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.
If the backend shows missing package errors:
source backend/.venv/bin/activate
pip install -r backend/requirements.txtIf the frontend cannot start:
cd frontend
rm -rf node_modules package-lock.json
npm installThe 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.
Ensure:
- the virtual environment is active
- the Python packages are installed
- the current working directory and module path are correct
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
If you want the fastest local setup:
make install
make devThen open:
- http://localhost:5173 for the frontend
- http://localhost:8000/docs for the backend API documentation
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.