A beginner-friendly traffic prediction and route optimization system built with Python. This project demonstrates machine learning for traffic prediction and graph algorithms (Dijkstra & A*) for route optimization.
This system includes three main modules:
- Traffic Prediction Module - ML model (Random Forest) predicts traffic volume
- Route Optimization Module - Dijkstra & A* algorithms find optimal routes
- Dashboard Module - Interactive Streamlit UI for visualization
traffic-routing-system/
βββ data/ # Data generation and storage
β βββ generate_traffic_data.py
β βββ traffic_data.csv # Generated traffic records
β βββ road_segments.csv # Road segment metadata
βββ models/ # ML models
β βββ traffic_predictor.py # Random Forest predictor
β βββ saved/ # Saved model files
βββ algorithms/ # Route optimization algorithms
β βββ graph_builder.py # Road network graph construction
β βββ route_optimizer.py # Dijkstra & A* implementations
βββ app/ # Streamlit dashboard
β βββ dashboard.py
βββ tests/ # Unit tests
β βββ test_traffic_prediction.py
β βββ test_route_optimization.py
βββ run_system.py # Main orchestration script
βββ requirements.txt # Dependencies
βββ README.md # This file
pip install -r requirements.txtGenerate data and train the model:
python run_system.py --setupLaunch the interactive Streamlit dashboard:
python run_system.py --dashboardOr directly:
streamlit run app/dashboard.py- Dataset: 20 road segments with time-based features
- Model: Random Forest Regressor
- Features: road_id, time_of_day, day_of_week
- Target: traffic_volume (vehicles/hour)
- Target MAPE: ~20%
- Graph Representation: Nodes = intersections, Edges = roads
- Edge Weights: Based on predicted traffic and distance
- Algorithms:
- Dijkstra's Algorithm (guaranteed shortest path)
- A* Algorithm (heuristic-guided, more efficient)
- Comparison: Shows time reduction between algorithms
- Interactive route selection
- Real-time traffic visualization
- Route comparison between Dijkstra and A*
- Network graph visualization
python run_system.py --all# Setup only
python run_system.py --setup
# Routing demo
python run_system.py --demo
# Run tests
python run_system.py --test
# Evaluate model
python run_system.py --evaluate
# Launch dashboard
python run_system.py --dashboardfrom data.generate_traffic_data import TrafficDataGenerator
from models.traffic_predictor import TrafficPredictor
from algorithms.graph_builder import RoadNetworkGraph
from algorithms.route_optimizer import RouteOptimizer
# Generate data
generator = TrafficDataGenerator(n_roads=20, n_samples=2000)
traffic_df = generator.generate_dataset()
# Train model
predictor = TrafficPredictor()
predictor.train(traffic_df)
# Get prediction
traffic = predictor.predict(road_id=1, time_of_day=8, day_of_week=0)
print(f"Predicted traffic: {traffic:.0f} vehicles/hour")
# Build graph
traffic_predictions = predictor.get_all_road_predictions(8, 0, 20)
graph = RoadNetworkGraph()
graph.build_from_road_segments(roads_df, traffic_predictions)
# Find optimal route
optimizer = RouteOptimizer(graph)
path, cost = optimizer.astar(start=0, end=24)
print(f"Optimal path: {path}")
print(f"Travel time: {cost:.1f} minutes")Run all tests:
python run_system.py --testOr directly:
python -m pytest tests/The system targets the following performance metrics:
| Metric | Target | Description |
|---|---|---|
| MAPE | ~20% | Mean Absolute Percentage Error |
| MAE | Low | Mean Absolute Error (vehicles) |
| RΒ² Score | >0.7 | Coefficient of determination |
- Python 3.8+
- Pandas - Data manipulation
- NumPy - Numerical operations
- Scikit-learn - Machine Learning
- NetworkX - Graph operations
- Streamlit - Dashboard UI
- Matplotlib - Visualization
The traffic prediction module uses a Random Forest regressor to predict traffic volume based on:
- Road ID (which road segment)
- Time of day (hour 0-23)
- Day of week (0=Monday to 6=Sunday)
Traffic patterns are generated with realistic rush hour peaks and weekend variations.
The route optimization module implements:
Dijkstra's Algorithm:
- Explores all possible paths systematically
- Guaranteed to find shortest path
- Time complexity: O((V + E) log V)
A Algorithm:*
- Uses heuristic (Euclidean distance) to guide search
- More efficient than Dijkstra
- Same optimal result when heuristic is admissible
Edge weights combine distance and traffic congestion:
weight = (distance / 40) * 60 * (1 + (traffic / 500)Β²)
The Streamlit dashboard provides:
- Sidebar controls for time, day, source, and destination
- Real-time traffic predictions for all roads
- Interactive route visualization
- Algorithm comparison metrics
Modify n_roads in run_system.py:
generator = TrafficDataGenerator(n_roads=30, n_samples=2000)Edit models/traffic_predictor.py:
from sklearn.ensemble import GradientBoostingRegressor
self.model = GradientBoostingRegressor(n_estimators=100)Edit algorithms/route_optimizer.py:
def _heuristic(self, node: int, goal: int) -> float:
# Add custom logic here
return custom_distance_estimateThis is a learning project. Feel free to:
- Add more sophisticated ML models
- Implement additional algorithms (Bellman-Ford, Floyd-Warshall)
- Enhance the dashboard with real-time data
- Add map integration (OpenStreetMap, Google Maps)
This project is for educational purposes.
- Dijkstra's algorithm (Edsger W. Dijkstra, 1956)
- A* algorithm (Peter Hart, Nils Nilsson, Bertram Raphael, 1968)
- Scikit-learn team for the excellent ML library
- Streamlit team for the amazing dashboard framework