Skip to content

Interactive Neural Network Builder - Build and train ANN from scratch with visual interface

Notifications You must be signed in to change notification settings

ZeeetOne/ann-from-scratch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 ANN from Scratch - Professional Neural Network Framework

Version Python Node.js License

Interactive web application for building, training, and testing Artificial Neural Networks from scratch using Python and NumPy.

πŸŽ‰ Professional Implementation: Modern architecture with ES6 modules, PostCSS build system, Clean Architecture, and SOLID principles.

πŸ“ Project Structure

ann-from-scratch/
β”œβ”€β”€ backend/                          # Python/Flask Backend
β”‚   β”œβ”€β”€ core/                         # βš™οΈ ML Algorithms (Pure Python/NumPy)
β”‚   β”‚   β”œβ”€β”€ neural_network.py         # Main NeuralNetwork class
β”‚   β”‚   β”œβ”€β”€ activation_functions.py   # Sigmoid, ReLU, Softmax, Linear, Threshold
β”‚   β”‚   β”œβ”€β”€ loss_functions.py         # MSE, Binary/Categorical Cross-Entropy
β”‚   β”‚   β”œβ”€β”€ optimizers.py             # GD, SGD, Momentum
β”‚   β”‚   └── __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ services/                     # πŸ”§ Business Logic Layer
β”‚   β”‚   β”œβ”€β”€ network_service.py        # Network building & management
β”‚   β”‚   β”œβ”€β”€ training_service.py       # Training orchestration & metrics
β”‚   β”‚   β”œβ”€β”€ data_service.py           # Data processing & validation
β”‚   β”‚   └── __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ api/                          # 🌐 REST API Layer
β”‚   β”‚   β”œβ”€β”€ routes/                   # API Endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ network_routes.py     # /build_network, /network_info
β”‚   β”‚   β”‚   β”œβ”€β”€ training_routes.py    # /train, /backpropagation, /update_weights
β”‚   β”‚   β”‚   β”œβ”€β”€ prediction_routes.py  # /predict, /forward_pass
β”‚   β”‚   β”‚   β”œβ”€β”€ example_routes.py     # /quick_start_binary, /quick_start_multiclass
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ middleware/               # Error Handling
β”‚   β”‚   β”‚   β”œβ”€β”€ error_handler.py
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ app.py                    # Flask Application Factory
β”‚   β”‚   └── __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ utils/                        # πŸ› οΈ Utilities
β”‚   β”‚   β”œβ”€β”€ validators.py             # Input validation
β”‚   β”‚   β”œβ”€β”€ data_processor.py         # Data transformations
β”‚   β”‚   └── __init__.py
β”‚   β”‚
β”‚   β”œβ”€β”€ config.py                     # Configuration (Dev, Prod, Test)
β”‚   └── __init__.py
β”‚
β”œβ”€β”€ frontend/                         # HTML/CSS/JavaScript Frontend
β”‚   β”œβ”€β”€ static/
β”‚   β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”‚   β”œβ”€β”€ src/                  # πŸ“ Source CSS (Modular)
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ base/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ variables.css      # CSS custom properties
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ reset.css          # CSS reset & base styles
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ layout.css         # Page layout & structure
β”‚   β”‚   β”‚   β”‚   β”‚   └── utilities.css      # Animations & modals
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”‚   β”‚   └── network-canvas.css # Network visualization styles
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ features/
β”‚   β”‚   β”‚   β”‚   β”‚   └── app-features.css   # App-specific UI styles
β”‚   β”‚   β”‚   β”‚   └── main.css          # Imports all CSS modules
β”‚   β”‚   β”‚   └── dist/                 # ⚑ Built CSS (Generated by PostCSS)
β”‚   β”‚   β”‚       └── style.css         # Compiled & minified CSS
β”‚   β”‚   β”‚
β”‚   β”‚   └── js/                       # πŸ“¦ JavaScript (ES6 Modules)
β”‚   β”‚       β”œβ”€β”€ modules/              # Feature Modules
β”‚   β”‚       β”‚   └── network/
β”‚   β”‚       β”‚       └── network-builder.js  # Interactive network visualization
β”‚   β”‚       β”œβ”€β”€ utils/                # Shared Utilities
β”‚   β”‚       β”‚   β”œβ”€β”€ api-client.js     # Centralized backend communication
β”‚   β”‚       β”‚   └── formatters.js     # Number formatting utilities
β”‚   β”‚       β”œβ”€β”€ config/
β”‚   β”‚       β”‚   └── constants.js      # Application constants
β”‚   β”‚       β”œβ”€β”€ app.js                # πŸš€ Main Entry Point (ES6 Module)
β”‚   β”‚       └── app.js.backup         # Backup of original file
β”‚   β”‚
β”‚   └── templates/                    # Jinja2 Templates
β”‚       β”œβ”€β”€ partials/
β”‚       β”‚   β”œβ”€β”€ head.html             # <head> section with CSS
β”‚       β”‚   β”œβ”€β”€ navbar.html           # Navigation bar
β”‚       β”‚   β”œβ”€β”€ hero.html             # Hero section
β”‚       β”‚   β”œβ”€β”€ steps.html            # Progress indicator
β”‚       β”‚   β”œβ”€β”€ footer.html           # Footer
β”‚       β”‚   β”œβ”€β”€ modal.html            # Modal dialogs
β”‚       β”‚   └── scripts.html          # JavaScript includes
β”‚       └── index.html                # Main page with 7 interactive tabs
β”‚
β”œβ”€β”€ .gitignore                        # Git ignore rules
β”œβ”€β”€ package.json                      # πŸ“¦ Node.js dependencies (PostCSS build)
β”œβ”€β”€ postcss.config.js                 # PostCSS configuration
β”œβ”€β”€ requirements.txt                  # 🐍 Python dependencies
β”œβ”€β”€ run.py                            # Application entry point
β”œβ”€β”€ run.bat                           # Windows batch launcher
β”œβ”€β”€ README.md                         # This file
└── CLAUDE.md                         # AI assistant project guidance

✨ Key Features

πŸ—οΈ Modern Architecture

  • Clean Architecture: Core β†’ Services β†’ API layer separation
  • SOLID Principles: Applied throughout the codebase
  • ES6 Modules: Modern JavaScript with import/export
  • PostCSS Build System: Modular CSS compiled to single optimized file
  • Design Patterns: Strategy, Factory, Facade

🧠 Neural Network Capabilities

  • Flexible Architecture: Build custom networks with any layer configuration
  • Activation Functions: Sigmoid, ReLU, Softmax, Linear, Threshold
  • Loss Functions: MSE, Binary Cross-Entropy, Categorical Cross-Entropy
  • Optimizers: Gradient Descent (GD), SGD, Momentum
  • Smart Initialization: Xavier/He initialization prevents vanishing/exploding gradients

🎨 Interactive Web Interface

  • Visual Network Builder: Drag-and-drop interface to create connections
  • Real-time Training: Watch loss decrease during training
  • 7 Interactive Tabs: Build β†’ Dataset β†’ Forward β†’ Loss β†’ Epoch β†’ Train β†’ Results
  • Responsive Design: Works on desktop and mobile (DaisyUI + Tailwind CSS)
  • Step-by-Step Workflow: Guided learning experience

πŸ“Š Visualization & Metrics

  • Network Visualization: Interactive canvas showing nodes and connections
  • Training Charts: Loss curves with Chart.js
  • Evaluation Metrics: Accuracy, Precision, Recall, F1-score
  • Confusion Matrix: Per-class performance analysis
  • Layer-by-layer Inspection: View activations at each layer

πŸ“¦ Installation

Prerequisites

  • Python 3.8+ with pip
  • Node.js 16+ with npm (for CSS build)

Setup

  1. Clone Repository

    git clone https://github.com/yourrepo/ann-from-scratch.git
    cd ann-from-scratch
  2. Install Python Dependencies

    # Recommended: Create virtual environment
    python -m venv venv
    
    # Windows
    venv\Scripts\activate
    
    # Linux/Mac
    source venv/bin/activate
    
    # Install dependencies
    pip install -r requirements.txt
  3. Install Node.js Dependencies (for CSS build)

    npm install
  4. Build CSS (first time or when CSS changes)

    npm run build:css

πŸš€ Quick Start

Run the Application

# Start Flask development server
python run.py

# Or on Windows
run.bat

Open your browser to http://localhost:5000

Using the Web Interface

  1. Build Network (Tab 1)

    • Click "Binary Classification (3-4-1)" or "Multi-Class (3-4-2)" for quick start
    • Or build custom network using visual builder
    • Click "Build Network" button
  2. Load Dataset (Tab 2)

    • Upload CSV file, or
    • Click "Load Example Dataset"
    • Click "Save Dataset & Continue"
  3. Forward Pass (Tab 3)

    • Click "Run Forward Pass"
    • View predictions and layer activations
  4. Calculate Loss (Tab 4)

    • Select loss function
    • Click "Calculate Loss"
  5. Run Epoch (Tab 5)

    • Configure learning rate and optimizer
    • Click "Run 1 Epoch"
    • See backpropagation and weight updates
  6. Train (Tab 6)

    • Set number of epochs
    • Click "Start Training"
    • Watch real-time progress
  7. View Results (Tab 7)

    • See loss curves
    • Review metrics and confusion matrix

πŸ’» Python API Usage

Basic Example

from backend.core import NeuralNetwork
import numpy as np

# Create network
network = NeuralNetwork()
network.add_layer(2, 'linear')    # 2 inputs
network.add_layer(2, 'sigmoid')   # 2 hidden neurons
network.add_layer(1, 'sigmoid')   # 1 output

# Set connections (fully connected)
network.set_connections(
    1, [[0,1], [0,1]],             # Each hidden connects to both inputs
    [[0.5,-0.3], [-0.4,0.6]],      # Weights
    [0.1, -0.2]                     # Biases
)
network.set_connections(
    2, [[0,1]],                     # Output connects to both hidden
    [[0.8,-0.5]],                   # Weights
    [0.2]                           # Bias
)

# Train (AND gate example)
X = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [0], [0], [1]])

history = network.train(
    X, y,
    epochs=500,
    learning_rate=0.5,
    optimizer='gd',
    loss_function='mse'
)

# Predict
y_pred_classes, y_pred_probs = network.predict(X)
print(f"Final Loss: {history['loss'][-1]:.6f}")
print(f"Predictions:\n{y_pred_probs}")

🌐 REST API Usage

Quick Start with Example Network

import requests

# Load example binary network
response = requests.post('http://localhost:5000/quick_start_binary')
data = response.json()

# Train with example dataset
train_response = requests.post('http://localhost:5000/train', json={
    'dataset': data['example_dataset'],
    'epochs': 1000,
    'learning_rate': 0.5,
    'optimizer': 'gd',
    'loss_function': 'binary_crossentropy'
})

result = train_response.json()
print(f"Training complete!")
print(f"Accuracy: {result['metrics']['accuracy'] * 100:.2f}%")
print(f"Final Loss: {result['final_loss']:.6f}")

API Endpoints

Network Building:

  • POST /build_network - Build custom network
  • POST /quick_start_binary - Load binary classification example (3-4-1)
  • POST /quick_start_multiclass - Load multi-class example (3-4-2)
  • GET /network_info - Get current network information

Predictions:

  • POST /predict - Make predictions on dataset
  • POST /forward_pass - Get detailed layer-by-layer activations

Training:

  • POST /train - Train network with dataset
  • POST /calculate_loss - Calculate current loss
  • POST /backpropagation - Calculate gradients (educational)
  • POST /update_weights - Single weight update step (educational)

πŸ› οΈ Technologies

Backend

  • Python 3.8+ - Core language
  • Flask - Web framework
  • NumPy - Numerical computations
  • Pandas - Data processing

Frontend

  • HTML5 - Markup
  • Tailwind CSS + DaisyUI - UI framework
  • JavaScript (ES6 Modules) - Application logic
  • Chart.js - Visualizations

Build Tools

  • PostCSS - CSS processing
  • Autoprefixer - Browser compatibility
  • cssnano - CSS minification

πŸ“ License

MIT License - Free to use for educational and commercial purposes.

πŸ™ Acknowledgments

Inspired by best practices from:

  • Robert C. Martin - Clean Architecture & SOLID Principles
  • Gang of Four - Design Patterns
  • Martin Fowler - Refactoring
  • Miguel Grinberg - Flask Web Development

πŸ“§ Support

  • Create an issue on GitHub for bugs or questions
  • See CLAUDE.md for AI assistant guidance
  • Check inline code documentation for implementation details

Built with ❀️ for Deep Learning Education

Learn by building. Understand by implementing. Master by teaching.

About

Interactive Neural Network Builder - Build and train ANN from scratch with visual interface

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •