Skip to content

About

“My project is Traffic Flow Prediction using Machine Learning. The main aim of this project is to predict traffic volume based on time and other factors like weather. I used a dataset that contains traffic data, and I applied a Linear Regression model to learn patterns in traffic flow.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚦 AI-Powered Traffic Prediction System

A complete machine learning solution for predicting traffic situation (low, normal, high, heavy) with an interactive web dashboard.

📋 Project Overview

This project includes:

✅ Complete ML Pipeline

  • Data loading and preprocessing
  • Feature engineering (14 features)
  • Random Forest classifier training
  • 100% accuracy on test data

✅ Interactive Web Dashboard

  • Real-time traffic predictions
  • Beautiful and responsive UI
  • Model accuracy display
  • Prediction confidence scores

✅ Comprehensive Visualizations

  • Confusion matrix heatmap
  • Feature importance plot
  • Traffic distribution pie chart
  • Hourly average traffic line chart

🛠️ Installation

Prerequisites

  • Python 3.7+
  • pip (Python package manager)

Step 1: Install Dependencies

cd "c:\Users\monis\Downloads\ml project"
pip install -r requirements.txt

🚀 Usage

Step 1: Train the Model (if not already trained)

python train_model.py

This will:

  • Load and preprocess the traffic data
  • Engineer 14 features
  • Train the Random Forest classifier
  • Generate visualizations (saved as PNG images)
  • Save the model and predictor for the web app

Expected Output:

  • traffic_model.pkl - Trained model
  • label_encoder.pkl - Label encoder
  • features.pkl - Feature list
  • traffic_predictor.pkl - Prediction function
  • model_accuracy.pkl - Model accuracy
  • PNG visualizations in static/ folder

Step 2: Run the Web Application

python app.py

Then open your browser and navigate to:

http://localhost:5000

Step 3: Make Predictions

  1. Dashboard Tab:

    • Enter vehicle counts (cars, bikes, buses, trucks)
    • Select hour and day of week
    • Click "Predict Traffic"
    • View predictions with confidence scores
  2. Visualizations Tab:

    • View model performance charts
    • Explore feature importance
    • Analyze traffic patterns

📊 Features

Model Features (14 total)

Raw Features:

  • CarCount - Number of cars
  • BikeCount - Number of bikes
  • BusCount - Number of buses
  • TruckCount - Number of trucks
  • Total - Total vehicles

Temporal Features:

  • Hour - Hour of day (0-23)
  • DayOfWeek_encoded - Day encoded (0-6)
  • TimePeriod_encoded - Morning/Day/Evening/Night
  • is_peak_hour - Binary: peak hours (7-9 AM, 5-7 PM)
  • is_weekend - Binary: Saturday/Sunday

Derived Features:

  • CarPercentage - Percentage of cars
  • BikePercentage - Percentage of bikes
  • BusPercentage - Percentage of buses
  • TruckPercentage - Percentage of trucks

Traffic Situations

🟢 LOW - Light traffic, smooth flow 🔵 NORMAL - Moderate traffic, acceptable congestion 🟠 HIGH - Heavy traffic, noticeable delays 🔴 HEAVY - Very heavy traffic, significant delays

📈 Model Performance

  • Accuracy: 100%
  • Model Type: Random Forest Classifier
  • Estimators: 100 trees
  • Max Depth: 15
  • Training Samples: 2,380
  • Test Samples: 596
  • Precision/Recall: All classes at 100%

Class Distribution

  • Normal: 56.1% (1,669 samples)
  • Heavy: 22.9% (682 samples)
  • Low: 10.2% (304 samples)
  • High: 10.8% (321 samples)

🎯 Making Predictions

Using the Web Dashboard

  1. Navigate to http://localhost:5000
  2. Enter traffic and time information
  3. Click "Predict Traffic"
  4. View prediction with confidence score and probabilities

Using the Python API

from train_model import TrafficPredictor
import pickle

# Load predictor
with open('traffic_predictor.pkl', 'rb') as f:
    predictor = pickle.load(f)

# Make prediction
result = predictor.predict(
    car_count=50,
    bike_count=10,
    bus_count=5,
    truck_count=5,
    hour=8,
    day_of_week='Monday'
)

print(f"Prediction: {result['predicted_situation']}")
print(f"Confidence: {result['confidence']}")
print(f"Probabilities: {result['probabilities']}")

📁 Project Structure

ml project/
├── train_model.py              # ML training pipeline
├── app.py                      # Flask web application
├── requirements.txt            # Required Python packages
├── README.md                   # This file
├── Traffic.csv                 # Original dataset
├── TrafficTwoMonth.csv         # Alternative dataset
├── traffic_model.pkl           # Trained model
├── traffic_predictor.pkl       # Predictor object
├── model_accuracy.pkl          # Model accuracy
├── label_encoder.pkl           # Label encoder
├── features.pkl                # Feature list
├── confusion_matrix.png        # Confusion matrix visualization
├── feature_importance.png      # Feature importance plot
├── traffic_distribution.png    # Traffic distribution pie chart
├── hourly_traffic.png          # Hourly traffic line chart
├── static/                     # Static assets for web app
│   ├── confusion_matrix.png
│   ├── feature_importance.png
│   ├── traffic_distribution.png
│   └── hourly_traffic.png
└── templates/                  # HTML templates
    ├── base.html              # Base template with styling
    ├── index.html             # Dashboard page
    └── visualize.html         # Visualizations page

🌐 Web Dashboard Features

Dashboard Page

✨ Real-time Prediction Form

  • Input vehicle counts with number spinners
  • Dropdown selectors for hour and day
  • Instant validation and feedback

🎯 Prediction Results

  • Traffic situation with color coding
  • Confidence score prominently displayed
  • Probability distribution for all classes
  • Input summary with key metrics

📊 Model Accuracy Badge

  • Displays 100% accuracy
  • Shows perfect predictions badge

📈 Recent Predictions History

  • Shows last 5 predictions
  • Quick reference for previous results

Visualizations Page

📊 Confusion Matrix

  • Shows prediction accuracy for each class
  • Color-coded heat map

🏆 Feature Importance Plot

  • Top 14 features ranked by importance
  • Visualizes feature contribution to predictions

📈 Traffic Distribution Pie Chart

  • Shows proportion of each traffic situation
  • Color-coded segments

⏰ Hourly Average Traffic Line Chart

  • Vehicle count trends throughout the day
  • Identifies peak traffic hours

🎨 UI Features

✨ Modern Design

  • Gradient backgrounds
  • Smooth animations
  • Responsive layout
  • Color-coded traffic situations

🎯 Interactive Elements

  • Real-time form validation
  • Instant predictions
  • Visual feedback
  • Historical tracking

📱 Responsive

  • Works on desktop
  • Tablet-friendly
  • Mobile-optimized

🔧 Troubleshooting

Port Already in Use

If port 5000 is already in use:

# In app.py, change the port:
app.run(debug=True, host='0.0.0.0', port=5001)

Model Files Missing

Regenerate model files by running:

python train_model.py

Import Errors

Install missing packages:

pip install -r requirements.txt --upgrade

📝 Example Predictions

Morning (8:00 AM, Monday):
Input: 50 cars, 10 bikes, 5 buses, 5 trucks
Output: LOW (98% confidence)

Evening Rush (5:00 PM, Friday):
Input: 120 cars, 20 bikes, 15 buses, 10 trucks
Output: NORMAL (79.92% confidence)

Night (2:00 AM, Sunday):
Input: 30 cars, 5 bikes, 3 buses, 2 trucks
Output: LOW (98% confidence)

🚀 Performance Tips

  • The model achieves 100% accuracy on the test set
  • Predictions are made in < 10ms
  • The dashboard is fully responsive
  • Visualizations are pre-generated for fast loading

📚 Technologies Used

  • ML/Data: scikit-learn, pandas, numpy
  • Web: Flask, HTML5, CSS3, JavaScript
  • Visualization: matplotlib, seaborn
  • Server: Werkzeug

📧 Support

For issues or questions, ensure:

  1. All dependencies are installed: pip install -r requirements.txt
  2. You've run the training script: python train_model.py
  3. You're accessing the correct URL: http://localhost:5000
  4. Check that no other service is using port 5000

📄 License

This project is open source and available for educational use.


Created: April 2026 Model Accuracy: 100% Classes: 4 (Low, Normal, High, Heavy) Features: 14

Happy Traffic Predicting! 🚦

About

“My project is Traffic Flow Prediction using Machine Learning. The main aim of this project is to predict traffic volume based on time and other factors like weather. I used a dataset that contains traffic data, and I applied a Linear Regression model to learn patterns in traffic flow.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages