A complete machine learning solution for predicting traffic situation (low, normal, high, heavy) with an interactive web dashboard.
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
- Python 3.7+
- pip (Python package manager)
cd "c:\Users\monis\Downloads\ml project"
pip install -r requirements.txtpython train_model.pyThis 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 modellabel_encoder.pkl- Label encoderfeatures.pkl- Feature listtraffic_predictor.pkl- Prediction functionmodel_accuracy.pkl- Model accuracy- PNG visualizations in
static/folder
python app.pyThen open your browser and navigate to:
http://localhost:5000
-
Dashboard Tab:
- Enter vehicle counts (cars, bikes, buses, trucks)
- Select hour and day of week
- Click "Predict Traffic"
- View predictions with confidence scores
-
Visualizations Tab:
- View model performance charts
- Explore feature importance
- Analyze traffic patterns
Raw Features:
CarCount- Number of carsBikeCount- Number of bikesBusCount- Number of busesTruckCount- Number of trucksTotal- Total vehicles
Temporal Features:
Hour- Hour of day (0-23)DayOfWeek_encoded- Day encoded (0-6)TimePeriod_encoded- Morning/Day/Evening/Nightis_peak_hour- Binary: peak hours (7-9 AM, 5-7 PM)is_weekend- Binary: Saturday/Sunday
Derived Features:
CarPercentage- Percentage of carsBikePercentage- Percentage of bikesBusPercentage- Percentage of busesTruckPercentage- Percentage of trucks
🟢 LOW - Light traffic, smooth flow 🔵 NORMAL - Moderate traffic, acceptable congestion 🟠 HIGH - Heavy traffic, noticeable delays 🔴 HEAVY - Very heavy traffic, significant delays
- 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%
- Normal: 56.1% (1,669 samples)
- Heavy: 22.9% (682 samples)
- Low: 10.2% (304 samples)
- High: 10.8% (321 samples)
- Navigate to http://localhost:5000
- Enter traffic and time information
- Click "Predict Traffic"
- View prediction with confidence score and probabilities
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']}")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
✨ 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
📊 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
✨ 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
If port 5000 is already in use:
# In app.py, change the port:
app.run(debug=True, host='0.0.0.0', port=5001)Regenerate model files by running:
python train_model.pyInstall missing packages:
pip install -r requirements.txt --upgradeMorning (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)
- 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
- ML/Data: scikit-learn, pandas, numpy
- Web: Flask, HTML5, CSS3, JavaScript
- Visualization: matplotlib, seaborn
- Server: Werkzeug
For issues or questions, ensure:
- All dependencies are installed:
pip install -r requirements.txt - You've run the training script:
python train_model.py - You're accessing the correct URL:
http://localhost:5000 - Check that no other service is using port 5000
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! 🚦