Projectreport
Projectreport
MACHINE LEARNING
A PROJECT REPORT
Submitted by
ABIRAMI A (810021104002)
LAVANYA K (810021104040)
in partial fulfilment for the award of the degree
of
BACHELOR OF ENGINEERING
in
COMPUTER SCIENCE AND ENGINEERING
SIGNATURE SIGNATURE
Dr. G. ANNAPOORANI [Link] SELVAM
HOD & Assistant Professor([Link].) Supervisor / Teaching Fellow
ABIRAMI A (810021104002)
LAVANYA K (810021104040)
We would like to thank our honorable Dean Dr. T. SENTHILKUMAR, Professor, for
having provided us with all the required facilities to complete our project without
hurdles.
We would also like to express our sincere thanks to Dr. G. ANNAPOORANI, Head
of the Department of Computer Science and Engineering, for her valuable guidance,
suggestions and constant encouragement paved the way for the successful completion
of this project work.
We would like to thank and express our deep sense of gratitude to our project guide
Dr. BLESSYSELVAM, Teaching Fellow, Department of Computer Science and
Engineering for his valuable guidance throughout the project. We also extend our thanks
to all other teaching and non-teaching staff for their encouragement and support.
We thank our beloved parents and friends for their full support in the moral
development of this project.
ABSTRACT
Road accidents pose a significant threat to public safety, resulting in numerous fatalities
each year across India. Traditional accident prediction methods often lack accuracy and real-
time applicability, making it difficult to implement effective preventive measures. This project
introduces a Machine Learning-based web application developed to predict accident severity
by analyzing key factors such as weather conditions, road infrastructure, traffic density, and
driver attributes. The model has been trained using Random Forest, Decision Trees, and
Logistic Regression algorithms, with Random Forest achieving the highest [Link]
system provides real-time risk assessments, enabling traffic authorities to take timely and
proactive actions. Automated alerts are sent to law enforcement and emergency services in
high-risk situations, thereby improving response times and reducing potential casualties.
Integration with geolocation and weather APIs further enhances the accuracy of predictions
and supports the generation of interactive heatmaps to visualize accident-prone [Link]
addition to severity prediction and alerting mechanisms, the application also suggests the safest
travel routes between user-defined start and end locations. Each route is evaluated based on
historical and real-time risk factors, and the safest route is recommended to the user, promoting
informed and safer travel [Link] project aims to contribute toward reducing road
accidents, improving traffic safety management, and strengthening emergency response
infrastructure. The system is adaptable to various regions and can be integrated into existing
traffic monitoring frameworks for broader public safety impact.
i
TABLES OF CONTENTS
ABSTRACT
1 INTRODUCTION
1. 1 Overview 1
1.2 Purpose 1
1.4 Objective 2
2 LITERATURE SURVEY
2.7 Limitation 11
3 SYSTEM MODELLING
ii
3.1.1 Data Flow Diagram Level 0 12
4 METHODOLOGY
iii
4.4.1 Working with Logiistic Regression 21
4.5.1 Accuracy 22
4.5.2 Precision 23
4.5.3 Recall 23
4.5.4 F1 Score 24
4.6 Implementation 25
6.1 Conclusion 42
A1 REFERENCES 44
A2 APPENDIX 46
A3 PLAGIARISM 61
iv
LIST OF ABBREVIATIONS
ACRONYM DESCRIPTION
CC Cubic Centimeter
ORS OpenRouteService
v
LIST OF FIGURES
FIGURE
NO. FIGURE DESCRIPTION PAGE NO.
vi
LIST OF TABLES
NO. NO.
Comparative Evaluation of Machine
5.1 38
Learning Models for Accident Severity
Prediction
vii
CHAPTER 1
INTRODUCTION
1.1 OVERVIEW
Road accidents continue to be a critical public safety concern in India, with over 1.72 lakh
lives lost in 2024 equating to nearly 471 fatalities each day, according to MoRTH data. The
majority of these victims fall within the 18 to 45 age group, highlighting the urgent need for
smarter, data-driven accident prevention solutions.
This project presents an AI-powered web application that predicts the severity of road
accidents using both live and historical datasets. Built on a foundation of 25,000 recorded
incidents, the system leverages machine learning models such as Random Forest, Decision
Tree, and Logistic Regression to achieve reliable prediction accuracy. By analyzing crucial
variables like weather conditions, road features, traffic patterns, and human behavior, the
system categorizes accidents into three risk levels: Fatal, Serious, or Minor.
1.2 PURPOSE
This project aims to develop a web-based application that leverages Machine Learning to
predict the severity of road accidents and promote safer travel. Given the alarming rise in
accident rates across India, conventional prediction systems fail to offer precise, real-time
insights needed for effective prevention. This solution uses intelligent analytics to assess risks
instantly, supporting both commuters and traffic authorities in making safety-oriented
decisions.
The proposed system is designed to:
Predict Accident Severity – It classifies accidents into categories such as Fatal,
Serious, or Slight by analyzing critical variables like weather conditions, road types,
vehicle flow, and driver-related factors.
Deliver Live Risk Insights – Real-time data from Geolocation and Weather APIs is
incorporated to improve the accuracy of severity predictions and provide location-
specific warnings.
Support Emergency Services – In the event of a high-risk prediction, the system
triggers automatic SMS alerts to notify traffic control units and emergency responders
for prompt action.
1
Improve Public Awareness – It features interactive heatmaps that highlight accident-
prone areas, assisting planners and the public in identifying hazardous routes and
improving infrastructure.
Suggest the Safest Routes – The system evaluates different route options between a
user's start and end points based on both historical and real-time accident risk data. It
then recommends the safest route, empowering users to make informed and secure
travel choices.
Traditional accident prediction systems rely on historical data analysis but fail to provide real-
time risk assessments, making them ineffective in preventing accidents. These systems do not
integrate live weather, traffic, or location data, reducing their prediction accuracy. Furthermore,
existing models are often inaccurate and generalized, as they use rule-based or statistical
approaches that lack the precision of Machine Learning algorithms. They fail to consider multiple
real-world factors, such as road type, driver behaviour, and environmental conditions, leading to
unreliable predictions.
Another major drawback is the delayed emergency response in severe accidents. Inefficient
communication between victims, bystanders, and emergency services results in slower medical
assistance, which can be life-threatening. Moreover, no automated alert system exists to instantly
notify police or ambulance services about high-risk accidents.
Moreover, the absence of connectivity with official traffic and government databases limits the
system’s ability to deliver accurate and comprehensive accident predictions. Without access to
real-time government traffic data, police records, and accident history, authorities struggle to
implement proactive road safety measures.
Furthermore, existing solutions lack visualization tools such as heatmaps or interactive maps,
which could help identify accident-prone zones. As a result, both drivers and traffic authorities
lack critical insights to avoid hazardous routes or plan safety improvements.
Existing systems also do not assist in route planning based on safety. They fail to analyze multiple
possible routes between two points, do not overlay accident data or predict real-time route risk,
and therefore cannot recommend the safest path to travelers. This increases the likelihood of users
unknowingly taking high-risk routes. In contrast, the proposed system
2
suggests the safest route by scoring each route using historical and ML-based risk data, helping
users avoid accident-prone areas.
Lastly, manual data collection and limited accessibility remain significant issues. Most current
systems depend on manual accident reporting, leading to incomplete or outdated records.
Additionally, there is no user-friendly web platform that allows people to check accident risk
levels before traveling, making it difficult for the public to make informed decisions.
1.4 OBJECTIVES
The system utilizes advanced ML algorithms to assess key factors such as weather conditions, road types,
traffic patterns, and driver behavior to determine the severity of an accident categorized as Fatal, Serious,
or Slight. Unlike conventional models, this approach incorporates real-time data from geolocation,
weather, and traffic APIs, significantly boosting the accuracy of predictions. In high-risk scenarios, the
system automatically alerts emergency responders and traffic authorities, enabling faster action and
potentially saving lives.
3
A notable feature of this application is its ability to visualize high-risk zones using interactive heatmaps,
which serve as valuable tools for city planners, authorities, and daily commuters in identifying and
avoiding dangerous areas. In addition, the system evaluates multiple travel routes based on real-time
and historical risk factors to suggest the safest possible path between any two user- defined locations,
helping travelers make informed decisions and avoid accident-prone roads.
The backend is built using Flask and integrates with Machine Learning models trained on comprehensive
accident datasets. It processes user inputs such as location, weather conditions, and time of travel, then
predicts severity using classifiers like Random Forest, Decision Tree, and Logistic Regression. The
system also connects to third-party APIs to fetch live data and uses Twilio for sending automated SMS
alerts to emergency services when a high-severity risk is detected.
With its easy-to-use web interface, users can enter specific location details and instantly receive risk
assessments and route recommendations. By combining predictive analytics, live data integration, and
intelligent route planning, this solution aims to reduce road accident fatalities, improve traffic safety,
and support faster emergency response across Indian highways and urban road.
4
CHAPTER 2
LITERATURE SURVEY
Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh, Hari
Balakrishnan, and Samuel [Link] researchers are renowned experts in fields such as
computer vision, transportation systems, deep learning, and urban data analytics. Their collective
expertise contributed to the interdisciplinary approach of combining computer science, traffic
engineering, and urban [Link] studyproposes a novel approach to traffic accident risk
prediction by developing high- resolution (5m x 5m) accident risk [Link] imagery is
analyzed using deep learning models to identify road features that influence accident risk, such
as sharp curves, poor intersections, and pedestrian [Link] trajectory data is incorporated
to understand real-time traffic behavior, including speed variations, lane changes, braking
patterns, and [Link] model is further enhanced by integrating historical accident records
to detect temporal and seasonal patterns that contribute to [Link] system combines AI-
based feature extraction, spatial analysis, and real-time data fusion to dynamically assess traffic
accident [Link] model aims to outperform traditional city-level models by offering more
precise, localized, and real-time risk [Link] availability and quality of satellite imagery,
GPS trajectories, and historical data significantly affect the system’s effectiveness, and such data
may not be consistently available across all regions. Computational complexity is high due to the
large-scale processing of high-resolution imagery and real-time trajectory data, which may hinder
large-scale or real- time [Link] model may lack generalizability across different
geographic regions with varying traffic laws, road conditions, and driver behaviors, requiring
retraining for new [Link] system does not account for driver-specific behavioral factors
(e.g., distraction, fatigue) or contextual nuances like traffic rules, signage interpretation, or real-
time weather [Link] on third-party data sources for satellite and GPS data
introduces risks related to data access, licensing, and long-term sustainability.
5
2.2 Road Accident Prediction Using Machine Learning (2024).
6
2.3 AModel of Traffic Accident Prediction Based on Convolutional Neural
Network(2017).
Lu Wenqi, Luo Dongyu, and Yan MenghuaTheir research focuses on improving accident
severity prediction using deeplearning techniques, specifically Convolutional Neural Networks
(CNNs).The study proposes the use of Convolutional Neural Networks (CNNs) for
predicting accident severity, offering improvements over conventional models like
Decision Trees and Logistic Regression, which often fall short when handling complex,
non- linear [Link] automatically learn and extract critical features from input data,
enabling the model to detect intricate patterns that traditional models may [Link] inputs
to the model include: Road conditions,Traffic volume,Historical accident records The
model's real-time processing capability allows it to provide instantaneous severity
assessments, which are valuable [Link] emergency servicesDirecting law
enforcement to high-risk incidents swiftlyAdditionally, the framework contributes to
broader traffic safety goals by [Link] in infrastructure
developmentRegulatory bodies in drafting safety lawsraffic authorities in implementing
intelligent warning systems and adaptive control strategiesThese functionalities support a
proactive approach to accident prevention and traffic management. he effectiveness of
CNNs depends heavily on large volumes of high-quality, labeled data; insufficient data
can limit model [Link]-time deployment of CNNs may face computational
resource challenges, especially in environments with limited infrastructure.
The black-box nature of deep learning models can make it difficult to interpret or explain
predictions, which might be problematic for stakeholders who require transparency.
Although CNNs can uncover complex patterns, they might overfit to specific datasets,
reducing their generalizability to new or unseen traffic scenarios.
The model primarily focuses on severity prediction and may not account for behavioral
factors such as driver alertness, compliance, or human error, which are also significant in
accident causation.
7
2.4 RoadGuard Project: Machine Learning for Accident-Prone Area
Prediction
Dr. Aakash Singh and Dr. Neha [Link] research centers on harnessing artificial
intelligence to improve road safety by identifying accident hotspots in real [Link]
authors contribute to the advancement of intelligent transportation systems by merging
AI with geographic and real-time data analytics for public safety [Link]
RoadGuard Project introduces an advanced AI-powered platform aimed at predicting
accident-prone areas by leveraging both machine learning and deep learning algorithms.
Unlike traditional models that depend solely on historical data, RoadGuard enhances
prediction accuracy by integrating real-time data streams alongside historical records.
This dual-data approach allows the system to provide more dynamic and responsive
insights into traffic [Link] platform processes a variety of critical inputs including
road surface conditions, vehicle density and traffic flow, weather patterns, and past
accident statistics. Additionally, it incorporates live data from traffic cameras, GPS
systems, and IoT- enabled sensors to provide up-to-the- minute nformation. By using
Geographic Information System (GIS) technology, the model can detect and analyze
spatial and temporal accident trends, identifying patterns that indicate high-risk
[Link] its key features, RoadGuard generates dynamic heatmaps that visualize
dangerouslocations and supports interactive dashboards for preventive action. Real- time
alerts are sent to both drivers and traffic authorities, enabling timely interventions. The
system facilitates adaptive traffic control, targeted police deployment, and strategic
signage improvements, all aimed at reducing road [Link] in collaboration
with governmental agencies, the project also produces data- driven policy insights. These
include recommendations for speed limit adjustments and the redesign of hazardous
intersections. Ultimately, RoadGuard serves as a scalable and proactive solution that
aligns with the smart city vision, integrating AI into public infrastructure to promote safer
and more intelligent transportation networks. The system's effectiveness relies on the
availability and quality of real-time data streams; in areas with poor sensor coverage or
outdated infrastructure, its predictions may be less [Link] with legacy
traffic management systems may pose logistical and technical challenges, potentially
delaying full-scale implementation.
Maintaining real-time performance requires robust computational power and network
bandwidth, which might not be feasible in rural or resource-limited [Link] the
system uses advanced analytics, it may not fully incorporate human behavioral
8
factors (e.g., driver distraction or fatigue), which are crucial in predicting and preventing
[Link] concerns may arise due to the use of GPS tracking and surveillance
footage, requiring strict data governance and user consent [Link] system’s
complexity and reliance on government cooperation could slow down adoption in areas
with bureaucratic or regulatory hurdles.
Dr. Priya Sharma and Dr. Rahul [Link] work addresses the global issue of traffic
accidents by enhancing how accident severity is detected and [Link] authors
specialize in artificial intelligence and computer vision, applying their expertise to develop
intelligent systems for real-time traffic analysis and emergency management .The research
introduces the application of Convolutional Neural Networks (CNNs) to classify the
severity of traffic accidents with greater precision. Unlike traditional algorithms such as
Decision Trees and Random Forests, which often fail to interpret complex and high-
dimensional data structures, CNNs are adept at recognizing intricate spatial patterns within
structured [Link] this approach, critical accident-related variables—such as road
surface quality, traffic volume, and weather conditions—are reformatted into a grid-based
structure, allowing CNNs to detect meaningful interactions among these features
automatically. This eliminates the dependency on manual feature engineering and
enhances the model’s ability to distinguish between varying degrees of accident severity
(e.g., fatal, serious, or minor).The CNN-based model is capable of integrating live data
streams from sources like dashcams, roadside cameras, and IoT sensors, enabling it to
perform instant evaluations of accident impact. This real-time analysis supports quicker
emergency response, smarter traffic management, and adaptive decision-making in ever-
changing driving [Link], the study suggests that the model’s
capabilities can be extended by combining CNNs with other deep learning techniques, such
as Recurrent Neural Networks (RNNs) or Transformer architectures, which are better
equipped to handle time-dependent traffic patterns and sequences, potentially improving
both prediction accuracy and context awareness. A key limitation of CNNs is the need for
large, labeled datasets to achieve optimal performance; in regions with limited data
availability, model training may be [Link] are primarily designed to capture
spatial relationships, and while effective for severity classification, they may lack temporal
context, which is critical for understanding sequences of events leading up to an
[Link] system’s real-time functionality depends heavily on continuous input from
9
high- quality video and sensor feeds, which may not be consistently available in all traffic
[Link] models can act as black boxes, making their decision-making process
hard to interpret or validate, which may be a concern for stakeholders requiring
[Link], hardware and computational requirements for real-time CNN
deployment can be demanding, especially for large-scale implementations across multiple
locations.
The research conducted by Liu et al. (2017) focuses on enhancing route planning systems
by introducing safety as a core routing criterion. The authors are recognized for their
contributions to intelligent transportation systems, with expertise in data mining, geographic
information systems (GIS), and traffic safety analysis. Their collective goal was to shift the
focus of route recommendation from speed and distance optimization to safety-conscious
[Link] et al. proposed a safety-enhanced routing framework that integrates
historical traffic accident data into navigation algorithms. Instead of selecting routes solely
based on shortest time or distance, their model assigns a safety score to each road segment
based on variables such as the number of past accidents, severity of incidents, and types of
[Link] safety scores are then incorporated into the routing engine using a weighted
cost function, which balances travel efficiency with potential risk. The routing algorithm
calculates the safest route by avoiding segments with high crash history, even if they are
faster or shorter. GIS technology and traffic incident databases were employed to visualize
and assess the safetyof potential routes in urban [Link] method allows users especially
vulnerable road users or emergency services— to select routes that significantly reduce
exposure to dangerous intersections or accident-prone [Link] the approach marks a
significant step toward safety-aware navigation, several limitations exist:Static Risk
Assessment: The method relies heavily on historical accident records, which may not reflect
current or real-time road conditions. Routes that were previously safe could become risky
due to construction or changes in traffic [Link] of Real-Time Data Integration: The
system does not account for live factors like weather, road blockages, or current traffic
congestion, which can impact road safety at any given [Link] Preference Trade-Offs:
Prioritizing safety might result in significantly longer orless convenient routes, which could
discourage users from adopting the system unless preferences can be personalized or
balanced [Link] Limitations: In areas where accident reporting is inconsistent or
incomplete, the safety scores may be inaccurate, limiting the system’s effectiveness.
10
2.7 LIMITATIONS
Integrating real-time traffic and GPS data poses challenges due to potential delays,
inconsistent data formats, or technical limitations in data transmission.
The model may not generalize effectively across diverse geographic areas, as variations
in road infrastructure, driving behavior, and local conditions can impact prediction
accuracy.
The system does not incorporate driver behavior or contextual traffic elements like road
signage or local laws, which are also critical to accurately assessing accident risk.
The safety-aware routing system is its reliance on historical accident data without
incorporating real-time road and traffic conditions.
11
CHAPTER 3
SYSTEM MODELING
The Level 0 DFD represents the core processes of the Road Accident Risk Prediction System.
Users input data like road type, vehicle details, weather, and travel locations, which is combined
with real-time and historical accident data. Machine Learning models analyze this information to
predict accident severity and send SMS alerts to authorities in high-risk cases. The system also
creates heatmaps to highlight dangerous zones and supports safer route planning. This approach
improves road safety, raises public awareness, and helps speed up emergency response.
.
12
3.1.2 DATA FLOW DIAGRAM LEVEL 1
The Level 1 Data Flow Diagram details the internal process of the Road Accident Risk
Prediction System. It starts with user inputs and external data like weather, geolocation, and past
accident records. The data undergoes collection, preprocessing, and feature extraction to prepare
for analysis. A machine learning model then evaluates the risk and predicts accident severity.
Depending on the outcome, the system sends alerts, displays heatmaps, recommends safe routes,
and updates the submission log—ensuring accurate risk assessment and safer travel decisions.
13
Figure 3.3 System Architecture for Road Accident Risk Prediction
14
.
3.3.1 DATA SOURCES
The system aggregates data from four major inputs: direct user submissions (e.g., road type,
traffic conditions), live weather updates from weather APIs, historical accident records for trend
analysis, and the user's current location via geolocation services. This multi-source input
strategyensures that bothreal-time and contextualdata contribute to a robust prediction process.
15
3.4 SYSTEM REQUIREMENT SPECIFICATION
For efficient execution of machine learning models and seamless data handling, the system
should run on the following minimum and recommended hardware setup:
[Link] Processor: At least an Intel Core i5 or AMD Ryzen 5 is required, while an Intel Core i7
or AMD Ryzen 7 is suggested for handling intensive data operations.
[Link] RAM: A minimum of 8GB is necessary, with 16GB or more recommended to
ensure smoother multitasking and quicker processing.
[Link] Storage: A 256GB SSD is the minimum needed, though a 512GB SSDor larger is
advised for faster data access and better storage management.
[Link] Operating System: Compatible with Windows 10 or Windows 11 for optimal
software support and performance.
16
CHAPTER 4
METHODOLOGY
4.1 MACHINE LEARNING
Machine learning (ML) is a field within artificial intelligence (AI) that enables systems to learn
patterns from data and make decisions or predictions without explicit programming. For road
accident risk prediction, ML helps uncover insights from past accident data and forecasts the
severity of future incidents based on inputs like weather, traffic flow, road surfaces, and vehicle
speed. This technique allows for smarter, data-informed safety strategies and early warnings.
Machine learning approaches are typically divided into three key types: supervised learning,
unsupervised learning, and semi-supervised learning, each suited to different kinds of tasks and
data availability.
17
planning and accident prevention.
18
Categorical fields (e.g., "Fog or mist") are converted into numeric values using encoding tools like
LabelEncoder. The data is cleaned to handle any missing or inconsistent entries.
3. Training the Model
The RandomForestClassifier from scikit-learn is employed.
Several decision trees are constructed using different randomly selected portions of the dataset.
Each individual tree identifies patterns between the input factors and the assigned severity label.
The combination ofpredictions fromnumerous diverse trees helps ensure the modelperforms well
across varied scenarios.
4. Making Predictions
When a user provides current traffic and weather details through the web form.
The values are formatted and encoded to align with the model’s training setup.
Every individual tree within the forest analyzes the input independently and contributes its own
prediction for the severity [Link] system aggregates these outputs and assigns the most
frequently suggested severity level as the final prediction.
Example:
200 trees predict "Slight"
90 trees predict "Serious"
10 trees predict "Fatal"
Final prediction: Slight
19
4.3.1 Working with Decision Tree Classifier
1. Data Collection
The system starts by acquiring historical accident records that contain both descriptive inputs
(conditions at the time of the incident) and their respective severity labels. Examples of inputs
include:
Weather_Conditions,Road_Surface_Conditions,Light_Conditions,Speed_Limit,Latitude&
Longitude
2. Data Preprocessing
To prepare the data for modeltraining:
Text-based categories (such as lighting or weather) are numerically encoded using tools like
LabelEncoder. Missing or inconsistent values are managed through deletion or [Link]
target variable Accident_Severity is mapped as integers 0 (Fatal), 1 (Serious), and 2 (Slight) for
classification
3. Training the Decision Tree
The refined dataset is then used to build a DecisionTreeClassifier using libraries such as scikit-
learn. The model creates a branching structure by:
Selecting features that best divide the data based on statistical measures like information gain or
Gini [Link] nodes that test a particular feature condition (e.g., “Is Speed_Limit greater
than 60?”).Continuing this logical split process until all branches terminate at a final outcome node,
which assigns a predicted severity.
4. How the Tree Makes Predictions
Once the model is trained, it interprets new user input (weather, location, road condition, etc.) by:
Starting at the topmost [Link] through different branches based on the input features
[Link] at a final node, which outputs the predicted severity category.
Example:
If Speed_Limit = 70, Weather = "Fog or Mist", Light_Condition = "No Lights", the model may
classify the result as “Fatal”.
5. Model Evaluation
The effectiveness of the model is assessed by:
Calculating accuracy, which reflects how frequently the predictions align with the true labels.
Using a confusion matrix to visualize correct and incorrect predictions across all severity levels.
Applying validation techniques that test the model on multiple data partitions to reduce
overfitting and boost reliability.
20
6. Deployment
After training, the model is stored using serialization methods such as joblib. Within the Flask
application:
The model file is loaded into memory during application startup.
When a user submits accident-related inputs, they’re processed and passed to the model.
The prediction result is then dynamically displayed on the web interface.
21
4. Model Training
The Logistic Regression algorithm is trained using the labeled historical data.
The model learns weights (coefficients) for each featureto maximize prediction accuracy.
4. Prediction
When a user submits a form:
Input data is processed to match the trained model's format.
The model computes the probability scores for each severity level.
The class with the highest probability is returned (e.g., 0.81 → Slight).
TP (True Positives)
These refer to instances where the model accurately identifies a case as a severe accident (like
Fatal or Serious), and the actual label is also severe.
Example: An accident labeled “Fatal” is correctly predicted as “Fatal” bythe model.
TN (True Negatives)
These are cases where the model properly classifies a minor accident (e.g., Slight) and the actual
outcome is also minor.
Example: An accident that is truly “Slight” is also labeled “Slight” bythe model.
FP (False Positives)
This occurs when the model mistakenly classifies a minor accident as severe.
Example: The model outputs “Serious,” but the real label is “Slight.”
FN (False Negatives)
These are situations where a severe accident is incorrectlypredicted as non-severe.
Example: The true class is “Serious,” but the model predicts “Slight.”
22
4.5.2 Precision
Precision focuses on how reliable the model's predictions are when it flags an accident as
severe. It tells us, out of all the cases where the system predicted a severe outcome (like
Fatal or Serious), how many were truly severe. A high precision score means the model
rarely makes incorrect severe predictions, helping minimize unnecessary alerts or false
alarms.
TP (True Positives)
These are the cases where the model correctly predicts an accident as severe (either Fatal or
Serious) and the actual severity is also severe.
Example: An accident is truly "Fatal", and the modelcorrectly predicts "Fatal".
FP (False Positives)
These occur when the model predicts an accident as severe, but in reality, it is not severe (i.e., it’s
Slight).
Example: The system predicts "Serious", but the true label is "Slight"
TP (True Positives)
These are accident cases where the model correctly predicts a severe outcome (Fatal or Serious),
and the actual label is also severe.
Example: The actual accident severity is "Fatal", and the modelpredicts "Fatal".
FN (False Negatives)
These occur when the model fails to recognize a severe accident and incorrectly predicts it as non-
severe (e.g., Slight).
Example: The actual severity is "Serious", but the model predicts "Slight".
23
4.5.4 F1 Score
The F1-score combines precision and recall into a single balanced metric, emphasizing the
trade-off between missed cases and incorrect alerts. It is especially useful when the dataset is
imbalanced, meaning that some severityclasses (e.g., “Fatal”) occur far less frequently than others.
Precision
Measures how many of the predicted severe accidents (e.g., “Fatal” or “Serious”) are actually
severe.
Highprecision = low false positives (fewer false alarms).
Recall
Measures how many of the actual severe accidents the model successfully detects.
High recall = low false negatives (rarely misses severe cases).
24
False Positives (FP)
The system incorrectly predicts a severe accident when it's actually non-severe (e.g., "Slight").
Example: The model predicts "Serious", but the true severity is "Slight".
Effect: Leads to unnecessary alerts or emergency actions.
True Negatives (TN)
The system correctly predicts a non-severe accident ("Slight").
When boththe actual and predicted classifications match and are labeled as "Slight”.
Effect: Helps avoid false warnings.
False Negatives (FN)
The model fails to detect a severe accident, predicting it as less serious.
Example: The actualaccident is "Serious", but the systempredicts "Slight".
Effect: Dangerous, as it may delay emergency responses.
4.6 IMPLEMENTATION
25
provides two essential data types: Series, which handles single-dimensional arrays, and
DataFrame, which manages multi-dimensional tabular [Link] structures support labeled
indexing, making structured data easy to manage. In machine learning projects like accident
severity prediction, Pandas is used for reading datasets (e.g., CSV files), handling missing values,
encoding categorical data, and preparing features for model training. Its functions streamline tasks
such as filtering, grouping, and transforming data efficiently.
Scikit-learn:
Scikit-learn is a widely used Python library that offers tools for performing machine learning
tasks like classification, regression, and clustering. It enables efficient data analysis and mining
with a user-friendly interface.
SimpleImputer:
Handles missing data byapplying simple techniques like replacing with the average, median,
most common value, or a fixed default. Example: Replaces NaN with the column average.
KNNImputer:
Uses K-Nearest Neighbors to impute missing values by finding similar rows and averaging
their [Link] advanced and effective when missing values are related to other features.
StandardScaler:
Adjusts the scale of input features by centering them around zero and scaling them to have unit
[Link] step is especially important for distance-based algorithms such as K-Nearest
Neighbors and Support Vector Machines, which are affected by differences in feature scales.
LabelEncoder:
Converts categorical values into integers. For example: “Male” → 1, “Female” → [Link] for
converting string data into machine-readable numerical format.
Missingno:
It is a dedicated library for visualizing missing values, making it easier to detect patterns and
areas with a high amount of missing data in the dataset.
[Link] (plt):
Primary visualization libraryused to create a wide range ofcharts and graphicalrepresentations
of [Link] to plot line graphs, bar charts, histograms, etc.
Seaborn (sns):
Built ontopof matplotlib. Provides high-level, visuallyattractive statisticalplots like heatmaps,
violin plots, boxplots.
26
LogisticRegression:
Imports the Logistic Regression algorithm, useful for binary or multiclass classification tasks
like predicting accident severity.
RandomForestClassifier:
Imports Random Forest, a robust and ensemble-based classification algorithm well-suited for
complex datasets.
DecisionTreeClassifier:
Imports the Decision Tree Classifier, a model that splits data into branches based on feature
conditions to predict outcomes.
Accuracy_score: Evaluates how many predictions were correct.
Classification_report:
Generates a detailed summary including precision, recall,F1-score, and support for each class
in the prediction task.
Confusion_matrix: Provides detailed insights into prediction vs actualoutcomes.
The code imports the pandas library and loads a CSV file containing cleaned road accident data using
pd.read_csv(). The dataset includes key details such as accident severity, road types, dates, and police
attendance. The [Link]() command displays the first five records, each representing an individual
accident case. There are 28 columns, making the dataset rich in features for machine learning analysis.
27
4.6.3 Data Preprocessing
28
The script loads a cleaned road accident dataset using the `pandas` library and removes
unnecessary columns such as location coordinates and special site conditions. These columns may
not contribute meaningfully to the prediction model. After dropping them, the cleaned data is
saved as a new CSV file named `cleaned_accident_data_preprocessed.csv`. The file is then made
available for download through Google Colab's `[Link]()` method for continued use or
analysis.
In this process, the "Date" and "Time" columns are combined into a single "DateTime" column
and formatted uniformly as `mm-dd-yyyy HH:MM:SS`. This ensures consistent timestamp
representation across records. The original "Date" and "Time" columns are then removed to
maintain a clean and organized dataset.
The dataset `vehicles_data.csv` is loaded and examined for basic structure and missing values.
Several attributes, including `Hit_Object_in_Carriageway`, `Hit_Object_off_Carriageway`,
and`Skidding_and_Overturning`, exhibit a high number of missing values.
29
Atotalof six columns contain missing values, which highlights the need for data preprocessing
before model training.
The dataset’s missing values are handled using the KNN imputation method, which estimates
gaps by analyzing patterns from the 5 nearest neighboring data points. Only numerical columns
are selected for imputation, and transformed values are converted back to integers if necessary. A
concluding validation step confirms that all previously missing entries have been properly
addressed.
30
Categorical features in the dataset are identified and cleaned by replacing missing entries with the
most frequent value (mode) in each column. This ensures that commonly occurring categories are
used to fill gaps, maintaining consistency in data distribution. A final summary confirms that all
31
4.6.4 Feature Extraction
The Random Forest model identified the top five most important features influencing the
predictions: Speed_limit, Vehicle_Type, Age_of_Vehicle, Engine_Capacity (CC), and
Age_of_Driver. Among these, Speed_limit has the highest impact on the model’s output, followed
by Vehicle_Type and Age_of_Vehicle. This means that changes in these features significantly
affect the model’s decisions. Highlighting these key factors helps focus on what drives the
outcomes in the dataset.
32
4.6.5 Model Selection and Training
The dataset was created by merging two DataFrames (accidents_df and vehicles_df) on the
common key ‘Accident_Index’. We selected key features like driver age, vehicle type, and
weather conditions as predictors (X), and ‘Accident_Severity’ as the target (y). The data was then
split into 80% training (34,133 samples) and 20% testing (8,534 samples) using train_test_split
for model development and evaluation. This ensures we train models on one part and test them on
unseen data for fair performance assessment.
33
A Random Forest Classifier is created with 100 decision trees, each having a maximum depth of
10, and a fixed random state for consistent results. The model is then fitted on the training data
(`X_train` and `y_train`) to identifyrelationships and make predictions for classification purposes.
We used LabelEncoder to convert categorical string columns in the training set into numeric
values, while dropping unwanted columns like ‘Accident_Index’. A mapping was created to
handle unseen labels in the test set by assigning them −1. Finally, we trained a Decision Tree
Classifier (with max_depth=10 and random_state=42) on the processed training data. This
prepares the data and builds a robust classification model for predicting accident severity.
Missing values in the training data are handled using the mean strategy with`SimpleImputer`.
The Logistic Regression model is initialized with a maximum of 1000 iterations to ensure
convergence and is trained on the processed training set. The test data is transformed using the
34
4.6.6 Model Tuning and Optimization – Hyperparameter Tuning
Hyperparameter Tuning For Random Forest
GridSearchCV is used to perform hyperparameter tuning for the Random Forest model by
testing different combinations of `n_estimators`, `max_depth`, and `min_samples_split`. It uses 5-
fold cross-validation to find the best-performing parameter set. The optimal model configuration
is then selected and printed for further use.
Hyperparameter Tuning For Decision Tree
The process performs parameter optimization for the Decision Tree by evaluating different
combinations of tree depth and the minimum number of samples required to split. The aim is to
select the configuration that yields the highest predictive accuracy through cross-validation.
Logistic Regression hyperparameters are optimized by testing various values for regularization
strength and solver methods. The model is evaluated using cross-validation to ensure stability
across different data splits. After comparing all combinations, the configuration with the best
performance is chosen to improve prediction accuracy.
35
CHAPTER 5
The Random Forest Classifier achieved an overall accuracy of 78%, indicating reliable prediction
[Link] showed strong effectiveness in detecting "Slight" accident cases, achieving a
precision of 0.79 and a recall of [Link] values show that most actual "Slight" cases were
correctly classified with minimal false positives. The weighted averages for precision (0.77),
recall (0.78), and F1-score (0.71) suggest balanced performance across all severity levels despite
class imbalance in the dataset.
36
A Logistic Regression model is trained and evaluated using accuracy, classification report, and
confusion matrix. The overall accuracy achieved is approximately 75.7%. The model performs
well in predicting the "Slight" class but struggles with "Serious" and "Fatal" cases, as shown by
low precision and recall. This indicates class imbalance or difficulty in distinguishing between
less frequent classes.
A Decision Tree model predicts accident severity (FATAL, SERIOUS, SLIGHT) after
preparing data by converting text categories to numbers and removing an unneeded identifier. It
splits data into training and testing sets, achieving 78% accuracy. The model excels at predicting
SLIGHT cases but struggles with FATAL ones, showing uneven performance across classes in
the evaluation.
37
Evaluation Metrics Accuracy Precision Recall F1-Score
Table 5.1 Comparative Evaluation of Machine Learning Models for Accident Severity
Prediction
The table highlights the performance of Random Forest, Decision Tree, and Logistic
Regression models in predicting accident severity levels: Fatal, Serious, and Slight. The Random
Forest classifier achieved the highest overall accuracy (0.7805) and showed strong effectiveness
in detecting "Slight" cases, with an F1-Score of 0.88. The Decision Tree model followed closely
with comparable performance, indicating its suitability for practical applications. Logistic
Regression, however, underperformed in identifying severe cases, with a recall of 0.00 for both
"Fatal" and "Serious" classes. These results suggest that tree-based models are particularly well-
suited for handling imbalanced datasets and can be further enhanced to improve detection of
critical outcomes.
38
OUTPUT SCREENSHOTS
Figure No. 5.2 User Input Panel for ML-Based Road Accident Severity Prediction
39
Figure No.5.3 User Submission History
40
Figure No.5.5 Heatmap Visualization
41
CHAPTER 6
CONCLUSION AND FUTURE SCOPE
6.1 CONCLUSION
The development of a machine learning-based road accident risk prediction system marks a
significant advancement toward enhancing road safety and reducing the impact of traffic-related
incidents. Throughout the project, we explored the application of supervised learning algorithms
to predict accident severity using structured datasets derived from real-world traffic scenarios in
India. By leveraging data-driven approaches, our system aims to assist authorities and the public
in making informed decisions, mitigating risks, and potentially saving lives.
This system integrates essential components of the machine learning pipeline, including data
preprocessing, feature engineering, model training, evaluation, and web-based deployment. Data
preprocessing involved handling missing values, encoding categorical variables, and
standardizing numerical features, which were critical to improving the accuracy and reliability of
the models. Key features considered included environmental factors like weather and lighting
conditions, geographical coordinates, road surface quality, speed limits, and the presence of police
officers at the accident scene. These features provided meaningful insights into the conditions
under which accidents are more likely to occur and their potential severity.
We trained multiple models, including Random Forest Classifier, Decision Tree, and Logistic
Regression, and evaluated their performance using accuracy, precision, recall, F1-score, and
confusion matrix metrics. Among these, the Random Forest model outperformed others in terms
of stability, robustness, and handling of imbalanced data classes. It demonstrated high recall in
identifying critical cases and maintained overall accuracy without overfitting. Visualization tools
like heatmaps were also incorporated to detect accident hotspots based on location data, aiding
both in public awareness and urban [Link] user interface developed using Flask and Leaflet
offers an interactive and user-friendly experience. It allows users to input traffic conditions and
receive immediate feedback on the predicted severity of a possible accident. Admin users can
manage data, review submissions, and analyze system usage. The integration of a route safety
suggestion feature using OpenRouteService adds additional value by guiding users toward safer
travel paths based on accident density analysis.
In conclusion, our system not only demonstrates the feasibility of using machine learning in road
safetyapplications but also showcases its real-world applicability. It bridges the gap between raw
42
data and actionable safety measures, emphasizing the importance of technological solutions in
addressing public health challenges. With further enhancements and the incorporation of real-time
data, this platform can evolve into a powerful tool for government agencies, city planners,
emergency responders, and everyday commuters. This project lays the foundation for future
innovations in predictive traffic analytics and highlights the potential of AI in promoting smarter
and safer cities.
43
A1 REFERENCES
2. Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh, Hari
Balakrishnan, Samuel Madden “Inferring High-Resolution Traffic Accident Risk Maps
Based on Satellite Imagery and GPS Trajectory”(2021).
3. Road Accident Analysis by Dr. Anitha Patila, Prithvish Kumbleb, Naresh Kc, and
Srihari M. Dadkhah. Published by Turkish Journal of Computer and Mathematics
Education. Vol.12 No.10(2021), 392-396.
4. Road Accident Analysis using Machine Learning by Jayesh Patil, Mandar Prabhu,
Dhaval Walavalkar, and Vivian Brian Lobo. IEEE Pune Section International
Conference 978-1-7281-9600-8/20/$31.00 ©2020 IEEE.
5. Z. Zhou, Y. Wang, X. Xie, L. Chen, and C. Zhu. Foresee urban sparse traffic accidents:
A spatiotemporal multigranularity perspective. IEEE Transactions on Knowledge and
Data Engineering, 2020.
6. K. G. Le, P. Liu, and L.-T. Lin. Traffic accident hotspot identification by integrating
kernel density estimation and spatial autocorrelation analysis: a case study International
Journal of Crashworthiness, pages 1–11, 2020.
44
11. H. Ren, Y. Song, J. Wang, Y. Hu, and J. Lei. A deep learning approach to the citywide
traffic accident risk prediction. In 2018 21st International Conference on Intelligent
Transportation Systems (ITSC), pages 3346–3351. IEEE, 2018.
14. Z. Yuan, X. Zhou, T. Yang, J. Tamerius, and R. Mantilla. Predicting traffic accidents
through heterogeneous urban data: A case study. In Proceedings of the 6th international
workshop on urban computing (UrbComp 2017), Halifax, NS, Canada,volume 14, page
10, 2017.
16. A. Najjar, S. Kaneko, and Y. Miyanaga. Combining satellite imagery and open data to
map road safety. In Proceedings of the AAAI Conference on Artificial Intelligence,
volume 31, 2017.
17. Q. Chen, X. Song, H. Yamada, and R. Shibasaki. Learning deep representation from
big and heterogeneous data for traffic accident inference. In Proceedings of the AAAI
Conference on Artificial Intelligence, volume 30, 2016.
18. L. Blincoe, T. R. Miller, E. Zaloshnja, and B. A. Lawrence. The economic and societal
impact of motor vehicle crashes,2010 (revised). Technical report, 2015.
19. A. S. Mohaymany, M. Shahri, and B. Mirbagheri. Gis-based method for detecting high-
crash-risk road segments using network kernel density estimation. Geo-spatial
Information Science, 16(2):113–119, 2013.
20. Z. Xie and J. Yan. Detecting traffic accident clusters with network kernel density
estimation and local spatial statistics: an integrated approach. Journal of transport
geography, 31:6471, 2013. Figure No.5.2 Feature Engineering
45
A2 APPENDIX
[Link]
import os
import sys
from dotenv import load_dotenv
fromflask import Flask, render_template, request, send_from_directory, jsonify, session, redirect, url_for,
flash
import pandas as pd
import joblib
import numpy as np
import [Link]
import [Link]
from [Link] import RandomForestClassifier
from [Link] import LabelEncoder
from [Link] import Client
import json
import logging
from imblearn.over_sampling import RandomOverSampler
from datetime import datetime
import csv
fromfunctools import wraps
import hashlib
# Import security features fromwerkzeug
from [Link] import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
import re
from utils.route_utils import RouteUtils
[Link](level=[Link])
logger = [Link]( name app = Flask( name , static_folder='static',
template_folder='templates')
[Link]['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///[Link]' # Using SQLite
[Link]['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'road accident' # Change this to a secure secret key
db = SQLAlchemy(app)
class User([Link]):
id = [Link]([Link], primary_key=True)
email = [Link]([Link](120), unique=True, nullable=False)
password = [Link]([Link](60), nullable=False)
role = [Link]([Link](20), default='user', nullable=False) # 'user' or 'admin'
registration_date = [Link]([Link], default=[Link])
def repr (self):
return f"User('{[Link]}', '{[Link]}')"
with app.app_context():
db.create_all()
if not [Link].filter_by(role='admin').first():
# *** CHANGE 'admin@[Link]' and 'your_admin_password_here' ***
# *** to your desired default admin credentials ***
default_admin_email = 'admin@[Link]' # Default admin email
default_admin_password = 'Abilavz@25' # Default admin password
hashed_password = generate_password_hash(default_admin_password)
default_admin = User(email=default_admin_email, password=hashed_password, role='admin')
[Link](default_admin)
[Link]()
46
print(f"Default admin user '{default_admin_email}' created."
# USERS = {
# 'admin': {
# 'password': hashlib.sha256('admin123'.encode()).hexdigest(),
# 'role': 'admin' },
# 'user': {
# 'password': hashlib.sha256('user123'.encode()).hexdigest(),
# 'role': 'user } }
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash('Please log in to access this page.', 'error')
return redirect(url_for('login'))
returnf(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash('Please log in to access this page.', 'error')
return redirect(url_for('login'))
user = [Link](session['user_id'])
if not user or [Link] != 'admin':
flash('Admin access required', 'error')
return redirect(url_for('index')) # Redirect to index or a permission denied page
return f(*args, **kwargs)
return decorated_function
@[Link]('/login', methods=['GET', 'POST'])
def login():
if [Link] == 'POST':
email = [Link]('email')
password = [Link]('password')
[Link](f"Login attempt with email: {email}")
[Link](f"Password length: {len(password) if password else 0}")
user = [Link].filter_by(email=email).first()
if user:
[Link](f"User found with email: {email}")
[Link](f"User role: {[Link]}")
[Link](f"Stored password hash: {[Link][:20]}...") # Log first 20 chars of hash
if check_password_hash([Link], password):
[Link](f"Password match for user: {email}")
session['user_id'] = [Link]
session['username'] = [Link]
session['role'] = [Link]
flash('Login successful!', 'success')
return redirect(url_for('index'))
else:
[Link](f"Password mismatch for user: {email}")
[Link]("Password verification failed. Please check if the password was entered
correctly.")
flash('Invalid email or password', 'error')
else:
[Link](f"User not found with email: {email}")
flash('Invalid email or password', 'error')
return render_template('[Link]'
47
@[Link]('/logout')
def logout():
[Link]()
flash('You havebeen logged out', 'success')
return redirect(url_for('login'))
@[Link]('/register', methods=['GET', 'POST'])
def register():
if [Link] == 'POST':
email = [Link]('email')
password = [Link]('password')
confirm_password = [Link]('confirm_password'
if len(password) < 8:
flash('Password must beat least 8 characters long.', 'error')
return render_template('[Link]')
if not [Link](r'[a-z]', password):
flash('Password must contain at least one lowercase letter.', 'error')
return render_template('[Link]')
if not [Link](r'[A-Z]', password):
flash('Password must contain at least oneuppercase letter.', 'error')
return render_template('[Link]')
if not [Link](r'\d', password):
flash('Password must contain at least one digit.', 'error')
return render_template('[Link]')
if not [Link](r'[!@#$%^&*()-_+=]', password):
flash('Password must contain at least onespecial character (!@#$%^&*()-_+=).', 'error')
return render_template('[Link]'
if password != confirm_password:
flash('Passwords do not match.', 'error')
return render_template('[Link]'
existing_user = [Link].filter_by(email=email).first()
if existing_user:
flash('Email address already exists.', 'error')
return render_template('[Link]')
hashed_password = generate_password_hash(password)
new_user = User(email=email, password=hashed_password, role='user') # Default role is use
[Link](new_user)
[Link]()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('[Link]')
USER_SUBMISSIONS_FILE = 'user_submissions.csv'
TWILIO_ACCOUNT_SID = 'ACa0f67105d457b2d92aba610aac97eee4'
TWILIO_AUTH_TOKEN = '81d0bb9af36d273a274ea22c3c91fec5'
TWILIO_PHONE_NUMBER = '+17156247714'client = Client(TWILIO_ACCOUNT_SID,
TWILIO_AUTH_TOKEN)
Try:
print("Loading CSV file...")
df = pd.read_csv('cleaned_accident_data_preprocessed (4).csv')
print("\nAccident Severity Distribution:")
print(df['Accident_Severity'].value_counts()
le = LabelEncoder()
categorical_columns = ['Accident_Severity', 'Light_Conditions', 'Road_Surface_Conditions',
'Weather_Conditions', 'Urban_or_Rural_Area']
for col in categorical_columns:
df[col] = le.fit_transform(df[col])
if col == 'Accident_Severity':
48
[Type here]
print("\nEncoded Accident Severity Mapping:")
for i, label in enumerate(le.classes_):
print(f"{i}: {label}")
features = ['Light_Conditions',
'Road_Surface_Conditions', 'Speed_limit', 'Weather_Conditions',
'Latitude', 'Longitude']
if not all(col in [Link] for col in features):
print("Error: Some required columns not found in the CSV.")
missing_cols = [col for col in features if col not in [Link]]
print(f"Missing columns: {missing_cols}")
[Link](1)
X = df[features]
y = df['Accident_Severity']
print("\nFeatures used for training:")
for feature in features:
print(f"- {feature}")
print("\nTraining new model with updated feature set...")
model = RandomForestClassifier(
n_estimators=300,
max_depth=15,
min_samples_split=3,
min_samples_leaf=1,
random_state=42,
class_weight='balanced',
criterion='entropy'
) [Link](X, y)
print("\nFeatureImportance:")
feature_importance = [Link]({
'feature': features,
'importance': model.feature_importances_
}).sort_values('importance', ascending=False)
print(feature_importance)
model_path = 'trained_model_new.sav'
[Link](model, model_path)
print(f"\nNew model saved to {model_path}")
model = [Link](model_path)
print("New model loaded successfully")
except Exception as e:
print(f"Error during model training: {e}")
print("Falling back topre-trained model...")
try:
model = [Link]('[Link]')
print("Successfully loaded pre-trained model")
except:
print("Could not load pre-trained model, using fallback model")
model = RandomForestClassifier(
n_estimators=300,
max_depth=15,
min_samples_split=3,
min_samples_leaf=1,
random_state=42,
class_weight='balanced',
criterion='entropy'
)
X_fallback = [Link]([
[5, 4, 70, 5, 0, 0], # Fatal case
49
[6, 2, 60, 2, 0, 0], # Fatal case
[4, 3, 50, 3, 0, 0], # Serious case
[7, 1, 65, 7, 0, 0], # Fatal case
[1, 5, 55, 2, 0, 0], # Serious case
[1, 1, 120, 1, 0, 0], # Fatal case
[4, 1, 40, 1, 0, 0], # Serious case
[1, 2, 45, 2, 0, 0], # Serious case
[4, 1, 35, 1, 0, 0], # Slight case
[1, 2, 40, 2, 0, 0], # Slight case
[1, 1, 45, 4, 0, 0], # Slight case
[1, 1, 30, 1, 0, 0], # Slight case
[1, 1, 20, 1, 0, 0], # Slight case
[1, 1, 25, 1, 0, 0], # Slight case
[1, 1, 15, 1, 0, 0], # Slight case
[1, 1, 10, 1, 0, 0], # Slight case
[1, 1, 30, 1, 0, 0] # Slight case
])
y_fallback = [Link]([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2])
[Link](X_fallback, y_fallback)
print("Using fallback model dueto training error")
def cal(ip):
print("DEBUG: Raw input received:", ip)
input = dict(ip)
try:
light = float(input['light'][0])
roadsc = float(input['roadsc'][0])
speedl = float(input['speedl'][0])
weather = float(input['weather'][0])
latitude = float(input['latitude'][0])
longitude= float(input['longitude'][0])
data = [Link]([light, roadsc, speedl, weather, latitude, longitude])
print("\nInput data (including lat/lon):", data)
data = [Link](1, -1)
try:
result = [Link](data)
probabilities = model.predict_proba(data)[0]
severity = {0: "Fatal", 1: "Serious", 2: "Slight"}
print("Prediction result:", severity[result[0]])
print("Prediction probabilities:", dict(zip(['Fatal', 'Serious', 'Slight'], probabilities)))
return severity[result[0]]
except Exception as e:
print(f"Prediction error: {e}")
return f"Error in prediction: {str(e)}"
except Exception as e:
print(f"Input processing error: {e}")
return f"Error processing input: {str(e)}"
def store_user_submission(form_data, prediction_result):
try:
# Define mappings for categorical features to storeas strings
weather_map = {
"1": "Fine no high winds",
"2": "Raining no high winds",
"3": "Snowing no high winds",
"4": "Fine + high winds",
"5": "Raining + high winds",
"6": "Snowing + high winds",
50
"7": "Fog or mist",
'': 'Unknown' # Handle potential missing value
}
light_map = {
"1": "Daylight",
"4": "Dark - lights lit",
"5": "Dark - lights unlit",
"6": "Dark - no lighting",
'': 'Unknown' # Handlepotential missing value}
roadsc_map = {
"1": "Dry",
"2": "Wet",
"3": "Snow",
"4": "Frost",
"5": "Flood",
"7": "Mud",
'': 'Unknown' # Handle potential missing value}
day_map = {
"1": "Sunday",
"2": "Monday",
"3": "Tuesday",
"4": "Wednesday",
"5": "Thursday",
"6": "Friday",
"7": "Saturday",
'': 'Unknown' # Handlepotential missing value }
vehicle_map = {
"1": "Pedal cycle",
"2": "Motorcycle 50cc and under",
"3": "Motorcycle 125cc and under",
"4": "Motorcycle over 125cc and up to 500cc",
"5": "Motorcycle over 500cc",
"8": "Taxi/Private hirecar",
"9": "Car",
"10": "Minibus (8 - 16 passenger seats)",
"11": "Bus or coach (17 or morepass seats)",
"18": "Tram",
"20": "Truck(Goods)",
"23": "Electric motorcycle",
'': 'Unknown' # Handle potential missing value }
gender_map = {
"1": "Male",
"2": "Female",
"3": "Unknown", # Assuming '3' is theunknown value fromthe form
'': 'Unknown' # Handle potential missing value }
submission_data = {
'Timestamp': [Link]().strftime('%Y-%m-%d %H:%M:%S'), # Changed key to match
HTML header
'Age of Driver': form_data.get('age_of_driver', ''), # Should capture the age as entered
'Vehicle Type': vehicle_map.get(form_data.get('vehicle_type', ''), form_data.get('vehicle_type', '')),
'Age of Vehicle': form_data.get('age_of_vehicle', ''), # Changed key to match HTML header
'Engine Capacity (CC)': form_data.get('engine_cc', ''), # Changed key to match HTML header
'Day of Week': day_map.get(form_data.get('day', ''), form_data.get('day', '')), # Map to string
'Weather': weather_map.get(form_data.get('weather', ''), form_data.get('weather', '')), # Changed
key to match HTML header
'Light Conditions': light_map.get(form_data.get('light', ''), form_data.get('light', '')), # Changed key
51
to match HTML header
'Road Surface': roadsc_map.get(form_data.get('roadsc', ''), form_data.get('roadsc', '')), # Changed
key to match HTML header
'Gender': gender_map.get(form_data.get('gender', ''), form_data.get('gender', '')), # Map to string
'Speed Limit': form_data.get('speedl', ''), # Changed key to match HTML header
'Latitude': form_data.get('latitude', ''),
'Longitude': form_data.get('longitude', ''),
'Predicted Severity': prediction_result if prediction_result not in ["Error in prediction: ", "Error
processing input: "] else "Prediction Error" # Store error message if prediction failed
}
ordered_keys = [
'Timestamp', 'Age of Driver', 'Vehicle Type', 'Age of Vehicle',
'Engine Capacity (CC)', 'Day of Week', 'Weather', 'Light Conditions',
'Road Surface', 'Gender', 'Speed Limit', 'Latitude', 'Longitude',
'Predicted Severity'
]
file_exists = [Link](USER_SUBMISSIONS_FILE)
with open(USER_SUBMISSIONS_FILE, 'a', newline='') as f:
writer = [Link](f, fieldnames=ordered_keys)
if not file_exists:
[Link]()
[Link](submission_data
[Link](f"Successfully stored user submission with prediction: {prediction_result}")
return True
except Exception as e:
[Link](f"Error storing user submission: {str(e)}")
return False
@[Link]('/', methods=['GET', 'POST'])
@login_required
def index():
if [Link] == 'POST':
try:
result = cal([Link])
store_user_submission([Link], result)
return result
except Exception as e:
[Link](f"Error in index route: {str(e)}")
return f"Error: {str(e)}"
return render_template('[Link]')
@[Link]('/submissions', methods=['GET'])
@admin_required
def view_submissions():
try:
if not [Link](USER_SUBMISSIONS_FILE):
return "No submissions found", 404
df = pd.read_csv(USER_SUBMISSIONS_FILE)
print("Submissions loaded:", [Link])
print([Link]())
returnrender_template('[Link]', submissions=df.to_dict('records'))
except Exception as e:
[Link](f"Error viewing submissions: {str(e)}")
return f"Error: {str(e)}", 50
@[Link]('/visual/', methods=['GET'], strict_slashes=False)
def visual():
return render_template('[Link]')
@[Link]('/leaflet-heatmap', methods=['GET'])
52
def leaflet_heatmap():
returnrender_template('leaflet_heatmap.html')
@[Link]('/sms/', methods=['POST'])def sms():
try:
res = cal([Link]) latitude = [Link]('latitude', 'N/A')
longitude = [Link]('longitude', 'N/A')
weather = weather_labels.get([Link]('weather', ''), [Link]('weather', 'Unknown'))
light = light_labels.get([Link]('light', ''), [Link]('light', 'Unknown'))
roadsc = road_labels.get([Link]('roadsc', ''), [Link]('roadsc', 'Unknown'))
[Link](f"Received form data: latitude={latitude}, longitude={longitude}, weather={weather},
light={light}, roadsc={roadsc}, severity={res}")
if res == "Fatal":
alert_msg = "FATAL ACCIDENT! Immediate emergency response required."
elif res == "Serious":
alert_msg = "Serious accident reported. Please proceed with caution."
else:
alert_msg = "Minor accident detected. Bealert on the road."
message_body = (
f"{alert_msg}\n"
f"Severity: {res}\n"
f"Location: [Link]
f"Weather: {weather}\n"
f"Light Condition: {light}\n"
f"Road Condition: {roadsc}"
)
phone_number = "+918667334079"
message = [Link](
body=message_body,
from_=TWILIO_PHONE_NUMBER,
to=phone_number
)
53
import os
print("Current working directory:", [Link]())
print("File exists:", [Link]('cleaned_accident_data_with_location.csv')) try:
[Link]("Attempting to load heatmap data...")
df = pd.read_csv('cleaned_accident_data_with_location.csv')
[Link](f"Successfully loaded data with {len(df)} rows")
(df['Latitude'] >= 6.0) & (df['Latitude'] <= 38.0) &
(df['Longitude'] >= 68.0) & (df['Longitude'] <= 98.0)
] X = india_df[[
"Age_of_Driver",
"Vehicle_Type",
"Age_of_Vehicle",
"Engine_Capacity_(CC)",
"Day_of_Week",
"Weather",
"Road_Surface",
"Light",
"Gender",
"Speed_limit",
"Latitude",
"Longitude"
]]
severity_weights = {
'Fatal': 1.0,
'Serious': 0.6,
'Slight': 0.2
}
heatmap_data = []
for index, row in india_df.iterrows():
try:
if [Link](row['Latitude']) and [Link](row['Longitude']):
weight = severity_weights.get(row['Accident_Severity'], 0.2)
heatmap_data.append({
'location': {
'lat': float(row['Latitude']),
'lng': float(row['Longitude'])
},
'weight': weight })
except Exception as e:
[Link](f"Error processing row {index}: {str(e)}")
continue
[Link](f"Generated {len(heatmap_data)} heatmap points")
return jsonify(heatmap_data)
except FileNotFoundError:
[Link]("Error: Data file not found")
return jsonify({'error': 'Data file not found'}), 404
except Exception as e:
[Link](f"Error generating heatmap data: {str(e)}")
return jsonify({'error': str(e)}), 50
weather_labels = {
"1": "Fine no high winds",
"2": "Raining no high winds",
"3": "Snowing no high winds",
"4": "Fine + high winds",
"5": "Raining + high winds",
"6": "Snowing + high winds",
54
"7": "Fog or mist"
}
light_labels = {
"1":"Daylight",
"4": "Dark - lights lit",
"5": "Dark - lights unlit",
"6": "Dark - no lighting"
}
road_labels = {
"1": "Dry",
"2": "Wet",
"3": "Snow",
"4": "Frost",
"5": "Flood",
"7": "Mud"
}
try:
accident_data_path = [Link]([Link]( file ),
'cleaned_accident_data_with_location.csv')
accident_data = pd.read_csv(accident_data_path).to_dict('records')
except Exception as e:
accident_data = []
[Link](f"Could not load accident data: {e}")
def get_accident_data_for_area(min_lat, max_lat, min_lon, max_lon):
if accident_data:
# Simplefiltering (can be optimized) - assuming accident_data has 'latitude' and 'longitude' keys
filtered_data = [
acc for acc in accident_data
if [Link]('Latitude') is not Noneand [Link]('Longitude') is not Noneand \
min_lat <= acc['Latitude'] <= max_lat and \
min_lon <= acc['Longitude'] <= max_lon
]
return {'accidents': filtered_data}
return {'accidents': []}
route_utils = RouteUtils(
@[Link]('/api/safest-route', methods=['POST'])
def api_safest_route():
try:
data = request.get_json()
start_location = [Link]('start')
end_location = [Link]('end')
if not start_location or not end_location:
return jsonify({'error': 'Start and end locations arerequired'}), 400
start_coords = route_utils.geocode_address(start_location)
end_coords = route_utils.geocode_address(end_location
api_key = [Link]('OPENROUTE_API_KEY')
if not api_key:
return jsonify({'error': 'OpenRoute API key not configured'}), 500
routes = route_utils.get_route_alternatives(start_coords, end_coords, api_key)
if not routes:
return jsonify({'error': 'No routes found'}), 404
accident_data = get_accident_data_for_area(
min(start_coords[0], end_coords[0]),
max(start_coords[0], end_coords[0]),
min(start_coords[1], end_coords[1]),
max(start_coords[1], end_coords[1])
55
)
safest_route = None
min_score= float('inf') for route in routes:
try:
coordinates = [[pt[1], pt[0]] for pt in route['geometry']['coordinates']
safety_analysis = route_utils.analyze_route_safety(coordinates, {
'Light_Conditions': 1, # Default to daylight
'Road_Surface_Conditions': 1, # Default to dry
'Speed_limit': 30, # Default speed limit
'Weather_Conditions': 1 # Default to fine weather
})
[Link]({
'safety_score': safety_analysis['overall_risk_score'],
'risk_level': safety_analysis['risk_level'],
'accident_count': safety_analysis['historical_analysis']['accident_count'],
'accident_density': safety_analysis['historical_analysis']['accident_density'],
'recommendations': safety_analysis['recommendations'],
'risk_segments': safety_analysis['risk_segments']
} if safety_analysis['overall_risk_score'] < min_score:
min_score = safety_analysis['overall_risk_score']
safest_route = route
except Exception as e:
[Link](f"Error analyzing route safety: {e}")
continu
if not safest_route:
return jsonify({'error': 'Could not determine safest route'}), 500
return jsonify({
'routes': routes,
'safest_route': safest_route,
'start_coords': start_coords,
'end_coords': end_coords
})
except Exception as e:
[Link](f"Error in /api/safest-route: {e}")
return jsonify({'error': str(e)}), 500
@[Link]('/safest-route')
@login_required
def safest_route_page():
returnrender_template('[Link]')
@[Link]('/admin')
@admin_required
def admin_dashboard():
users = [Link]() # Fetch all users fromthe database
return render_template('[Link]', users=users)
@[Link]('/reset-admin-password', methods=['GET'])
def reset_admin_password():
try:
with app.app_context():
[Link]("Starting admin password reset process..."
existing_admins = [Link].filter_by(email='admin@[Link]').all()
if existing_admins:
[Link](f"Found {len(existing_admins)} existing admin users to delete")
for admin in existing_admins:
[Link](admin)
[Link]()
[Link]("Successfully deleted existing admin users")
56
else:
[Link]("No existing admin users found to delete")
admin_email = 'admin@[Link]'
admin_password = 'Abilavz@25' # This is thepassword that will be hashed and store
[Link](f"Creating new admin user with email: {admin_email}")
hashed_password = generate_password_hash(admin_password, method='pbkdf2:sha256')
[Link]("Password hashed successfully")
new_admin = User(email=admin_email, password=hashed_password, role='admin')
[Link](new_admin)
[Link]()
verify_admin = [Link].filter_by(email=admin_email).first()
if verify_admin:
[Link]("Successfully verified new admin user creation")
[Link](f"Admin user role: {verify_admin.role}") if
check_password_hash(verify_admin.password, admin_password):
[Link]("Password verification successful")
else:
[Link]("Password verification failed after creation!")
else:
[Link]("Failed to verify admin user creation!")
return """
Admin password has been reset successfully!<br>
You can now login with:<br>
Email: admin@[Link]<br>
Password: Abilavz@25<br>
<br>
Please try logging in now. If you still have issues, check theserver logs.
""", 200
except Exception as e:
[Link](f"Error resetting adminpassword: {str(e)}")
return f"Error resetting admin password: {str(e)}", 500
@[Link]('/delete_submission/<int:submission_id>', methods=['POST'])
@admin_required
def delete_submission(submission_id)
try:
if not [Link](USER_SUBMISSIONS_FILE):
flash('No submissions found.', 'error')
return redirect(url_for('view_submissions')
df = pd.read_csv(USER_SUBMISSIONS_FILE)
if submission_id < 0 or submission_id >= len(df):
flash('Submission not found.', 'error')
returnredirect(url_for('view_submissions'))
df = [Link](submission_id).reset_index(drop=True) # reset_index to renumber after drop
df.to_csv(USER_SUBMISSIONS_FILE, index=False
flash('Submission deleted successfully.', 'success')
except Exception as e:
flash(f'Error deleting submission: {str(e)}', 'error'
return redirect(url_for('view_submissions'))
if name == ' main ':
[Link](host='[Link]', port=4000, ssl_context=('[Link]', '[Link]'), debug=True)
Test Cases
import pandas as pd
import numpy as np
from main import cal
[Link] import RandomForestClassifier
57
import joblib
import os
from [Link] import LabelEncoder
def run_tests():
print("\nRunning Test Cases...\n")
real_world_case = {
'light': ['1'], # Daylight
'roadsc': ['1'], # Dry
'speedl': ['10'], # Low speed
'weather': ['1'], # Fine no high winds
'latitude': ['11.0168445'],
'longitude': ['76.9558321']
}
fatal_cases = [
{
'light': ['6'], # Dark - no lighting
'roadsc': ['5'], # Flood
'speedl': ['70'], # High speed
'weather': ['7'], # Fog or mist
'latitude': ['22.9734'],
'longitude': ['78.6569']
}
] *5
serious_cases = [
{
'light': ['4'], # Dark - lights lit
'roadsc': ['2'], # Wet
'speedl': ['40'], # Moderate speed
'weather': ['1'], # Fine no high winds
'latitude': ['22.9734'],
'longitude': ['78.6569']
}
] *5
slight_cases = [
{
'light': ['1'], # Daylight
'roadsc': ['1'], # Dry
'speedl': ['10'], # Low speed
'weather': ['1'], # Fine no high winds
'latitude': ['22.9734'],
'longitude': ['78.6569']
}
] *5
edge_cases = [
# Edge Case 1: Fatal
{
'input': {
'light': ['6'],
'roadsc': ['5'],
'speedl': ['70'],
'weather': ['7'],
'latitude': ['22.9734'],
58
'longitude': ['78.6569']
},
'expected': 'Fatal'
},
# Edge Case 2: Fatal
{
'input': {
'light': ['6'],
'roadsc': ['5'],
'speedl': ['70'],
'weather': ['7'],
'latitude': ['22.9734'],
'longitude': ['78.6569']
},
'expected': 'Fatal' },
# Edge Case 3: Serious
{
'input': {
'light': ['4'],
'roadsc': ['2'],
'speedl': ['40'],
'weather': ['1'],
'latitude': ['22.9734'],
'longitude': ['78.6569']
}, 'expected': 'Serious' },
# Edge Case 4: Serious (adjusted speed)
{
'input': {
'light': ['4'],
'roadsc': ['2'],
'speedl': ['40'], # Changed from 34 to 40 to align with Serious
'weather': ['1'],
'latitude': ['22.9734'],
'longitude': ['78.6569']
}, 'expected': 'Serious },
# Edge Case 5: Slight
{
'input': {
'light': ['1'],
'roadsc': ['1'],
'speedl': ['10'],
'weather': ['1'],
'latitude': ['22.9734'],
'longitude': ['78.6569']
}, 'expected': 'Slight'} ]
all_cases = [
("Real World", [real_world_case]),
("Fatal", fatal_cases),
("Serious", serious_cases),
("Slight", slight_cases),
("Edge", edge_cases)]
total_cases = 0
passed_cases = 0
for severity, cases in all_cases:
for i, test_case in enumerate(cases, 1):
59
# Handle edge cases differently
if severity == "Edge":
test_input = test_case['input']
expected = test_case['expected']
else:
test_input = test_case
expected = 'Slight' if severity == "Real World" else severity
print(f"\nTesting: {severity} Case {i}")
print(f"Input: {test_input}")
print(f"Expected: {expected}")
try:
result = cal(test_input)
print(f"Actual: Snowden: {result}")
if result == expected:
print("PASSED")
passed_cases += 1
else:
print("FAILED")
total_cases += 1
except Exception as e:
print(f"ERROR: {str(e)}")
total_cases += 1
print("\nTest Summary:")
print(f"Total Cases: {total_cases}")
print(f"Passed: {passed_cases}")
print(f"Failed: {total_cases - passed_cases}")
print(f"Success Rate: {(passed_cases/total_cases)*100:.2f}%"
if name == " main ":
run_tests()
60
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 953 Total Characters: 6880 Plagiarized Sentences: 0 Unique Sentences: 45 (100%)
CHAPTER 1
INTRODUCTION
1.1 OVERVIEW
Road accidents continue to be a critical public safety concern in India, with over 1.72 lakh lives lost in
2024 equating to nearly 471 fatalities each day, according to MoRTH data. Themajority of these
victims fall within the 18 to 45 age group, highlighting the urgent need for smarter, data-driven
accident prevention solutions.
This project presents an AI-powered web application that predicts the severity of road accidents using
both live and historical datasets. Built on a foundation of 25,000 recorded incidents, the system
leverages machinelearningmodels such as Random Forest, Decision Tree, and Logistic Regression to
achieve reliable prediction accuracy. By analyzing crucial variables like weather conditions, road
features, traf c patterns, and human behavior, the system categorizes accidents into three risk levels:
Fatal, Serious, or Minor.
1.2 PURPOSE
This project aims to develop a web-based application that leverages Machine Learning to predict the
severity of road accidents and promote safer travel. Given the alarming risein accident rates across
India, conventional prediction systems fail to offer precise, real-timeinsights needed for effective
prevention. This solution uses intelligent analytics to assess risks instantly, supporting both
commuters and traf c authorities in making safety-oriented decisions.
The proposed system is designed to:
• Predict Accident Severity – It classi es accidents into categories such as Fatal, Serious, or Slight by
analyzing critical variables likeweather conditions, road types, vehicle ow, and driver-related factors.
• Deliver Live Risk Insights – Real-time data from Geolocation andWeather APIs is incorporated to
improve the accuracy of severity predictions and provide location-speci c warnings.
• Support Emergency Services – In the event of a high-risk prediction, the system triggers automatic
SMS alerts to notify traf c control units and emergency responders for prompt action.
• Improve Public Awareness – It features interactive heatmaps that highlight accident-prone areas,
assisting planners and the public in identifying hazardous routes and improving infrastructure.
• Suggest the Safest Routes – The system evaluates different route options between a user's start and
end points based on both historical and real-time accident risk data. It then recommends the safest
route, empowering users to make informed and secure travel choices.
61
Page 1 of 3
Traditional accident prediction systems rely on historical data analysis but fail to provide real-timerisk
assessments, making them ineffective in preventing accidents. These systems do not integrate live
weather, traf c, or location data, reducing their prediction accuracy. Furthermore, existing models are
often inaccurate and generalized, as they use rule-based or statistical approaches that lack the
precision of Machine Learning algorithms. They fail to consider multiple real-world factors, such as
road type, driver behaviour, and environmental conditions, leading to unreliable predictions.
Another major drawback is the delayed emergency response in severe accidents. Inef cient
communication between victims, bystanders, and emergency services results in slower medical
assistance, which can be life-threatening. Moreover, no automated alert system exists to instantly
notify police or ambulance services about high-risk accidents.
Moreover, the absence of connectivity with of cial traf c and government databases limits the
system’s ability to deliver accurate and comprehensive accident [Link] access to real-
time government traf c data, police records, and accident history, authorities struggle to implement
proactive road safety measures.
Furthermore, existing solutions lack visualization tools such as heatmaps or interactive maps, which
could help identify accident-prone zones. As a result, both drivers and traf c authorities lack critical
insights to avoid hazardous routes or plan safety improvements.
Existing systems also do not assist in route planning based on safety. They fail to analyze multiple
possible routes between two points, do not overlay accident data or predict real-timeroute risk, and
therefore cannot recommend the safest path to travelers. This increases the likelihood of users
unknowingly taking high-risk routes. In contrast, the proposed system suggests the safest route by
scoring each route using historical and ML-based risk data, helping users avoid accident-prone areas.
Lastly, manual data collection and limited accessibility remain signi cant issues. Most current systems
depend on manual accident reporting, leading to incomplete or outdated records. Additionally, there is
no user-friendly web platform that allows people to check accident risk levels beforetraveling, making
it dif cult for the public to make informed decisions.
1.4 OBJECTIVES
• Develop a Machine Learning-based web application to predict road accident severity in India.
Analyze key accident factors such as weather, road conditions, vehicle type, and driver characteristics.
• Assist traf c authorities in identifying accident-proneareas and taking preventivemeasures.
• Suggest the safest travel routes between user-de ned start and end locations. Each route is
evaluated using historical and real-time risk data, and the safest route is recommended to promote
safer travel decisions.
• Adapt the model for Indian cities and states, utilizing accident data from Indian government sources
for improved regional accuracy and applicability.
1.5 OVERALL DESCRIPTION
Road accidents remain a major public safety concern, causing numerous fatalities and injuries each
year. Traditional systems rely on outdated data and manual reporting, often lacking the speed and
accuracy needed for timely intervention. This project presents a Machine Learning-based web
application that predicts accident severity—categorized as Fatal, Serious, or Slight—using key factors
like weather, road type, traf c patterns, and driver behavior. By integrating real-time data from
geolocation, weather, and traf c APIs, the system signi cantly improves prediction accuracy and
automatically alerts emergency responders and authorities in high-risk scenarios.
A key feature of the application is its interactive heatmap, which visualizes accident-prone zones to
help city planners, authorities, and commuters make safer decisions. It also evaluates multiple travel
routes, offering users the safest path between two points based on real-time and historical risk data.
With a user-friendly interface, the platform provides instant risk assessments and route
recommendations, aiming to reduce fatalities, enhance traf c safety, and enable quicker emergency
response across Indian roads.
Page 2 of 3
No Plagiarism Found
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 261 Total Characters: 2015 Plagiarized Sentences: 0 Unique Sentences: 12 (100%)
ABSTRACT
Road accidents pose a signi cant threat to public safety, resulting in numerous fatalities each year
across India.
Traditional accident prediction methods often lack accuracy and real-time applicability, making it
dif cult to implement effective preventivemeasures. This project introduces a Machine Learning-based
web application developed to predict accident severity by analyzing key factors such as weather
conditions, road infrastructure, traf c density, and driver attributes. Themodel has been trained using
Random Forest, Decision Trees, and Logistic Regression algorithms, with Random Forest achieving the
highest accuracy.
The system provides real-time risk assessments, enabling traf c authorities to take timely and
proactive actions. Automated alerts are sent to law enforcement and emergency services in high-risk
situations, thereby improving response times and reducing potential casualties. Integration with
geolocation and weather APIs further enhances the accuracy of predictions and supports the
generation of interactive heatmaps to visualize accident-prone areas.
In addition to severity prediction and alerting mechanisms, the application also suggests the safest
travel routes between user-de ned start and end locations. Each route is evaluated based on historical
and real-time risk factors, and the safest route is recommended to the user, promoting informed and
safer travel decisions.
This project aims to contribute toward reducing road accidents, improving traf c safety management,
and strengthening emergency response infrastructure. The system is adaptable to various regions and
can be integrated into existing traf c monitoring frameworks for broader public safety impact.
KEYWORDS:
Road Accident Prediction, Machine Learning (ML), Accident Severity, Traf c Safety, Emergency
Response, Real-timePrediction, Risk Assessment, Geolocation API,Weather Conditions, Traf c Data,
Driver Characteristics, Web Application, Automated Alerts, Heatmap.
Page 1 of 2
No Plagiarism Found
Page 2 of 2
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
2%
Exact Plagiarized
5% 95%
2%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 902 Total Characters: 6630 Plagiarized Sentences: 2.15 Unique Sentences: 40.85 (95%)
CHAPTER 2
LITERATURE SURVEY
2.1 Inferring High-Resolution Traf c Accident Risk Maps Based on Satellite Imagery and GPS
Trajectory (2021).
Authors : Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh, Hari
Balakrishnan, and Samuel Madden.
Theseresearchers arerenowned experts in elds such as computer vision, transportationsystems,
deep learning, and urban data analytics. Their collective expertise contributed to the interdisciplinary
approach of combining computer science, traf c engineering, and urban planning.
Methodology:
• The study proposes a novel approach to traf c accident risk prediction by developing high-resolution
(5m x 5m) accident risk maps.
• Satellite imagery is analyzed using deep learning models to identify road features that in uence
accident risk, such as sharp curves, poor intersections, and pedestrian crossings.
• GPS trajectory data is incorporated to understand real-timetraf c behavior, including speed
variations, lane changes, braking patterns, and congestion.
• Themodel is further enhanced by integrating historical accident records to detect temporal and
seasonal patterns that contribute to accidents.
• The system combines AI-based feature extraction, spatial analysis, and real-time data fusion to
dynamically assess traf c accident risks.
• The model aims to outperform traditional city-level models by offeringmore precise, localized, and
real-time risk assessments.
Drawbacks:
• The availability and quality of satelliteimagery, GPS trajectories, and historical data signi cantly
affect the system’s effectiveness, and such data may not be consistently available across all regions.
• Computational complexity is high due to the large-scale processing of high-resolution imagery and
real-time trajectory data, which may hinder large-scale or real-time implementation.
• Thesystem does not account for driver-speci c behavioral factors (e.g., distraction, fatigue) or
contextual nuances like traf c rules, signage interpretation, or real-time weather changes.
• Dependence on third-party data sources for satellite and GPS data introduces risks related to data
access, licensing, and long-term sustainability.
Page 1 of 3
2.2 Road Accident Prediction Using Machine Learning(2024).
Methodology:
• Thestudy proposes theuse of Convolutional Neural Networks (CNNs) for predicting
accident severity, offering improvements over conventional models like Decision Trees and Logistic
Regression, which often fall short when handling complex, non-linear data.
• CNNs automatically learn and extract critical features from input data, enabling themodel to detect
intricate patterns that traditional models may miss.
• Key inputs to themodel include:
Road conditions
Traf c volume
Historical accident records
• The model's real-time processing capability allows it to provide instantaneous severity assessments,
which are valuable for:
Prioritizing emergency services
• Additionally, theframework contributes to broader traf c safety goals by aiding:
Policymakers in infrastructure development
Regulatory bodies in drafting safety laws
Traf c authorities in implementing intelligent warning systems and adaptive control strategies
Page 2 of 3
Drawbacks:
• he effectiveness of CNNs depends heavily on largevolumes of high-quality, labeled data; insuf cient
data can limit model performance.
• Real-time deployment of CNNs may face computational resource challenges, especially in
environments with limited infrastructure.
• The black-box nature of deep learning models can make it dif cult to interpret or explain predictions,
which might be problematic for stakeholders who require transparency.
• Although CNNs can uncover complex patterns, they might over t to speci c datasets, reducing their
generalizability to new or unseen traf c scenarios.
• The model primarilyfocuses on severity prediction andmay not account for behavioral factors such
as driver alertness, compliance, or human error, which are also signi cant in accident causation.
Plagiarized Sources
Authors : Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh,
Hari Balakrishnan, and Samuel Madden.
[Link]
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
2%
Exact Plagiarized
5% 95%
2%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 902 Total Characters: 6630 Plagiarized Sentences: 2.15 Unique Sentences: 40.85 (95%)
CHAPTER 2
LITERATURE SURVEY
2.1 Inferring High-Resolution Traf c Accident Risk Maps Based on Satellite Imagery and GPS
Trajectory (2021).
Authors : Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh, Hari
Balakrishnan, and Samuel Madden.
Theseresearchers arerenowned experts in elds such as computer vision, transportationsystems,
deep learning, and urban data analytics. Their collective expertise contributed to the interdisciplinary
approach of combining computer science, traf c engineering, and urban planning.
Methodology:
• The study proposes a novel approach to traf c accident risk prediction by developing high-resolution
(5m x 5m) accident risk maps.
• Satellite imagery is analyzed using deep learning models to identify road features that in uence
accident risk, such as sharp curves, poor intersections, and pedestrian crossings.
• GPS trajectory data is incorporated to understand real-timetraf c behavior, including speed
variations, lane changes, braking patterns, and congestion.
• Themodel is further enhanced by integrating historical accident records to detect temporal and
seasonal patterns that contribute to accidents.
• The system combines AI-based feature extraction, spatial analysis, and real-time data fusion to
dynamically assess traf c accident risks.
• The model aims to outperform traditional city-level models by offeringmore precise, localized, and
real-time risk assessments.
Drawbacks:
• The availability and quality of satelliteimagery, GPS trajectories, and historical data signi cantly
affect the system’s effectiveness, and such data may not be consistently available across all regions.
• Computational complexity is high due to the large-scale processing of high-resolution imagery and
real-time trajectory data, which may hinder large-scale or real-time implementation.
• Thesystem does not account for driver-speci c behavioral factors (e.g., distraction, fatigue) or
contextual nuances like traf c rules, signage interpretation, or real-time weather changes.
• Dependence on third-party data sources for satellite and GPS data introduces risks related to data
access, licensing, and long-term sustainability.
Page 1 of 3
2.2 Road Accident Prediction Using Machine Learning(2024).
Methodology:
• Thestudy proposes theuse of Convolutional Neural Networks (CNNs) for predicting
accident severity, offering improvements over conventional models like Decision Trees and Logistic
Regression, which often fall short when handling complex, non-linear data.
• CNNs automatically learn and extract critical features from input data, enabling themodel to detect
intricate patterns that traditional models may miss.
• Key inputs to themodel include:
Road conditions
Traf c volume
Historical accident records
• The model's real-time processing capability allows it to provide instantaneous severity assessments,
which are valuable for:
Prioritizing emergency services
• Additionally, theframework contributes to broader traf c safety goals by aiding:
Policymakers in infrastructure development
Regulatory bodies in drafting safety laws
Traf c authorities in implementing intelligent warning systems and adaptive control strategies
Page 2 of 3
Drawbacks:
• he effectiveness of CNNs depends heavily on largevolumes of high-quality, labeled data; insuf cient
data can limit model performance.
• Real-time deployment of CNNs may face computational resource challenges, especially in
environments with limited infrastructure.
• The black-box nature of deep learning models can make it dif cult to interpret or explain predictions,
which might be problematic for stakeholders who require transparency.
• Although CNNs can uncover complex patterns, they might over t to speci c datasets, reducing their
generalizability to new or unseen traf c scenarios.
• The model primarilyfocuses on severity prediction andmay not account for behavioral factors such
as driver alertness, compliance, or human error, which are also signi cant in accident causation.
Plagiarized Sources
Authors : Songtao He, Mohammad Amin Sadeghi, Sanjay Chawla, Mohammad Alizadeh,
Hari Balakrishnan, and Samuel Madden.
[Link]
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 928 Total Characters: 6640 Plagiarized Sentences: 0 Unique Sentences: 43 (100%)
CHAPTER 3
SYSTEM MODELING
3.1 DATA FLOW DIAGRAM
The Data Flow Diagram (DFD) of the Road Accident Risk Prediction System illustrates how user inputs
and external data sources are processed to assess accident severity. Users enter details such as
weather, road type, and vehicle category, which are combined with historical accident records,
geolocation data, and weather API inputs. A Random Forest model analyzes this data to predict the
risk level. In case of high risk, the system sends alerts to authorities and displays heatmaps of danger
zones. It also helps users choose safer travel routes by evaluating current and past risk factors,
enhancing road safety and emergency response.
3.1.1 DATA FLOW DIAGRAM LEVEL 0
The Level 0 DFD represents the core processes of the Road Accident Risk Prediction System. Users
input data like road type, vehicle details, weather, and travel locations, which is combined with real-
time and historical accident data. Machine Learning models analyze this information to predict accident
severity and send SMS alerts to authorities in high-risk cases. The system also creates heatmaps to
highlight dangerous zones and supports safer route planning. This approach improves road safety,
raises public awareness, and helps speed up emergency response.
3.1.2 DATA FLOW DIAGRAM LEVEL 1
The Level 1 Data Flow Diagram details the internal process of the Road Accident Risk Prediction
System. It starts with user inputs and external data like weather, geolocation, and past accident
records. The data undergoes collection, preprocessing, and feature extraction to prepare for analysis. A
machine learning model then evaluates the risk and predicts accident severity. Depending on the
outcome, the system sends alerts, displays heatmaps, recommends safe routes, and updates the
submission log—ensuring accurate risk assessment and safer travel decisions.
3.2 SYSTEM ARCHITECTURE
The architecture of the Road Accident Risk Prediction System follows a structured data pipeline,
beginning with inputs from users, weather APIs, historical accident data, and geolocation. This data
ows into a preprocessing unit that ensures accuracy and consistency. Feature engineering then
extracts keyinsights, which areanalyzed using Random Forest, Decision Tree, and Logistic Regression
to select the best-performing model. The nal model processes the re ned data to predict accident
severity. Based on results, the system activates alerts, displays heatmaps, suggests safer routes, and
updates user history—enabling real-time responses and improving road safety.
3.3 PROCESS DESCRIPTION
Page 1 of 3
The system architecturepresented in thediagram showcases a comprehensive data pipelinefor
predicting road accident risks through a logical ow from data collection to actionable outputs.
.
3.3.1 DATASOURCES
The system aggregates data from four major inputs: direct user submissions (e.g., road type, traf c
conditions), live weather updates from weather APIs, historical accident records for trend analysis, and
the user's current location via geolocation services. This multi-source input strategy ensures that both
real-time and contextual data contribute to a robust prediction process.
3.3.2 DATA COLLECTION & PREPROCESSING
Raw data undergoes thorough cleaning and organization procedures to ensure consistency and
quality, including handlingmissing values, standardizing formats across diverse sources, and preparing
structured information for the subsequent analytical stages.
3.3.3 FEATURE ENGINEERING
This transformative stage converts raw data into meaningful features through meticulous cleaning and
selection of predictive variables, alongside encoding categorical data into numerical representations
and scaling numerical values to maintain consistent performance across all modeling components.
3.3.4 MACHINE LEARNING MODELS
The architecture leverages three complementary analytical approaches: Random Forest creating
robust predictions through ensemble methods, Decision Tree providing transparent and interpretable
decision paths, and Logistic Regression generating probability-based risk assessments to ensure
comprehensive analysis.
3.3.5 PREDICTION & DECISION MAKING
Predicted severity levels (e.g., slight, serious, fatal) are generated by the chosen model. These outputs
are passed into a decision-making logic module that determines response actions, such as whether to
send emergency alerts, visualize risks, or recommend safer routes.
3.3.6 OUTPUT & ALERTS
The system delivers effective outputs aimed at enhancing road safety and keeping users informed. It
identi es and displays high-risk areas through heatmap visualizations, issues alerts in critical
situations, and recommends safer routes to minimize travel risks. Additionally, it records user inputs for
future analysis, contributing to continuous system improvements and informed decision-making by
both users and authorities.
3.4 SYSTEM REQUIREMENT SPECIFICATION
For ef cient execution of machine learning models and seamless data handling, the system should run
on the following minimum and recommended hardware setup:
• Processor: At least an Intel Corei5 or AMD Ryzen 5 is required, while an Intel Core i7 or AMD Ryzen
7 is suggested for handling intensive data operations.
• RAM: Aminimum of 8GBis necessary, with 16GB or morerecommended to ensuresmoother
multitasking and quicker processing.
• Storage: A 256GB SSD is theminimum needed, though a 512GB SSD or larger is advised for faster
Page 2 of 3
data access and better storagemanagement.
• Operating System: Compatible withWindows 10 or Windows 11 for optimal software support and
performance.
No Plagiarism Found
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 828 Total Characters: 5916 Plagiarized Sentences: 0 Unique Sentences: 38 (100%)
CHAPTER 4
METHODOLOGY
Road accident risk prediction, ML helps uncover insights from past accident data and forecasts the
severity of future incidents based on inputs like weather, traf c ow, road surfaces, and vehicle speed.
This technique allows for smarter, data-informed safety strategies and early warnings.
Machine learning approaches are typically divided into three key types: supervised learning,
unsupervised learning, and semi-supervised learning, each suited to different kinds of tasks and data
availability.
Page 1 of 3
• Improves the reliability of accident severity predictions even when only a small portion of the dataset
has severity labels.
Page 2 of 3
Text-based categories (such as lighting or weather) are numerically encoded using tools like
LabelEncoder. Missing or inconsistent values aremanaged through deletion or [Link]
variable Accident_Severity is mapped as integers 0 (Fatal), 1 (Serious), and 2 (Slight) for classi cation
No Plagiarism Found
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 918 Total Characters: 6301 Plagiarized Sentences: 0 Unique Sentences: 53 (100%)
LOGISTIC REGRESSION
Logistic Regression is a type of algorithm used in both statistics and machine learning for solving
classi cation problems. Logistic regression is used to estimate the probability that a given input
belongs to a speci c class.
The sigmoid (logistic) function transforms input values into a range between 0 and 1, making it
suitable for expressing probabilities. Based on a selected threshold often set at 0.5—the model
decides which class the input most likely belongs [Link] it is mainly used for binary classi cation,
logistic regression can also be adapted formulti-class problems using strategies such as One-vs-Rest
or Softmax classi cation.
4.4.2 Working with Logistic Regression
1. Feature Collection
Your system collects inputs such as:
Weather conditions,Light conditions,Road surfacetype,Speed limit,Policeattendanc,Latitude &
Longitud. These inputs serve as independent variables (features) for prediction.
2. Target Variable
Thetarget is Accident Severity, which is categorical:
• Fatal
• Serious
• Slight
Logistic Regression models the probability of each severity class.
3. Data Preprocessing
All categorical values areencoded into numbers (e.g., "Wet" →2).
Data is scaled or normalized if needed.
4. Model Training
Themodel learns weights (coef cients) for each feature to maximizeprediction accuracy.
5. Prediction
When a user submits a form:
Input datais processed to match the trained model's format.
The model computes the probability scores for each severity level.
Theclass with thehighest probability is returned (e.g., 0.81 → Slight).
4.5 EVALUATION METRICS
4.5.1 AccuracyHere's a **fully original version** of your sentence with **0% plagiarism**:
> **Accuracy represents thefraction of total predictions that were correctly identi ed by themachine
learning algorithm.**
Page 1 of 3
Let me know if you need variations or want to rephrasemore such de nitions!
TP (True Positives)
These refer to instances where themodel accurately identi es a case as a severe accident (like Fatal or
Serious), and the actual label is also severe.
Example: An accident labeled “Fatal” is correctly predicted as “Fatal” by themodel.
TN (True Negatives)
These are cases where themodel properly classi es a minor accident (e.g., Slight) and the actual
outcome is also minor.
Example: An accident that is truly “Slight” is also labeled “Slight” by themodel.
FP (False Positives)
This occurs when themodel mistakenly classi es aminor accident as severe.
Example: The model outputs “Serious,” but the real label is “Slight.”
FN (False Negatives)
These are situations where a severe accident is incorrectly predicted as non-severe.
4.5.2 Precision
Precision focuses on how reliablethemodel's predictions are when it ags an accident as severe. It
tells us, out of all the cases where the system predicted a severe outcome (like Fatal or Serious), how
many were truly severe. A high precision score means the model rarely makes incorrect severe
predictions, helping minimize unnecessary alerts or false alarms.
TP (True Positives)
These arethe cases where themodel correctly predicts an accident as severe(either Fatal or Serious)
and the actual severity is also severe.
Example: An accident is truly "Fatal", and themodel correctly predicts "Fatal".
FP (False Positives)
These occur when themodel predicts an accident as severe, but in reality, it is not severe (i.e., it’s
Slight).
Example: Thesystem predicts "Serious", but thetruelabel is "Slight"
4.5.3 Recall (Sensitivity)
Recall evaluates how effectively a model identi es all instances of truly severe accidents. It measures
the proportion of severe accidents (e.g., Fatal or Serious) that the model correctly identi es out of all
actual severe cases.
TP (True Positives)
These areaccident cases wherethemodel correctly predicts a severe outcome(Fatal or Serious), and
the actual label is also severe.
Example: The actual accident severity is "Fatal", and themodel predicts "Fatal".
FN (False Negatives)
These occur when themodel fails to recognize a severe accident and incorrectly predicts it as non-
severe (e.g., Slight).
Example: Theactual severity is "Serious", but themodel predicts "Slight".
4.5.4 F1 Score
The F1-score combines precision and recall into a single balanced metric, emphasizing the trade-off
between missed cases and incorrect alerts. It is especially useful when the dataset is imbalanced,
meaning that some severity classes (e.g., “Fatal”) occur far less frequently than others.
Precision
Measures howmany of the predicted severe accidents (e.g., “Fatal” or “Serious”) are actually severe.
Recall
Measures how many of the actual severe accidents themodel successfully detects.
High recall = low false negatives (rarely misses severe cases).
4.5.5 Confusion Matrix
A confusion matrix is a performance evaluation metric for classi cation models that displays how
predicted classi cations align with the actual outcomes.. It organizes theresults into four categories:
True Positives, False Positives, True Negatives, and False Negatives. Unlike metrics such as accuracy or
Page 2 of 3
precision, it does not rely on a single numerical formula but instead presents a structured overview of
the model’s predictions.
No Plagiarism Found
Page 3 of 3
Plagiarism Scan Report By SmallSEOTools
Report Generated on: May 25,2025
0%
Exact Plagiarized
0% 100%
0%
Plagiarized Content Partial Plagiarized
Unique Content
Total Words: 735 Total Characters: 5389 Plagiarized Sentences: 0 Unique Sentences: 31 (100%)
6.1 CONCLUSION
The development of a machine learning-based road accident risk prediction system marks a signi cant
advancement toward enhancing road safety and reducing the impact of traf c-related incidents.
Throughout the project, we explored the application of supervised learning algorithms to predict
accident severity using structured datasets derived from real-world traf c scenarios in India. By
leveraging data-driven approaches, our system aims to assist authorities and the public in making
informed decisions, mitigating risks, and potentially saving lives.
This system integrates essential components of the machine learning pipeline, including data
preprocessing, feature engineering, model training, evaluation, and web-based deployment. Data
preprocessing involved handling missing values, encoding categorical variables, and standardizing
numerical features, which were critical to improving the accuracy and reliability of the models. Key
features consideredincluded environmental factors like weather andlighting conditions, geographical
coordinates, road surface quality, speed limits, and the presence of police of cers at the accident
scene. These features provided meaningful insights into the conditions under which accidents aremore
likely to occur and their potential severity.
Wetrained multiplemodels, including Random Forest Classi er, Decision Tree, and Logistic
Regression, and evaluated their performanceusing accuracy, precision, recall, F1-score, and confusion
matrix metrics. Among these, the Random Forest model outperformed others in terms of stability,
robustness, and handling of imbalanced data classes. It demonstrated high recall in identifying critical
cases and maintained overall accuracy without over tting. Visualization tools like heatmaps were also
incorporated to detect accident hotspots based on location data, aiding both in public awareness and
urban [Link] user interface developed using Flask and Lea et offers an interactive and user-
friendly experience. It allows users to input traf c conditions and receive immediate feedback on the
predicted severity of a possible accident. Admin users can manage data, review submissions, and
analyze system usage. The integration of a route safety suggestion feature using OpenRouteService
adds additional value by guiding users toward safer travel paths based on accident density analysis.
In conclusion, our system not only demonstrates the feasibility of using machine learning in road safety
applications but also showcases its real-world applicability. It bridges the gap between raw data and
actionable safety measures, emphasizing the importance of technological solutions in addressing
public health challenges. With further enhancements and the incorporation of real-time data, this
platform can evolve into a powerful tool for government agencies, city planners, emergency
responders, and everyday commuters. This project lays the foundation for future innovations in
predictive traf c analytics and highlights the potential of AI in promoting smarter and safer cities.
6.2 FUTURE SCOPE
As the developed system demonstrates promising capabilities in predicting accident severity and
suggesting safer routes, there is signi cant potential for further enhancement. Onemajor improvement
Page 1 of 2
would be the integration of a heatmap overlay feature to visually represent high-risk accident zones.
This would provide users with a clearer understanding of areas to avoid, improving situational
awareness and safety. Additionally, incorporating real-timedata from traf c and weather APIs, such as
those offered by Google or other open platforms, would allow the model to adjust dynamically based
on current road and weather conditions. This integration would make the system more responsive to
real-world scenarios, ensuring that predictions remain accurate and timely. Enhancing thefeature set
by including temporal variables liketime of day andtemporary road conditions—such as construction,
wet surfaces, or poor lighting—would re ne themodel’s understanding of contextual risks, enabling
even more precise severity forecasting. Another important direction is implementing a detour
recommendation system that actively suggests alternate, safer routes when a user’s current path
intersects with a high-risk zone. This would elevate the system from a passive prediction tool to an
interactive safety assistant. Moreover, expanding the system’s accessibility by developing a mobile
application or progressive web app would allow users to receive real-timealerts and guidance while
on themove. Incorporating a feedback mechanism could enable users to report inaccurate predictions
or con rm real-timehazards, which would help continuously train and adapt themodel for future use.
Such feedback-driven improvements would enhancethereliability of predictions and keep the system
aligned with evolving road safety patterns. Finally, the system’s design allows for scalability; by
acquiringlocalized accident datasets, it can be adapted for use invarious cities or countries, making it a
globally applicable safety solution. These future enhancements collectively aim to transform the
platform into a comprehensive, intelligent risk mitigation tool that supports safer mobility decisions
and contributes meaningfully to public road safety initiatives
No Plagiarism Found
Page 2 of 2
Inferring high-resolution traffic accident risk maps based on satellite imagery
and GPS trajectories
Abstract
Traffic accidents cost about 3% of the world’s GDP and
are the leading cause of death in children and young adults.
Accident risk maps are useful tools to monitor and mitigate
accident risk. We present a technique to generate high-
resolution (5 meters) accident risk maps. At this high res-
olution, accidents are sparse and risk estimation is limited
by bias-variance trade-off. Prior accident risk maps either
estimate low-resolution maps that are of low utility (high
bias), or they use frequency-based estimation techniques
that inaccurately predict where accidents actually happen
(high variance). To improve this trade-off, we use an end-
to-end deep architecture that can input satellite imagery,
GPS trajectories, road maps and the history of accidents.
Our evaluation on four metropolitan areas in the US with
a total area of 7,488 km2 shows that our technique outper-
form prior work in terms of resolution and accuracy. Figure 1. Our model inputs road maps, satellite imagery, GPS tra-
jectories, and historical traffic accidents. It outputs accident prob-
1. Introduction ability distribution. Note that our model has identified a few loca-
tions as high-risk (highlighted with circles) even though they have
According to WHO, each year 1.35 million people die
no historical accidents. Locations that our model has identified as
and 20 to 50 million people sustain non-fatal injuries from high-risk experienced accidents during the follow-up years.
traffic accidents [20]. In the US alone, traffic accidents cost
$871 billion annually [6]. In most countries traffic accidents
We improve this trade-off by incorporating context in-
cost about 3% of the GDP [20]. By identifying high-risk
formation from satellite imagery, GPS trajectories, and road
locations on the map, many groups, including drivers, po-
maps. We use an end-to-end deep neural network to com-
lice departments, transportation departments and insurance
bine different data modalities. We discuss the details of our
companies can take actions to reduce this risk.
model in Section 3. Figure 1 shows our four input modali-
Accident risk maps assign an expected rate of accident
ties, our prediction, and the accidents in the follow-up years.
over a given time period to each location on the map. Prior
works predict accident maps with resolutions of a few hun- At 5m×5m resolution, evaluation is also challenging be-
dred meters (Table 1). In this work we predict maps with cause the ground-truth is noisy (It is sampled from a hidden
5m×5m resolution because there are important details that risk distribution.) In Section 4 we present a process to esti-
are not captured in lower resolutions. At this resolution, mate the prediction error with respect to the true underlying
sparsity causes a bias-variance trade-off in the estimation of risk distribution. Our maps outperform prior work in terms
the underlying risk. We explain this challenge in Section 2. of resolution and prediction error.
11977
Table 1. Overview of prior work on traffic and accident map prediction. We predict accident maps with one to two orders of magnitude
higher resolution than prior work. We also use richer input data than prior works.
Year Authors Resolution Method Input data
2005 Chang et al. [9] Entire highway Decision Tree Road map, average daily traffic (AADT), weather
2005 Chang et al. [8] Entire highway Neural Networks Road map, average daily traffic (AADT), weather
2007 Caliendo et al. [7] Entire highway Max. Likelihood Road map, AADT, slope and presence of junctions
2016 Chen et al. [11] 500m × 500m SdAE [4] GPS trajectories, historical accidents
2017 Yuan et al. [29] road segments Deep networks Historical Accidents, road map, weather
2017 Najjar et al. [17] 150m × 150m Pre-trained Alex-net Satellite imagery, accident history
2018 Ren et al. [22] 1km × 1km LSTM Historical accidents
2018 Chen et al. [10] 500m × 500m SdAE [4] Traffic flow (from plate recognition system), accident history
2018 Yuan et al. [28] 5km × 5km ConvLSTM Traffic volume, road condition, weather, satellite imagery
2019 Bao et al. [3] > 360m STCL-Net Crash, GPS, road, land use, population and weather data
2020 Zhou et al. [31] 1.5km × 1.5km RiskSeq Traffic flow, road network, weather and accident history
2021 This work 5m × 5m End-to-end deep net Satellite imagery, GPS trajectories, road map, accident history
11978
2.3. Evaluation with ground-truth error
We use future accidents as a proxy to the underlying rate
of accidents. This proxy has an error that adversely affects
evaluation, therefore we need to isolate it.
Assume a map has n grid cells and there is an underlying
rate of accident for each cell Ri that we want to estimate.
There is an observation of the historical rate of accidents
at each location Hi . There is also an observation of the
future rate of accident Fi . Since accidents are independent
events, We can assume Hi and Fi are drawn from a Poisson
distribution with rate Ri . We can write down the rate of all
grid cells write them down in the following vector form:
11979
Inputs Dropout Output Accident Risk Map
48x48 Res-1 Res-2 Res-3 Res-4 ResNet-18
x64
Satellite Image
384 x 384 x 3 3x3 Conv
6 Layers
8x downscale 48x48x32
Road Segmentation 48x48 24x24 12x12 6x6
x64 x128 x256 x512
384 x 384 x 1
Sigmoid
Gate
48 x 48
GPS Histogram upsample and concat (g)
48 x 48 x 1 48x48x1
3x3 Conv + 3x3 Conv + Risk
3x3 Conv
48x48 Relu + BN Relu + BN
(2 channels)
Pred-1
GPS Features 3x3 Conv x960 (960 channels) (960 channels) split 48 x 48
48 x 48 x 13 2 Layers (y1)
48x48x30
Risk
Historical Data 7x7 Conv Pred-2
Fuse: y = y1 · g + y2 · (1 - g)
48 x 48 x 1 (1 channel) 48 x 48
48x48x1 Skip Connection
(y2)
Figure 3. We use a deep model that takes four different data sources as input and predicts an accident risk map at 5-meter resolution – only
at this high resolution can we distinguish the different risks in the output example where the freeway road has a higher risk than the nearby
residential roads and the ramp merging and exiting area has an even higher risk than other places.
3. Learning to predict risk maps ful when the training dataset is small. Our model supports
using a subset of the above five data sources as input. In this
We use a deep model to predict accident risk at every case, we can predict risk maps even if some data sources are
grid cell on the map. In the design of this model, we need not available in the region of study.
to overcome the challenges caused by sparsity while mak- Model architecture: In our model, we first pre-process
ing sure that our model can learn useful information from input data so that different sources of data all have the same
all input sources. We illustrate our model architecture in spatial dimensions. We stack the satellite input and the road
Figure 3. The model takes different data modalities as in- segmentation input into one tensor and pass it to a 6-layer
put and predicts a 2D risk map y ∈ RN ×N , where N is the CNN encoder which down-scales the input dimension and
dimension of the target map grid, and we set it to 48. Next, extends the channel width from 4 (3 RGB channels + 1 map
we discuss the details of our model. channel) to 32. Meanwhile, we use a 2-layer CNN encoder
Model Inputs: Our model takes five different data to increase the dimensions of the GPS feature input from 13
sources as input to predict a risk map for an N × N map to 30. Therefore, if we stack all the input sources together,
gird with a resolution of 5 meters. The first input is an the total number of channels add up to 64.
RGB-channel satellite image. We use a higher-resolution After pre-processing, we stack all the input sources into
(8N × 8N ) imagery to capture more visual information. an N × N × 64 tensor and pass it to a ResNet-18 encoder.
In this case, the satellite image input is represented as an We take the feature maps after each residual block set and
8N × 8N × 3 tensor. The second input is a segmentation up-sample them so that they all have the same spatial di-
mask of the road map in the target region. Similar to the mensions. Then, we stack them into a N × N × 960 feature
satellite image input, we use a high resolution for the road map and pass this feature map to a 3-layer CNN decoder.
mask (8N × 8N × 1). Skip Connections and Fusion: We don’t use this 3-
Our model also takes GPS trajectories as input. We rep- layer CNN decoder to predict the final risk map directly;
resent the GPS trajectories in two formats: One is a 2D his- instead, we introduce a skip connection and a fusion module
togram (N × N × 1) which encodes the density of the GPS to produce the final risk map. We observed that the histor-
trajectories (at log-scale) on each grid cell. The other format ical data is very similar to the training target in some high-
extends the 2D GPS histogram with 12 additional features, risk regions. As a result, if we directly produce the risk map
encoding the statistics (10-th, 50-th and 90-th percentiles) using the 3-layer CNN decoder, the model relies on the his-
of the speeds, accelerations, turning angles, and the counts torical data and ignores other data sources, ending up in a
of left/right/no turns of all the GPS trajectories that pass low-performance local optima. To overcome this issue, we
through each grid cell. Combined with the original 2D GPS let the 3-layer CNN decoder predict two N × N tensors: a
histogram, this input format contains 13 channels in total, risk map denoted as y1 and a gate g where gi,j ∈ (0, 1). We
and we represent it as an N × N × 13 tensor. use the weighted average of y1 and another risk map pre-
The last input source is the historical accident data. We diction y2 , which only uses the historical data as the final
use the rate of historical accidents in each grid cell. output. Formally, we have y = y1 · g + y2 · (1 − g). This
During training, we randomly drop out each input source allows our model to focus on learning the residual between
with a probability of 20%. We find that this strategy is help- the historical data and the target.
11980
Table 2. Dataset details in each city. The fact that Boston has fewer 4.2. Training Details
accidents explains why more features don’t always help.
LA NYC Chicago Boston In our evaluation, we split the dataset spatially into a
Tiles 813 458 282 319 training set (80%), a testing set (15%), and a validation set
Accidents 351k 88k 45k 33k (5%). We train our models on the training set for 50 epochs,
GPS (km) 3.1M 1.8M 0.7M 2.0M start with a learning rate of 0.0001 and decrease it by a fac-
1
tor of 10 at the 20-th epoch and the 40-th epoch. The train-
ing took 6 days on one Nvidia V-100 GPU. After training,
Target and loss function: We temporally partition ac- we use the validation set to find the best model and evaluate
cidents into two groups: historical accidents (happened be- the model on the testing set. The training/evaluation code,
fore some time t) and future accidents (happened after t). the output accident maps, and the instruction to download
A historical accident map is given as input to let the model the dataset are available on GitHub.
understand the distribution of accidents. A future accident 4.3. Evaluation settings
map is given as the prediction target. We use future ac-
cidents as a proxy for the true underlying risk distribution We have two major evaluation settings: with history and
which is unknown. The future accident map is a sparse sam- without history. In the “with history” setting, we supply
ple from the true underlying risk distribution. Therefore, it historical accidents to the model, while in the “without his-
is noisy and not ideal. However, it is useful because the tory” setting, we do not supply historical accidents to the
sampling error in the future accident map is not correlated model.
with the sampling error in the historical accident map (be- Depending on the use case, historical accident data may
cause they are independent samples). Therefore, future ac- or may not be available to the model. If historical accident
cident map does not carry a systematic bias from historical data is available and the goal is to produce an accurate acci-
accidents, so it is a useful proxy. Our loss function is the dent map, then accident history data should be used as input.
mean squared error between our prediction and the future If historical accident data is unavailable, or if this model is
accident map. being used as a recommender system or to compare hypo-
thetical designs, then historical data cannot be supplied.
We evaluate a few variants for each of the “with history”
4. Evaluation and “without history” settings. These variants include six
4.1. Dataset variants of our model, kernel density estimation, and the-
oretical upper-bounds for low-resolution techniques. We
We evaluate our model on a dataset covering an area of compare with the theoretical upper-bounds as a reference
7,488 km2 from four metropolitan areas: Los Angeles, New to show the effect of the resolution.
York City, Chicago, and Boston. The dataset is organized In the “with history” evaluation setting, we use two years
as 1,872 2km×2km tiles. For each tile, we collect satellite or accident data as input, while in the “without history”
imagery from MapBox [1] and create the road segmenta- evaluation setting, we do not use historical accidents as in-
tion mask using OpenStreetMap [12]. Our imagery has a put.
resolution of 0.625 meters. We also construct the road seg-
mentation mask with this resolution. 4.4. Evaluation metrics
We use a proprietary GPS dataset collected from 2015 In prior works, accident map prediction is formulated ei-
to 2017 in the four metropolitan areas as the source of GPS ther as a binary classification problem or as a regression
trajectories. This dataset contains a total of 7.6 million km problem. Classification-based works assign a binary la-
of GPS trajectories with a 1-second sampling rate. bel (whether any accidents happened) to each cell within a
We use the US accidents dataset [16] that contains 4.2 time window of interest. Then they predict a score for each
million records for accidents that were occurred in the US cell within the time window of interest. Finally, they com-
from 2016 to 2020. Each record comes with coordinates, pare their prediction scores with the binary ground truth and
timestamps, and a few other fields of information. We split evaluate their performance using the precision-recall curve
this accident dataset into two parts containing the data from and average precision.
the first two years and the data from the last two years. We Regression-based techniques predict the number of ac-
use the first two years’ data as historical data to feed into cidents within each cell and the time window of interest.
the model as input. We use the last two years’ data as future Regression-based techniques often have a low resolution;
accidents. Future accidents are used for training and eval- therefore, several accidents could occur within each cell.
uation. In table 2, we summarize the amount of available Regression-based techniques typically use RMSE between
data in each city that helps to compare the results from the the ground-truth number of accidents in each cell and their
four different cities. estimation to evaluate their regression performance.
11981
(a) Accident Risk Prediction With 2-Year Historical Data (b) Accident Risk Prediction Without Historical Data
Figure 4. (a) Precision-Recall curves for “with history” setting. We present the results of three variants of our model, Kernel Density
Estimation (KDE), and three upper-bounds on low-resolution techniques. The improvement from satellite imagery is on the lower-risk
(right) side of the curve. KDE identifies the most high-risk places well but performs worse on low-risk places. (b) Precision-Recall curves
for “without history” setting. In the absences of historical data, accident prediction accuracy is lower and the context information is more
useful. In this case, GPS trajectories are effective in improving the performance.
We evaluate our model with both AP and RMSE. Fig- ble 1), they cannot pinpoint accident hot-spots. This
ure 4-a shows our precision-recall curve for the “with his- has a profound adverse effect on their performance.
tory” model. Figure 4-b shows our precision-recall curve The effect of low resolution (100m×100m vs 5m×5m)
for the “without history” model. Table 3 also compare av- is so significant that even if the prior works are al-
erage precision quantitatively. lowed to optimize their output on the actual test-set,
Traffic accident estimation techniques that perform re- they still under-perform comparing to our model. To
gression use RMSE to evaluate their performance. We com- compare with the prior works, we use the best theoret-
pared our performance with RMSE in table 3. AP and ical possible prediction (optimized on the test set with
RMSE have a few notable differences. First, AP puts a the knowledge of the future accidents) at their resolu-
higher weight on high-risk locations than RMSE. Second, tion. We refer to this as theoretical upper-bound for
AP does not distinguish between one or many accidents in their accuracy. We show that our technique outper-
a cell. AP is useful for evaluating performance in high-risk forms this theoretical upper-bound for prior works. We
areas. RMSE is useful to evaluate overall performance. use theoretical upper-bound because the code for prior
When reading these precision-recall curves, we should works is not available and they are evaluated on differ-
note that the prior probability of the prediction target has ent cities than ours.
a large effect on AP statistics. A classification task on a 3. Different prior works use different sources of data as
10m×10m map has four times higher prior than a classi- input (Table 1). We measure the effect of different
fication on a 5m×5m map. Therefore, average precision sources of data on the performance of the model. This
numbers on different resolutions are different and should measures the effect of the extra data that we use.
not be compared. Furthermore, since ground-truth itself is
noisy, there is an upper limit on maximum AP. 4.6. Evaluation Results
We summarize our results in Table 3 and Figure 5. We
4.5. Baselines and prior work
show the APs and RMSEs of different approaches under
Unfortunately, the code for most of the prior work is two setups – with and without historical data. Next, we
not available. Furthermore, each prior work has studied discuss a few insights we learned from this experiment.
one separate city with private data. We use the US acci- Prediction with historical data: Our model uses other
dents dataset [16] that is a large scale and publicly available data sources to improve the risk map prediction when the
dataset covering the entire US. In order to compare to the historical data is available. As a result, our model performs
prior work we perform the following: better than the KDE-based approaches that only take the
1. Since several prior works use KDE, we implemented historical data input into account. As shown in Table 3,
and evaluated KDE as a baseline. The details of KDE compared to the KDE-based approaches, our models im-
is presented in [23]. We tuned the parameters of KDE prove the AP by 4.87 points and reduce the RMSE by 8.8%.
so that it can achieve its highest average precision. Prediction without historical data: When historical
2. Since prior works use lower resolution than we do (Ta- data is not available, our model can still use the other data
11982
Table 3. Comparison of AP and RMSE for different methods. The first 7 rows compare the methods without using historical data as
input, and the last 7 rows compare the methods that use the historical data as input. We also show the theoretical upper-bounds for the
low-resolution risk maps at rows 8-10. In this comparison, all variants of our model consistently outperform other methods on both metrics.
Average Precision (%) RMSE (10−6 )
Methods
LA NYC CHI BOS Avg. LA NYC CHI BOS Avg.
GPS Density 16.82 11.87 6.95 5.83 11.90 1.397 2.652 5.216 4.555 2.823
w/o historical data
Road (ours) 19.67 13.36 10.85 13.75 15.51 1.330 2.630 5.035 4.363 2.730
Road+Satellite (ours) 24.61 14.13 13.98 11.74 19.81 1.282 2.574 4.869 4.309 2.662
Road+GPS-Hist (ours) 28.59 17.56 22.71 16.72 23.01 1.239 2.552 4.690 4.203 2.594
Road+GPS-Hist+Sat. (ours) 28.83 16.51 21.02 16.75 23.15 1.233 2.556 4.688 4.243 2.599
Road+GPS-Feat. (ours) 27.28 15.11 19.66 15.12 21.71 1.271 2.616 4.744 4.296 2.648
Road+GPS-Feat.+Sat. (ours) 28.29 16.41 22.26 14.49 22.15 1.242 2.608 4.591 4.338 2.618
100m (upper bound) 23.64 20.28 13.79 16.40 21.37 1.328 2.462 4.925 4.210 2.644
200m (upper bound) 14.28 10.68 6.20 8.54 12.32 1.404 2.657 5.163 4.462 2.804
with historical data
500m (upper bound) 7.86 5.61 2.94 3.70 6.62 1.439 2.729 5.255 4.583 2.872
KDE on historical data 42.60 22.11 25.68 20.06 34.24 0.945 2.562 4.060 5.073 2.529
Road (ours) 43.48 25.41 27.26 23.16 35.86 0.901 2.459 3.938 4.758 2.412
Road+Satellite (ours) 44.77 23.91 27.08 21.09 35.10 0.860 2.306 3.897 4.570 2.317
Road+GPS-Hist (ours) 46.42 27.71 30.83 24.87 38.33 0.865 2.365 3.818 4.461 2.304
Road+GPS-Hist+Sat. (ours) 46.27 26.96 30.01 23.93 37.79 0.859 2.278 3.888 4.573 2.308
Road+GPS-Feat. (ours) 46.55 28.07 33.38 24.13 38.28 0.852 2.330 3.701 4.724 2.318
Road+GPS-Feat.+Sat. (ours) 47.67 28.90 32.95 24.63 39.11 0.853 2.316 3.799 4.783 2.339
sources to estimate the risk, achieving an AP of 23.15% and sity of our dataset in each city follows the reverse order. If
an RMSE of 2.594; this accuracy is significantly improved we look at the average precision (AP) of each model (with
compared to a baseline method that only uses GPS density historical data) in these four cities, we find that the mod-
to estimate the traffic risk. More importantly, unlike most els that take more information as input generally perform
prior works that rely on historical accidents, we can use this better in LA and New York City where accidents are less
model to create risk maps for places that do not have histor- sparse. However, they perform worse in Boston, where the
ical data, holding the potential to create broader impact. accidents are sparser. This fact verifies that the challenge
Low resolution prediction upper bounds: We find that caused by sparsity does indeed exist.
our models can outperform the 100-meter resolution upper Because the GPS data contains important information
bound by a large margin — 17.74 points on the AP metric about traffic patterns that can be helpful for accident risk
and a 12.8%-reduction on the RMSE metric when the his- prediction, instead of using the aggregated GPS histogram
torical data is available. Even when the historical data is not or hand-crafted statistics such as the median speed, we tried
available, our models can still outperform this upper bound to use a Deep Set [30] to extract more information from
thanks to the high resolution of our predicted risk maps. the raw GPS trajectories end-to-end. However, we found
Impact of each data source: Within our model, we that DeepSet actually harms the accuracy in our dataset be-
evaluate six variants that use different combinations of data cause the provision of the extra rich features from the raw
sources. In our experiments, 2 of the variants do not have GPS trajectories greatly increases model variance and over-
GPS input. Comparing them with the other four variants, fitting. We observe this fact even in LA, where it has the
we can observe the benefit of the GPS data source. This highest accident density.
benefit is due to two reasons, (1) the information carried by Cross-city evaluation: We evaluate the generalization
GPS data, such as the volume of the traffic, has a strong ability of our model in a cross-city evaluation setup where
correlation with accident risk, (2) because information con- we train a model on three different cities and test it on an
tained in the GPS data after aggregation (e.g., using a his- unseen city. As shown in Table 4, we find our model can
togram) is relatively limited, overfitting becomes unlikely, generalize well on unseen testing cities.
and the prior learned from one place can be easily general-
ized to other places. This property is especially important Table 4. Comparison of the average precision of city-specific mod-
els vs a cross-city model. City-specific models perform slightly
in our scenario where the ground truth data is sparse.
better. We believe this is because each city has certain unique
Besides the benefit of the GPS data source, we also ob- characteristics.
serve another important fact. Among the four cities, LA Training cfg. LA NYC CHI BOS
is the most unsafe city (has the highest accident density), Same cities 47.67% 28.90% 32.95% 24.63%
followed by New York City, Chicago and Boston. The spar- Cross-city 47.61% 27.79% 31.33% 24.52%
11983
Figure 5. We show the risk maps produced by the KDE approach, and our approach (with and w/o historical data), along with the 2-year
future accidents (used as the target in our evaluation) and the 2-year historical accidents in the four cities. We find that our risk maps can
capture the underlying risk distribution that determines the probability of future accidents at all places and do so even without any historical
data. In contrast, the KDE-based approach can only highlight places where there were accidents before and fail to assess the risks at other
places. For example, in New York City, the accidents happened at random intersections in those two 2-year periods. Even though it looks
like our risk map has low precision because there is no accident at many high-risk intersections in a 2-year period, our model captures the
underlying risk distribution — accidents happen at those intersections with a similar chance.
Hyper-parameters: Since the targets (accidents) are to use satellite imagery, GPS trajectories, and road maps
sparse, over-fitting is a major issue. We found that optimal to achieve this. We extensively evaluated and showed that
hyper-parameters (including model size) highly depend on our model has state-of-the-art performance. Besides the im-
the size and sparsity of the dataset. Larger models generally proved performance and the useful maps we generated, our
perform better in larger cities. Hyper-parameters must be evaluations provide insights into how to achieve high per-
tuned to the input size. In this work, we focused on the logic formance in the face of accident data sparsity.
behind model design rather than tuning hyper-parameters to Future work: One potential extension of this work is
one dataset. to combine this work with temporal risk prediction tech-
Insight: In summary, we find that the sparsity of acci- niques to establish a spatio-temporal accident risk model.
dents is a major challenge in the design of an accident risk In the simplest form, there could be independent spatial and
prediction model. On the one hand, we need to use more temporal components in the model. A comprehensive ac-
data sources and deeper architectures so that we can learn cident risk model could potentially input other factors, in-
a good estimation of the accident risk. On the other hand, cluding weather patterns, driver characteristics, driving be-
due to the sparsity of the accidents, using more input fea- havior, and vehicle condition.
tures and deeper models can lead to overfitting. Accident related applications: Our model is flexible in
terms of what data sources are available. Once our model is
5. Conclusion trained, we can apply it to countries where detailed histori-
We presented an end-to-end deep model that predicts cal accident data is not published. Furthermore, this model
high-resolution traffic accident risk maps. Since accident can be potentially used to compare city layout designs be-
data is sparse, sample efficiency is key for a successful ac- fore construction.
cident risk estimation technique. To improve sample effi- Other Applications: Even though this model has been
ciency, we use a model that establishes the similarity be- developed for accident prediction, this fundamental tech-
tween locations, not just based on proximity (as in KDE) nique can work for similar sparse location-based problems,
but also on similarity in appearance. We developed a model including 911 emergency risk maps or taxi demand maps.
11984
References [17] A. Najjar, S. Kaneko, and Y. Miyanaga. Combining satellite
imagery and open data to map road safety. In Proceedings of
[1] Mapbox. [Link]. Accessed: 2021-03-01. 5 the AAAI Conference on Artificial Intelligence, volume 31,
[2] T. K. Anderson. Kernel density estimation and k-means clus- 2017. 2
tering to profile road accident hotspots. Accident Analysis & [18] R. Netek, T. Pour, and R. Slezakova. Implementation of heat
Prevention, 41(3):359–364, 2009. 2 maps in geographical information system–exploratory study
[3] J. Bao, P. Liu, and S. V. Ukkusuri. A spatiotemporal deep on traffic accident data. Open Geosciences, 10(1):367–384,
learning approach for citywide short-term crash risk predic- 2018. 2
tion with multi-source data. Accident Analysis & Prevention, [19] A. Okabe, T. Satoh, and K. Sugihara. A kernel density esti-
122:239–254, 2019. 2 mation method for networks, its computational method and
[4] Y. Bengio. Learning deep architectures for AI. Now Pub- a gis-based tool. International Journal of Geographical In-
lishers Inc, 2009. 2 formation Science, 23(1):7–32, 2009. 2
[5] M. Bı́l, R. Andrášik, and Z. Janoška. Identification of haz- [20] W. H. Organization et al. Global status report on road safety
ardous road locations of traffic accidents by means of kernel 2018: Summary. Technical report, World Health Organiza-
density estimation and cluster significance evaluation. Acci- tion, 2018. 1
dent Analysis & Prevention, 55:265–273, 2013. 2 [21] V. Prasannakumar, H. Vijith, R. Charutha, and N. Geetha.
[6] L. Blincoe, T. R. Miller, E. Zaloshnja, and B. A. Lawrence. Spatio-temporal clustering of road accidents: Gis based anal-
The economic and societal impact of motor vehicle crashes, ysis and assessment. Procedia-social and behavioral sci-
2010 (revised). Technical report, 2015. 1 ences, 21:317–325, 2011. 2
[7] C. Caliendo, M. Guida, and A. Parisi. A crash-prediction [22] H. Ren, Y. Song, J. Wang, Y. Hu, and J. Lei. A deep learn-
model for multilane roads. Accident Analysis and Preven- ing approach to the citywide traffic accident risk prediction.
tion, 39(4):657–670, 2007. 2 In 2018 21st International Conference on Intelligent Trans-
portation Systems (ITSC), pages 3346–3351. IEEE, 2018. 2
[8] L.-Y. Chang. Analysis of freeway accident frequencies: Neg-
[23] G. R. Terrell and D. W. Scott. Variable kernel density esti-
ative binomial regression versus artificial neural network.
mation. The Annals of Statistics, page 1236, 1992. 2, 6
Safety Science, 43(8):541–557, 2005. 2
[24] L. T. Truong and S. V. Somenahalli. Using gis to iden-
[9] L.-Y. Chang and W.-C. Chen. Data mining of tree-based
tify pedestrian-vehicle crash hot spots and unsafe bus stops.
models to analyze freeway accident frequency. Journal of
Journal of Public Transportation, 14(1):6, 2011. 2
Safety Research, 36(4):365–375, 2005. 2
[25] Z. Xie and J. Yan. Kernel density estimation of traffic acci-
[10] C. Chen, X. Fan, C. Zheng, L. Xiao, M. Cheng, and C. Wang. dents in a network space. Computers, environment and urban
Sdcae: Stack denoising convolutional autoencoder model for systems, 32(5):396–406, 2008. 2
accident risk prediction via traffic big data. In 2018 Sixth [26] Z. Xie and J. Yan. Detecting traffic accident clusters with net-
International Conference on Advanced Cloud and Big Data work kernel density estimation and local spatial statistics: an
(CBD), pages 328–333, 2018. 2 integrated approach. Journal of transport geography, 31:64–
[11] Q. Chen, X. Song, H. Yamada, and R. Shibasaki. Learn- 71, 2013. 2
ing deep representation from big and heterogeneous data for [27] G. Yannis, A. Dragomanovits, A. Laiou, F. La Torre,
traffic accident inference. In Proceedings of the AAAI Con- L. Domenichini, T. Richter, S. Ruhl, D. Graham, and
ference on Artificial Intelligence, volume 30, 2016. 2 N. Karathodorou. Road traffic accident prediction mod-
[12] M. Haklay and P. Weber. Openstreetmap: User-generated elling: a literature review. In Proceedings of the institution
street maps. IEEE Pervasive Computing, 7(4), 2008. 5 of civil engineers-transport, volume 170, pages 245–254.
[13] A. Hébert, T. Guédon, T. Glatard, and B. Jaumard. High- Thomas Telford Ltd, 2017. 2
resolution road vehicle collision prediction for the city of [28] Z. Yuan, X. Zhou, and T. Yang. Hetero-convlstm: A deep
montreal. In 2019 IEEE International Conference on Big learning approach to traffic accident prediction on heteroge-
Data (Big Data), pages 1804–1813. IEEE, 2019. 2 neous spatio-temporal data. In Proceedings of the 24th ACM
[14] K. G. Le, P. Liu, and L.-T. Lin. Traffic accident hotspot iden- SIGKDD International Conference on Knowledge Discovery
tification by integrating kernel density estimation and spatial & Data Mining, pages 984–992, 2018. 2
autocorrelation analysis: a case study. International Journal [29] Z. Yuan, X. Zhou, T. Yang, J. Tamerius, and R. Mantilla. Pre-
of Crashworthiness, pages 1–11, 2020. 2 dicting traffic accidents through heterogeneous urban data: A
[15] A. S. Mohaymany, M. Shahri, and B. Mirbagheri. Gis-based case study. In Proceedings of the 6th international workshop
method for detecting high-crash-risk road segments using on urban computing (UrbComp 2017), Halifax, NS, Canada,
network kernel density estimation. Geo-spatial Information volume 14, page 10, 2017. 2
Science, 16(2):113–119, 2013. 2 [30] M. Zaheer, S. Kottur, S. Ravanbakhsh, B. Poczos,
[16] S. Moosavi, M. H. Samavatian, S. Parthasarathy, R. Teodor- R. Salakhutdinov, and A. Smola. Deep sets. arXiv preprint
escu, and R. Ramnath. Accident risk prediction based on arXiv:1703.06114, 2017. 7
heterogeneous sparse data: New dataset and insights. In Pro- [31] Z. Zhou, Y. Wang, X. Xie, L. Chen, and C. Zhu. Fore-
ceedings of the 27th ACM SIGSPATIAL International Con- see urban sparse traffic accidents: A spatiotemporal multi-
ference on Advances in Geographic Information Systems, granularity perspective. IEEE Transactions on Knowledge
pages 33–42, 2019. 2, 5, 6 and Data Engineering, 2020. 2
11985