0% found this document useful (0 votes)
27 views86 pages

M3 Final Documentation

The document presents a mini project thesis focused on predicting the severity of flight accidents and identifying their causes using machine learning techniques. The study claims to improve prediction accuracy to 85% compared to conventional methods, emphasizing the importance of enhanced models for aviation safety. The project is submitted by a group of students from the Indur Institute of Engineering and Technology under the guidance of Ms. K Kiranmai.

Uploaded by

SANDEEP KUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views86 pages

M3 Final Documentation

The document presents a mini project thesis focused on predicting the severity of flight accidents and identifying their causes using machine learning techniques. The study claims to improve prediction accuracy to 85% compared to conventional methods, emphasizing the importance of enhanced models for aviation safety. The project is submitted by a group of students from the Indur Institute of Engineering and Technology under the guidance of Ms. K Kiranmai.

Uploaded by

SANDEEP KUMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

SEVERITY LEVEL PREDICTION AND FINDING

CAUSE IN FLIGHT ACCIDENTS USING


MACHINE LEARNING
A Mini Project thesis submitted to the JAWAHARLAL NEHRU TECHNOLOGICAL
UNIVERSITY HYDERABAD in partial fulfilment of the requirement for the award of
the degree of
BACHELOR OF TECHNOLOGY
In
Artificial Intelligence & Machine Learning
Submitted by

Ch. Sathwik : 22D31A6609


MD.Awese Ali : 22D31A6634
G.Amulya : 22D31A6617
A.Varshini : 22D31A6603

Under the Guidance of

Ms K KIRANMAI

Asst. Professor, Dept. of CSE

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

INDUR INSTITUTE OF ENGINEERING AND TECHNOLOGY


(Affiliated to J.N.T.U.H, Hyderabad)
Ponnala (Vil), Siddipet (Dist.), Telangana State – 502 277.

June 2025
Date: / /2025

CERTIFICATE

This is to certify that the “SEVERITY LEVEL PREDICTION AND FINDING


CAUSE IN FLIGHT ACCIDENTS USING MACHINE LEARNING” being
submitted by

Ch. Sathwik 22D31A6609


MD.Awese Ali 22D31A6634
G.Amulya 22D31A6617
A.Varshini 22D31A6603

In partial fulfilment for the award of “BACHELOR OF TECHNOLOGY” in the


Department of “COMPUTER SCIENCE & ENGINEERING”(B.Tech) to the
“JAWAHARLAL NEHURU TECHNOLOGY UNIVERSITY HYDERABAD” is a
record of bonafide Mini Project Work carried out by them under our guidance and
supervision.

The results embodied in this for have not been submitted to kind of Any other
University or Institute for the award for any degree or diploma.

Ms K KIRANMAI Dr T. BENARJI
PROJECT GUIDE. Professor &
Asst. Professor, Dept. of CSE Head of the Dept -CSE

EXTERNAL EXAMINER
ACKNOWLEDGEMENT
We are thankful to Ms. Kiranmai, Project Guide, Asst. Prof., Dept. of CSE,

who guided us a lot by her favorable suggestions to complete my project. She search-
oriented personality with higher-end technical exposure.

We are thankful to Dr. T. Benarji, Head, Dept. of CSE, Indur Institute of


Engineering & Technology, for extending his help in the department’s academic
activities during the course duration. He is a dynamic, enthusiastic personality in
academic activities.

We extend our thanks to Dr. V.P. Raju, Principal, Indur Institute of


Engineering &Technology, Siddipet, for extending his help throughout the duration of
this project.

We sincerely acknowledge all the lecturers of the Dept. of CSE for their
motivation during my B. Tech course.

We would like to say thanks to all my friends for their timely help

and encouragement.

Ch. Sathwik 22D31A6609

22D31A6634
MD.Awese Ali

22D31A6617
G.Amulya

22D31A6603
A.Varshini

i
DECLARATION

We hereby declare that the project entitled “SEVERITY LEVEL


PREDICTION AND FINDING CAUSE IN FLIGHT ACCIDENTS USING
MACHINE LEARNING” submitted in the partial fulfilment of the requirement for the
award of the degree of Bachelor of Technology in Computer Science and Engineering.
This dissertation is our original work, and the project has not formed the basis for the
award of any degree, associate, fellowship, or any other similar titles, and no part of it
has been published or sent for publication at the time of submission.

BY

Ch. Sathwik 22D31A6609


MD.Awese Ali 22D31A6634
G.Amulya 22D31A6617
A.Varshini 22D31A6603

ii
ABSTRACT

The safety of the airlines and their passengers should be our top priority. Various
safety checks are performed continuously and manually round-the-clock, and the airline
team takes care of all safety precautions and measures, but there are still some cases of
accidents due to a variety of factors. To improve aviation safety and stop future
accidents, it is essential to estimate how severe a flying mishap would be. In this study,
we provide a method for estimating the seriousness of flying incidents. Our findings
show that the suggested method beats conventional machine learning methods,
predicting the severity of aviation accidents with an accuracy of up to 85%. Our work
stresses the value of enhancing the effectiveness of models for predicting the
seriousness of aircraft accidents. The suggested method may be applied by regulators
and specialists in aviation safety to improve aircraft safety by creating more potent
accident prevention measures.

iii
INDEX

CONTENTS PAGE NO.

ACKNOWLEDGEMENT i

DECLARATION ii

ABSTRACT iii

INDEX iv

LIST OF FIGURES viii - ix

LIST OF TABLES ix

CHAPTER 1: INTRODUCTION 1-5

1.1 Literature Survey 2-5

CHAPTER 2: SYSTEM ANALYSIS 6 - 36

2.1 Existing system 6

2.1.1 Aviation Incident Databases (Advantages &


6
Disadvantages)

2.1.2 Rule Based System (Advantages & Disadvantages) 6

2.2 Proposed system 6

2.2.1 Advantages of proposed system 6

2.2.2 Disadvantages of proposed system 7

2.3 Feasibility Study 7-9

2.3.1 Economical Feasibility 7

2.3.2 Technical Feasibility 8

2.3.3 Social Feasibility 8

iv
2.4 Requirement Analysis 8

2.5 Requirement specification 8-9

2.6 System Specification 9 - 10

2.6.1 Hardware Requirements 9

2.6.2 Software Requirements 10

2.7 System Environments 10 - 36

2.7.1 Python 10 - 25

2.7.2 Django 26 - 36

CHAPTER 3: SYSTEM DESIGN 37 - 43

3.1 System Architecture 37

3.2 Data Flow Diagram 38

3.3 UML Diagrams 39 - 43

3.3.1. Use Case Diagram 40

3.3.2. Class Diagram 41

3.3.3. Sequence Diagram 42

3.3.4. Activity Diagram 43

CHAPTER 4: IMPLEMENTATION 44 - 46

4.1 MODULES 44

4.2 Modules Description 44

4.2.1 User 44

4.2.2 Admin 44

v
4.2.3 ML 44 - 45

4.3 INPUT AND OUTPUT DESIGN 45 - 47

4.3.1 Input Design 45 - 46

4.3.2 Output Design 46 - 47

CHAPTER 5 : RESULTS 48 - 53

CHAPTER 6:SYSTEM TESTING 54 - 58

6.1 Unit testing 54

6.2 Integration testing 54

6.3 Functional test 55

6.4 System Test 55

6.5 White Box Testing 55 - 56

6.6 Black Box Testing 56

6.7 Unit Testing 56

6.8 Test strategy and approach 56 - 57

6.8.1 Test objectives 56

6.8.2 Integration Testing 57

6.8.3 Acceptance Testing 57

6.9 TESTCASES: 58

6.9.1 Sample Test Cases 58

CONCLUSION 59

vi
FUTURE ENHANCEMENT 60 - 61

BIBLIOGRAPHY 62 - 63

APPENDICES 64 - 75

vii
LIST OF FIGURES

FIGURE NO. FIGURE NAME PAGE NO.

Fig 2.7.2(a) Django Architecture 26

Fig 2.7.2(b) Model View Template Architecture 27

Fig 3.1 System Architecture 37

Fig 3.2 Data Flow Diagram For User 38

Fig 3.3.1 Use Case Diagram For User 40

Fig 3.3.2 Class Diagram 41

Fig 3.3.3 Sequence Diagram 42

Fig 3.3.4 Activity Diagram 43

Fig 5.1 Home Page 48

Fig 5.2 Register Form 48

Fig 5.3 Admin Login 49

Fig 5.4 Admin Home Page 49

Fig 5.5 User Details 50

Fig 5.6 User Login Page 50

Fig 5.7 User Home Page 51

Fig 5.8 Prediction Form 51

Fig 5.9 Predicted Outcome 52

Fig 5.10 Machine Learning Score 52

viii
Fig 5.11 DataSet View 53

Fig 5.12 Machine Learning Graphs 53

LIST OF TABLES

TABLE NO. TABLE NAME TABLE NO.

Table 6.9.1 Table showing various test cases 58

ix
CHAPTER 1
INTRODUCTION
Airlines now fly millions of people and tonnes of cargo around the world every
day as a result of the aviation industry's considerable growth over the years. The amount
of data collected grows along with the industry's expansion, necessitating the use of
increasingly effective data analysis methods. One such method is data mining, which
may be used to draw important conclusions from big datasets[11][12]. It entails seeing
trends, correlations, and connections in the data that may be utilized to guide judgment
calls. Expertise in data mining methods and tools is another challenge. Alongside
statistics, machine learning, and data visualizations, data mining calls for specialized
abilities and expertise. To make sure that the data mining findings are appropriate,
useful, and intelligible, aviation experts and data scientists must collaborate and
communicate. The potential rewards of data mining in aviation are enormous,
notwithstanding these difficulties, and there is a rising demand for specialists in this
area[12][13].

1
1.1 LITERATURE SURVEY
1.1.1 Aviation Accident Analysis Using Data Mining Techniques
Authors: Jianfeng Zhang and Hao Jiang in the Journal of Transportation Technologies
(2012)
Chemical manufacturing is a long-process industry, where an end product may
pass through numerous dangerous and complex steps. In such long chains of
coordinated activity, accidents remain common. This study made loss-prevention
recommendations for the chemical industry after conducting a review of accident
reports and creating a complex network model. A human factor analysis and
classification system (HFACS) was used to classify data from 109 investigation reports
from the Chinese mainland (2015–2020). Levels Ⅱ and Ⅲ of the HFACS output were
fed into a complex network model to generate a map of causes and chains of risk. It was
shown that most accidents were directly or indirectly caused by human action, and
human factors played a decisive role in occurrence, evolution, and resolution. The
model used was visualized in Gephi, and the key cause nodes were identified by their
topological characteristics. A modularity algorithm was used to derive the community
structures and segment the network map. Crucial nodes in each community were
compared with factors for each class in the HFACS model. It was also found that there
was a biasing factor in the causal processes of explosive accidents and poisoning and
asphyxiation accidents according to the associations classified by modularity. Risk
abatement strategies were proposed for the crucial factors.
1.1.2 Data Mining Techniques for Aviation Safety
AUTHORS: Iryna Yevseyeva and Nataliia Kovtun in the International Journal of
Applied Engineering Research (2016)
Predicting the sales of a product or demand for a service is an utmost need in
any industry. With the changes and increase in the channels and modes through which
the products are sold, the prediction of sales in the future becomes tedious. The number
of features that would help in predicting sales differs and increases. This leads to the
usage of machine Learning and Deep Learning Models in sales forecasting. A deep

2
survey of various works that employ machine learning and Deep learning approaches
for sales prediction is done and inferences are made. Every work
studied has a list of models which are used as baseline models for comparison and the
same is listed for better inferences. Works that address the problem of predicting the
sales of new products are also discussed. A list of publicly available sales forecasting
datasets is also given.
1.1.3 A Data Mining Approach to Airline Pricing
AUTHORS :Stefan Wörner and Christof Weinhardt in the Journal of Revenue and
Pricing Management

The blockchain has reached the tip of a global hype across a variety of
industries. The potential of this technology, inter alia building the fundament of
Bitcoin, is assumed to be immense and disruptive – particularly for the financial
industry. FinTech start-ups as well as established players however are just about to
explore the true potential of blockchain technology as the fundament of (financial)
markets. Before this backdrop, Information Systems research is making valuable
contributions to the field by integrating the technical view on blockchain with
interdis-ciplinary research approaches. Our contribution to the growing body of
Information Systems literature in the context of the blockchain is twofold: First, we
conduct a comprehensive litera-ture review of the most relevant and recent IS
research on blockchain. Second, based on the findings of our review, we build on
existing research and propose a Blockchain Market Engi-neering Framework, which
can support researchers as well as practitioners in analyzing and designing the
elements of blockchain-based markets on an individual and global level. In addi-
tion, we go beyond a purely analytical perspective and provide a toolbox to support
the active construction of blockchain-based ecosystems and infrastructures. In
doing so we pave the way for future research that will help to break down the
blockchain hype.

3
1.1.4 Optimised Levenshtein centroid cross-layer defence for multi-hop cognitive
radio networks. IET Communications, 15(2), 245-256
AUTHORS: Ganesh, D., Kumar, T. P., & Kumar, M. S. (2021)
Cognitive radio networks (CRN) make use of dynamic spectrum access to
communicate opportunistically. Unlicensed users severely affect the spectrum sensing
outcomes in CRN. Primary user emulation attack (PUEA) and spectrum sensing data
falsification (SSDF) have become a paramount concern in CRNs. It is especially
challenging when both masquerading (in the physical layer) and falsification (in the data
link layer) occur by providing false spectrum reports. Existing methods to detect such
attacks cannot be utilised in scenarios with multi-hop CRN. In this study, to mitigate
attack against PUEA and SSDF, a method called optimised sensing and Levenshtein
nearest centroid classification (OS-LNCC) for multi-hop CRN is presented. First, a
network model for multi-hop CRN is designed. Next, a probable density optimal logical
sensing model is designed to alleviate the problems related to falsification of spectrum
reports. Here, the falsification of spectrum reports is overcome by exploiting dual
factors, that is, probability for false alarm and probability for detection according to the
departure rate of primary user (PU). With these dual factors, optimal logical sensing is
made, therefore improving the throughput with minimum delay. Finally, each cognitive
radio (CR) user evaluates its current sensing information to existing sensing classes
through the Levenshtein distance function. Based on quantitative variables, the
prediction function of each sensing class is measured using nearest centroid (NC)
classifier and the sensing report is classified into either presence or absence of PU.
These predictive classes are then integrated at the fusion centre so that robust mitigation
against PUEA and SSDF is made. Computer simulation outputs show that OS-LNCC
method performs better than the conventional methods using metrics such as sensing
delay by 47%, percentage of error in prediction by 46% and throughput by 45%.

4
1.1.5 Internet of things: IETF protocols, algorithms and applications
AUTHORS : Kumar, M. Sunil, and K. Jyothi Prakash.
Airborne diseases cause detriment in the human life. Many were found in history
such as TB, SARS, MERS and recently COVID 19. These diseases hit the dead rate and
crushes health and wealth of the world population. Mostly, airborne diseases will spread
rapidly in crowdy places. Especially, in case of COVID-19, Wearing mask and
monitoring body temperature by individual is good solution to prevent rapid spread of
the disease. So, keeping safety measures in monitoring face mask and body temperature
is crucial in crowdy places such as Airports, railway stations, Bus Stations, malls,
temples, etc. is obligatory. With a focus on emphasizing the health of the people we
proposed integrated system that monitors body temperature and face mask of each
individual and open/close pathway gate to allow after knee verification. Proposed
Prototype uses Raspberry pi to monitor Face mask using CNN and Arduino to monitor
body temperature and enable motor drivers to open or close the pathway Gate.
Efficiency and loss of Proposed CNN model was trained and tested with multiple
epoches..

5
CHAPTER 2
SYSTEM ANALYSIS

2.1 EXISTING SYSTEM


2.1.1. Aviation Incident Databases (e.g., FAA, NTSB):
Advantages: These databases contain historical data on aviation incidents and
accidents, which can be used for analysis and modeling. They provide a
foundation for understanding past occurrences.
Disadvantages: Data might be limited, not uniformly structured, or contain
biases. They may lack certain crucial details or comprehensive information
required for robust predictive models.
2.1.2. Rule-Based Systems:
Advantages: Some aviation safety systems rely on predefined rules and
thresholds to identify potential hazards or predict severity levels based on
specific parameters.
Disadvantages: These systems might not adapt well to complex and evolving
scenarios. They could struggle to capture nuanced relationships between various
factors leading to accidents.

2.2 PROPOSED SYSTEM


Machine Learning-Based Predictive Model:
2.2.1Advantages:
Predictive Power: Machine learning models can learn complex patterns and
relationships from large datasets, potentially leading to more accurate
predictions.
Adaptability: These models can adapt to new data and improve over time,
accommodating evolving aviation scenarios and changes in safety regulations.
Identification of Complex Patterns: They can uncover hidden patterns in data
that might not be immediately evident through traditional analysis.

6
Real-time Analysis: With appropriate infrastructure, machine learning models
can be implemented for real-time analysis of flight data.
2.2.2 Disadvantages:
Data Quality: Models heavily rely on the quality and quantity of data.
Inaccurate or biased data can lead to skewed predictions.
Interpretability: Some complex machine learning models lack interpretability,
making it challenging to understand the reasoning behind their predictions.
Computational Resources: Training sophisticated models requires significant
computational resources, potentially posing scalability challenges.

2.3 FEASIBILITY STUDY

The feasibility of the project is analyzed in this phase and business proposal is
put forth with a very general plan for the project and some cost estimates. During
system analysis the feasibility study of the proposed system is to be carried out. This is
to ensure that the proposed system is not a burden to the company. For feasibility
analysis, some understanding of the major requirements for the system is essential.

Three key considerations involved in the feasibility analysis are,

• ECONOMICAL FEASIBILITY
• TECHNICAL FEASIBILITY
• SOCIAL FEASIBILITY

2.3.1 ECONOMICAL FEASIBILITY

This study is carried out to check the economic impact that the system will have
on the organization. The amount of fund that the company can pour into the research
and development of the system is limited. The expenditures must be justified. Thus the
developed system as well within the budget and this was achieved because most of the
technologies used are freely available. Only the customized products had to be
purchased.

7
2.3.2 TECHNICAL FEASIBILITY

This study is carried out to check the technical feasibility, that is, the

technical requirements of the system. Any system developed must not have a high
demand on the available technical resources. This will lead to high demands on the
available technical resources. This will lead to high demands being placed on the client.
The developed system must have a modest requirement, as only minimal or null
changes are required for implementing this system.

2.3.3 SOCIAL FEASIBILITY

The aspect of study is to check the level of acceptance of the system by the

user. This includes the process of training the user to use the system efficiently. The user
must not feel threatened by the system, instead must accept it as a necessity. The level
of acceptance by the users solely depends on the methods that are employed to educate
the user about the system and to make him familiar with it. His level of confidence must
be raised so that he is also able to make some constructive criticism, which is
welcomed, as he is the final user of the system.

2.4 REQUIREMENT ANALYSIS


The project involved analyzing the design of few applications so as to make the
application more users friendly. To do so, it was really important to keep the navigations
from one screen to the other well ordered and at the same time reducing the amount of
typing the user needs to do. In order to make the application more accessible, the
browser version had to be chosen so that it is compatible with most of the Browsers.

2.5 REQUIREMENT SPECIFICATION

Functional Requirements

▪ Graphical User interface with the User.

8
Software Requirements

For developing the application the following are the Software Requirements:

1. Python
2. Django
Operating Systems supported

1. Windows 10 64 bit OS
Technologies and Languages used to Develop

1. Python
Debugger and Emulator

▪ Any Browser (Particularly Chrome)


Hardware Requirements

For developing the application the following are the Hardware Requirements:

▪ Processor: Intel i9
▪ RAM: 32 GB
▪ Space on Hard Disk: minimum 1 TB

2.6 SYSTEM SPECIFICATION


2.6.1 HARDWARE REQUIREMENTS

System : Intel i3

Hard Disk : 1 TB.

Monitor : 14’ Colour Monitor.

Mouse : Optical Mouse.

Ram : 4GB

9
2.6.2 SOFTWARE REQUIREMENTS

Operating system : Windows 10

Coding Language : Python

Front-End : Html. CSS

Designing : Html,css,javascript

Data Base : SQLite

2.7 SYSTEM ENVIRONMENTS

2.7.1 Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-


level programming language. An interpreted language, Python has a design philosophy
that emphasizes code readability (notably using whitespace indentation to delimit code
blocks rather than curly brackets or keywords), and a syntax that allows programmers to
express concepts in fewer lines of code than might be used in languages such as C+
+or Java. It provides constructs that enable clear programming on both small and large
scales. Python interpreters are available for many operating systems. CPython,
the reference implementation of Python, is open source software and has a community-
based development model, as do nearly all of its variant implementations. CPython is
managed by the non-profit Python Software Foundation. Python features a dynamic
type system and automatic memory management. It supports multiple programming
paradigms, including object-oriented, imperative, functional and procedural, and has a
large and comprehensive standard library.

10
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −

$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −

>>> print "Hello, Python!"


If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!");. However in Python version
2.4.3, this produces the following result −

Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script
and continues until the script is finished. When the script is finished, the interpreter is
no longer active.

Let us write a simple Python program in a script. Python files have


extension .py. Type the following source code in a test.py file −

Live Demo
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to
run this program as follows −

11
$ python test.py
This produces the following result −

Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −

Live Demo
#!/usr/bin/python

print "Hello, Python!"


We assume that you have Python interpreter available in /usr/bin directory. Now,
try to run this program as follows −

$ chmod +x test.py # This is to make file executable


$./test.py
This produces the following result −

Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and
manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers −

12
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.

Starting an identifier with a single leading underscore indicates that the identifier
is private.

Starting an identifier with two leading underscores indicates a strongly private


identifier.

If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.

Reserved Words
The following list shows the Python keywords. These are reserved words and
you cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

13
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example −

if True:
print "True"
else:
print "False"
However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus in Python all the continuous lines indented with same number of spaces
would form a block. The following example has various statement blocks −

Note − Do not try to understand the logic at this point of time. Just make sure
you understood various blocks even if they are without braces.

#!/usr/bin/python

import sys

14
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text

15
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow
the use of the line continuation character (\) to denote that the line should continue. For
example −

total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example,
all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.

Live Demo

16
#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment
This produces the following result −

Hello, Python!
You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment


You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be
used as a multiline comments:
'''
This is a multiline
comment.
'''
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a
blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to


terminate a multiline statement.

Waiting for the User

17
The following line of the program displays the prompt, the statement saying
“Press the enter key to exit”, and waits for the user to take action −

#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")


Here, "\n\n" is used to create two new lines before displaying the actual line.
Once the user presses the key, the program ends. This is a nice trick to keep a console
window open until the user is done with an application.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that
neither statement starts a new code block. Here is a sample snip using the semicolon.
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple Statement Groups as Suites
A group of individual statements, which make a single code block are called
suites in Python. Compound or complex statements, such as if, while, def, and class
require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon
( : ) and are followed by one or more lines which make up the suite. For example −

if expression :
suite
elif expression :
suite
else :
suite
Command Line Arguments
Many programs can be run to provide you with some basic information about
how they should be run. Python enables you to do this with -h −

18
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
You can also program your script in such a way that it should accept various
options. Command Line Arguments is an advanced topic and should be studied a bit
later once you have gone through rest of the Python concepts.
Python Lists
The list is a most versatile datatype available in Python which can be written as
a list of comma-separated values (items) between square brackets. Important thing about
a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between


square brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values.


Optionally you can put these comma-separated values between parentheses also. For
example −

19
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −

tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value −

tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated,
and so on.

Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index. For example −

Live Demo
#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following result −

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples

20
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example −

Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −

dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error as follows −

Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −

dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

21
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in the simple
example −

Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result −

dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is
a simple example −

Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'

22
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after
del dict dictionary does not exist any more −

dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys


Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For
example −

Live Demo
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}


print "dict['Name']: ", dict['Name']

23
When the above code is executed, it produces the following result −

dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example

Live Demo
#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7}


print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −

Traceback (most recent call last):


File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new tuples as
the following example demonstrates −

Live Demo
#!/usr/bin/python

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

24
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')


Delete Tuple Elements
Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example −

Live Demo
#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);


print tup;
del tup;
print "After deleting tup : ";
print tup;
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −

('physics', 'chemistry', 1997, 2000)


After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

25
2.7.2 Django
Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design. Built by experienced developers, it takes care
of much of the hassle of Web development, so you can focus on writing your app
without needing to reinvent the wheel. It’s free and open source.
Django's primary goal is to ease the creation of complex, database-driven websites.
Django emphasizes reusabilityand "pluggability" of components, rapid
development, and the principle of don't repeat yourself. Python is used throughout, even
for settings files and data models.

Fig 2.7.2(a): Django Architecture


Django also provides an optional administrative create, read, update and
delete interface that is generated dynamically through introspection and configured via
admin models

26
Fig 2.7.2(b): Model View Template Architecture

Create a Project
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and
navigate to the place you want your project to be created, then use this code −

$ django-admin startproject myproject


This will create a "myproject" folder with the following structure −

myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
The Project Structure
The “myproject” folder is just your project container, it actually contains two elements

27
manage.py − This file is kind of your project local django-admin for interacting with
your project via command line (start the development server, sync db...). To get a full
list of command accessible via manage.py you can use the code −

$ python manage.py help


The “myproject” subfolder − This folder is the actual python package of your project. It
contains four files −

__init__.py − Just for python, treat this folder as package.

settings.py − As the name indicates, your project settings.

urls.py − All links of your project and the function to call. A kind of ToC of your
project.

wsgi.py − If you need to deploy your project over WSGI.

Setting Up Your Project


Your project is set up in the subfolder myproject/settings.py. Following are some
important options you might need to set −

DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets
you get more information about your project's error. Never set it to ‘True’ for a live
project. However, this has to be set to ‘True’ if you want the Django light server to serve
static files. Do it only in the development mode.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',

28
'NAME': 'database.sql',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Database is set in the ‘Database’ dictionary. The example above is for SQLite
engine. As stated earlier, Django also supports −

MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.

You can also set others options like: TIME_ZONE, LANGUAGE_CODE,


TEMPLATE…

Now that your project is created and configured make sure it's working −

$ python manage.py runserver


You will get something like the following on running the above code −

Validating models...

0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/

29
Quit the server with CONTROL-C.

A project is a sum of many applications. Every application has an objective and


can be reused into another project, like the contact form on a website can be an
application, and can be reused for others. See it as a module of your project.

Create an Application
We assume you are in your project folder. In our main “myproject” folder, the
same folder then manage.py −

$ python manage.py startapp myapp


You just created myapp application and like project, Django create a “myapp”
folder with the application structure −

myapp/
__init__.py
admin.py
models.py
tests.py
views.py
__init__.py − Just to make sure python handles this folder as a package.

admin.py − This file helps you make the app modifiable in the admin interface.

models.py − This is where all the application models are stored.

tests.py − This is where your unit tests are.

views.py − This is where your application views are.

30
Get the Project to Know About Your Application
At this stage we have our "myapp" application, now we need to register it with
our Django project "myproject". To do so, update INSTALLED_APPS tuple in the
settings.py file of your project (add your app name) −

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
Creating forms in Django, is really similar to creating a model. Here again, we
just need to inherit from Django class and the class attributes will be the form fields.
Let's add a forms.py file in myapp folder to contain our app forms. We will create a
login form.

myapp/forms.py

#-*- coding: utf-8 -*-


from django import forms

class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput())
As seen above, the field type can take "widget" argument for html rendering; in
our case, we want the password to be hidden, not displayed. Many others widget are
present in Django: DateInput for dates, CheckboxInput for checkboxes, etc.

31
Using Form in a View
There are two kinds of HTTP requests, GET and POST. In Django, the request
object passed as parameter to your view has an attribute called "method" where the type
of the request is set, and all data passed via POST can be accessed via the request.POST
dictionary.

Let's create a login view in our myapp/views.py −

#-*- coding: utf-8 -*-


from myapp.forms import LoginForm

def login(request):
username = "not logged in"

if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)

if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = Loginform()

return render(request, 'loggedin.html', {"username" : username})


The view will display the result of the login form posted through the
loggedin.html. To test it, we will first need the login form template. Let's call it
login.html.

<html>

32
<body>

<form name = "form" action = "{% url "myapp.views.login" %}"


method = "POST" >{% csrf_token %}

<div style = "max-width:470px;">


<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Identifiant" name = "username" />
</center>
</div>

<br>

<div style = "max-width:470px;">


<center>
<input type = "password" style = "margin-left:20%;"
placeholder = "password" name = "password" />
</center>
</div>

<br>

<div style = "max-width:470px;">


<center>

<button style = "border:0px; background-color:#4285F4; margin-top:8%;


height:35px; width:80%;margin-left:19%;" type = "submit"
value = "Login" >
<strong>Login</strong>

33
</button>

</center>
</div>

</form>

</body>
</html>
The template will display a login form and post the result to our login view
above. You have probably noticed the tag in the template, which is just to prevent
Cross-site Request Forgery (CSRF) attack on your site.

{% csrf_token %}
Once we have the login template, we need the loggedin.html template that will
be rendered after form treatment.

<html>

<body>
You are : <strong>{{username}}</strong>
</body>

</html>
Now, we just need our pair of URLs to get started: myapp/urls.py

from django.conf.urls import patterns, url


from django.views.generic import TemplateView

urlpatterns = patterns('myapp.views',

34
url(r'^connection/',TemplateView.as_view(template_name = 'login.html')),
url(r'^login/', 'login', name = 'login'))
When accessing "/myapp/connection", we will get the following
login.html template rendered −
Setting Up Sessions
In Django, enabling session is done in your project settings.py, by adding some
lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This
should be done while creating the project, but it's always good to know, so
MIDDLEWARE_CLASSES should have −

'django.contrib.sessions.middleware.SessionMiddleware'
And INSTALLED_APPS should have −

'django.contrib.sessions'
By default, Django saves session information in database (django_session table
or collection), but you can configure the engine to store information using other ways
like: in file or in cache.

When session is enabled, every request (first argument of any view in Django)
has a session (dict) attribute.

Let's create a simple sample to see how to create and save sessions. We have
built a simple login system before (see Django form processing chapter and Django
Cookies Handling chapter). Let us save the username in a cookie so, if not signed out,
when accessing our login page you won’t see the login form. Basically, let's make our
login system we used in Django Cookies handling more secure, by saving cookies
server side.

For this, first lets change our login view to save our username cookie server side −

35
def login(request):
username = 'not logged in'

if request.method == 'POST':
MyLoginForm = LoginForm(request.POST)

if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
request.session['username'] = username
else:
MyLoginForm = LoginForm()
return render(request, 'loggedin.html', {"username" : username}
Then let us create formView view for the login form, where we won’t display the form
if cookie is set −

def formView(request):
if request.session.has_key('username'):
username = request.session['username']
return render(request, 'loggedin.html', {"username" : username})
else:
return render(request, 'login.html', {})
Now let us change the url.py file to change the url so it pairs with our new view −

from django.conf.urls import patterns, url


from django.views.generic import TemplateView

urlpatterns = patterns('myapp.views',
url(r'^connection/','formView', name = 'loginform'),
url(r'^login/', 'login', name = 'login'))
When accessing /myapp/connection, you will get to see the following page

36
CHAPTER 3

SYSTEM DESIGN

3.1 SYSTEM ARCHITECTURE

Fig 3.1:System Architecture

37
3.2 DATA FLOW DIAGRAM

1. The DFD is also called as bubble chart. It is a simple graphical formalism that can
be used to represent a system in terms of input data to the system, various
processing carried out on this data, and the output data is generated by this system.
2. The data flow diagram (DFD) is one of the most important modeling tools. It is
used to model the system components. These components are the system process,
the data used by the process, an external entity that interacts with the system and
the information flows in the system.
3. DFD shows how the information moves through the system and how it is modified
by a series of transformations. It is a graphical technique that depicts information
flow and the transformations that are applied as data moves from input to output.
4. DFD is also known as bubble chart. A DFD may be used to represent a system at
any level of abstraction. DFD may be partitioned into levels that represent
increasing information flow and functional detail.

Fig 3.2 Data Flow Diagram For User

38
3.3 UML DIAGRAMS

UML stands for Unified Modeling Language. UML is a standardized general-


purpose modeling language in the field of object-oriented software engineering. The
standard is managed, and was created by, the Object Management Group.
The goal is for UML to become a common language for creating models of
object oriented computer software. In its current form UML is comprised of two major
components: a Meta-model and a notation. In the future, some form of method or
process may also be added to; or associated with, UML.
The Unified Modeling Language is a standard language for specifying,
Visualization, Constructing and documenting the artifacts of software system, as well as
for business modeling and other non-software systems.
The UML represents a collection of best engineering practices that have proven
successful in the modeling of large and complex systems.
The UML is a very important part of developing objects oriented software and
the software development process. The UML uses mostly graphical notations to express
the design of software projects.

GOALS:
The Primary goals in the design of the UML are as follows:
1. Provide users a ready-to-use, expressive visual modeling Language so that they can
develop and exchange meaningful models.
2. Provide extendibility and specialization mechanisms to extend the core concepts.
3. Be independent of particular programming languages and development process.
4. Provide a formal basis for understanding the modeling language.
5. Encourage the growth of OO tools market.
6. Support higher level development concepts such as collaborations, frameworks,
patterns and components.
7. Integrate best practices.

39
3.3.1 Use Case Diagram

A use case diagram in the Unified Modeling Language (UML) is a type of


behavioral diagram defined by and created from a Use-case analysis. Its purpose is to
present a graphical overview of the functionality provided by a system in terms of
actors, their goals (represented as use cases), and any dependencies between those use
cases. The main purpose of a use case diagram is to show what system functions are
performed for which actor. Roles of the actors in the system can be depicted.

Fig 3.3.1 Use Case Diagram

40
3.3.2 Class Diagram

In software engineering, a class diagram in the Unified Modeling Language


(UML) is a type of static structure diagram that describes the structure of a system by
showing the system's classes, their attributes, operations (or methods), and the
relationships among the classes. It explains which class contains information.

Fig 3.3.2 Class Diagram

41
3.3.3 Sequence Diagram

A sequence diagram in Unified Modeling Language (UML) is a kind of


interaction diagram that shows how processes operate with one another and in what
order. It is a construct of a Message Sequence Chart. Sequence diagrams are sometimes
called event diagrams, event scenarios, and timing diagrams.

Fig 3.3.3 Sequence Diagram

42
3.3.4 Activity Diagram
Activity diagrams are graphical representations of workflows of stepwise
activities and actions with support for choice, iteration and concurrency. In the Unified
Modeling Language, activity diagrams can be used to describe the business and
operational step-by-step workflows of components in a system. An activity diagram
shows the overall flow of control.

Fig 3.3.4 Activity Diagram

43
CHAPTER 4

IMPLEMENTATION

4.1 MODULES

● User
● Admin
● ML Techniques

4.2 MODULES DESCRIPTION

4.2.1 User:
The User can register the first. While registering he required a valid user email
and mobile for further communications. Once the user registers, then admin can activate
the customer. Once the admin activates the customer then the customer can login into
our system. After login he can add the data to predict the traffic prediction . After adding
the data we can find the prediction of the algorithm. First we can find the svm algorithm
and then we can find the random forest algorithm.

4.2.2 Admin:
Admin can login with his credentials. Once he logs in he can activate the users.
The activated user only login in our applications. The admin can set the predictions of
algorithms.Admin can predict random forest algorithms and also predict the support
vector machine algorithm. The admin can add new data to the dataset.

4.2.3 ML:
Decision Tree Classifier:
The Decision Tree Classifier is a versatile and intuitive supervised learning
algorithm used for both classification and regression tasks. Operating by partitioning the
feature space into a hierarchical structure of decisions, it sequentially selects the most

44
influential features to create a tree-like structure, aiding in decision-making. Known for
its simplicity and interpretability, it breaks down complex decisions into a series of
understandable rules. However, it's prone to overfitting with intricate datasets and
struggles to capture relationships between features that require nonlinear
representations. Despite this, its transparency and ease of implementation make it a
valuable tool in various domains for initial analysis and explanation.

Gradient Boosting:
Gradient Boosting is an ensemble learning technique that builds predictive
models in a sequential manner, combining the strengths of multiple weak learners to
create a robust, accurate model. It operates by iteratively improving upon its
predecessor's weaknesses, focusing on areas where earlier models performed poorly. By
minimizing errors through the use of gradients, it constructs subsequent models that
concentrate on rectifying the residual errors of the previous ones. Gradient Boosting,
represented by algorithms like XGBoost and LightGBM, excels in handling diverse data
types, dealing with complex relationships, and typically delivers high predictive
accuracy. However, its training process can be computationally intensive, demanding
careful parameter tuning to prevent overfitting.

4.3 INPUT AND OUTPUT DESIGN


4.3.1 Input Design

The input design is the link between the information system and the user. It
comprises the developing specification and procedures for data preparation and those
steps are necessary to put transaction data in to a usable form for processing can be
achieved by inspecting the computer to read data from a written or printed document or
it can occur by having people keying the data directly into the system. The design of
input focuses on controlling the amount of input required, controlling the errors,
avoiding delay, avoiding extra steps and keeping the process simple. The input is

45
designed in such a way so that it provides security and ease of use with retaining the
privacy. Input Design considered the following things:

➢ What data should be given as input?


➢ How the data should be arranged or coded?
➢ The dialog to guide the operating personnel in providing input.
➢ Methods for preparing input validations and steps to follow when error occur

Objectives

1.Input Design is the process of converting a user-oriented description of the


input into a computer-based system. This design is important to avoid errors in the data
input process and show the correct direction to the management for getting correct
information from the computerized system.

2. It is achieved by creating user-friendly screens for the data entry to handle


large volume of data. The goal of designing input is to make data entry easier and to be
free from errors. The data entry screen is designed in such a way that all the data
manipulates can be performed. It also provides record viewing facilities.

3.When the data is entered it will check for its validity. Data can be entered with
the help of screens. Appropriate messages are provided as when needed so that the user
will not be in maize of instant. Thus the objective of input design is to create an input
layout that is easy to follow

4.3.2 Output Design

A quality output is one, which meets the requirements of the end user and
presents the information clearly. In any system results of processing are communicated
to the users and to other system through outputs. In output design it is determined how
the information is to be displaced for immediate need and also the hard copy output. It
is the most important and direct source information to the user. Efficient and intelligent
output design improves the system’s relationship to help user decision-making

46
1. Designing computer output should proceed in an organized, well thought out
manner; the right output must be developed while ensuring that each output element is
designed so that people will find the system can use easily and effectively. When
analysis design computer output, they should Identify the specific output that is needed
to meet the requirements.

2.Select methods for presenting information.

3.Create document, report, or other formats that contain information produced


by the system.

The output form of an information system should accomplish one or more of the
following objectives.

• Convey information about past activities, current status or projections of the


• Future.
• Signal important events, opportunities, problems, or warnings.
• Trigger an action.
• Confirm an action.

47
CHAPTER 5
RESULTS

SCREENS
5.1 HOME PAGE

Fig 5.1 Home Page

5.2 REGISTER FORM

Fig 5.2 Register Form

48
5.3 ADMIN LOGIN

Fig 5.3 Admin Login

5.4 ADMIN HOME PAGE

Fig 5.4 Admin Home Page

49
5.5 USER DETAILS

Fig 5.5 User Details

5.6 USER LOGIN PAGE

Fig 5.6 User Login Page

50
5.7 USER HOME PAGE

Fig 5.7 User Home Page

5.8 PREDICTION FORM

Fig 5.8 Prediction Form

51
5.9 PREDICTED OUTCOME

Fig 5.9 Predicted Outcome

5.10 MACHINE LEARNING SCORE

Fig 5.10 Machine Learning Score

52
5.11 DATASET VIEW

Fig 5.11 DataSet View

5.12 MACINE LEARNING GRAPHS

Fig 5.12 Machine Learning Graphs

53
CHAPTER 6
SYSTEM TESTING
The purpose of testing is to discover errors. Testing is the process of trying to
discover every conceivable fault or weakness in a work product. It provides a way to
check the functionality of components, sub assemblies, assemblies and/or a finished
product It is the process of exercising software with the intent of ensuring that the
Software system meets its requirements and user expectations and does not fail in an
unacceptable manner. There are various types of test. Each test type addresses a specific
testing requirement
TYPES OF TESTS
6.1 UNIT TESTING
Unit testing involves the design of test cases that validate that the internal
program logic is functioning properly, and that program inputs produce valid outputs.
All decision branches and internal code flow should be validated. It is the testing of
individual software units of the application .it is done after the completion of an
individual unit before integration. This is a structural testing, that relies on knowledge
of its construction and is invasive. Unit tests perform basic tests at component level and
test a specific business process, application, and/or system configuration. Unit tests
ensure that each unique path of a business process performs accurately to the
documented specifications and contains clearly defined inputs and expected results.
6.2 INTEGRATION TESTING
Integration tests are designed to test integrated software components to
determine if they actually run as one program. Testing is event driven and is more
concerned with the basic outcome of screens or fields. Integration tests demonstrate that
although the components were individually satisfaction, as shown by successfully unit
testing, the combination of components is correct and consistent. Integration testing is
specifically aimed at exposing the problems that arise from the combination of
components.

54
6.3 FUNCTIONAL TEST
Functional tests provide systematic demonstrations that functions tested are
available as specified by the business and technical requirements, system
documentation, and user manuals.
Functional testing is centered on the following items:
Valid Input : identified classes of valid input must be accepted.
Invalid Input : identified classes of invalid input must be rejected.
Functions : identified functions must be exercised.
Output : identified classes of application outputs must be exercised.
Systems/Procedures : interfacing systems or procedures must be invoked.
Organization and preparation of functional tests is focused on
requirements, key functions, or special test cases. In addition, systematic coverage
pertaining to identify Business process flows; data fields, predefined processes, and
successive processes must be considered for testing. Before functional testing is
complete, additional tests are identified and the effective value of current tests is
determined. 6.4 System Test
System testing ensures that the entire integrated software system meets
requirements. It tests a configuration to ensure known and predictable results. An
example of system testing is the configuration oriented system integration test. System
testing is based on process descriptions and flows, emphasizing pre-driven process links
and integration points.
6.4 SYSTEM TEST
System testing ensures that the entire integrated software system meets
requirements. It tests a configuration to ensure known and predictable results. An
example of system testing is the configuration oriented system integration test. System
testing is based on process descriptions and flows, emphasizing pre-driven process links
and integration point
6.5 WHITE BOX TESTING
White Box Testing is a testing in which in which the software tester has
knowledge of the inner workings, structure and language of the software, or at least its

55
purpose. It is purpose. It is used to test areas that cannot be reached from a black box
level.

6.6 BLACK BOX TESTING


Black Box Testing is testing the software without any knowledge of the inner
workings, structure or language of the module being tested. Black box tests, as most
other kinds of tests, must be written from a definitive source document, such as
specification or requirements document, such as specification or requirements
document. It is a testing in which the software under test is treated, as a black box .you
cannot “see” into it. The test provides inputs and responds to outputs without
considering how the software works.
6.7 UNIT TESTING

Unit testing is usually conducted as part of a combined code and unit test phase
of the software lifecycle, although it is not uncommon for coding and unit testing to be
conducted as two distinct phases.

6.8 TEST STRATEGY AND APPROACH

Field testing will be performed manually and functional tests will be written in
detail.

6.8.1 Test objectives

• All field entries must work properly.


• Pages must be activated from the identified link.
• The entry screen, messages and responses must not be delayed.
Features to be tested

• Verify that the entries are of the correct format


• No duplicate entries should be allowed
• All links should take the user to the correct page.

56
6.8.2 Integration Testing
Software integration testing is the incremental integration testing of two or more
integrated software components on a single platform to produce failures caused by
interface defects.
The task of the integration test is to check that components or software
applications, e.g. components in a software system or – one step up – software
applications at the company level – interact without error.
Test Results: All the test cases mentioned above passed successfully. No defects
encountered.
6.8.3 Acceptance Testing
User Acceptance Testing is a critical phase of any project and requires
significant participation by the end user. It also ensures that the system meets the
functional requirements.
Test Results: All the test cases mentioned above passed successfully. No defects
encountered.

57
6.9 TESTCASES:
6.9.1 Sample Test Cases

Remarks
S.no Test Case Excepted Result Result
(IF Fails)
If already user
If User registration
1 User Register Pass email exist then
successfully.
it fails.
If Username and password is Un Register
2 User Login correct then it will getting Pass Users will not
valid page. logged in.
Generated if
3 Dataset Dataset will be viewed Pass
input is true
Input is not
Predicted the output value given output
4 prediction Pass
based on input values won’t be
generated
Generated will
Graphs will be prompted
5 Graphs Pass the user clicks
through ML the ML button
Admin can login with his Invalid login
6 Admin login login credential. If success he Pass details will not
gets his home page be allowed here
Admin can If the user did
Admin can activate the
7 activate the Pass not find it then
register user id
register users it won’t login.

Table 6.9.1 Table showing various test cases

58
CHAPTER 7

CONCLUSION

Data mining and machine learning approaches may be used to find patterns and
trends in aviation data analysis that may be challenging to spot using more conventional
analytical techniques. Machine learning algorithms, for instance, may be used to spot
trends in traveller behaviour, such as the kinds of aircraft they choose, the best times of
day to go, and the elements that affect their shopping choices. The ability to increase
operational effectiveness and cut expenses is another advantage of employing data
mining and machine learning in aviation data analysis. To assist minimize the chance of
delays or cancellations, airlines, for instance, can utilize predictive maintenance
algorithms to detect probable equipment faults before they happen..

59
CHAPTER 8
FUTURE ENHANCEMENT

1. Real-Time Monitoring and Alert Systems: Develop a system that


continuously monitors flight data in real time. This system could leverage
machine learning algorithms to detect anomalies or potential safety issues during
flights, enabling immediate alerts to be sent to relevant authorities or airline
personnel.
2. Integration of Advanced Sensors: Incorporate advanced sensors and IoT
devices within aircraft to gather more diverse and detailed data. Machine
learning models can then be trained on this richer dataset to better predict and
identify the root causes of accidents or potential hazards.

3. Multimodal Data Fusion: Combine various data sources such as flight data
recordings, weather reports, pilot communication transcripts, and maintenance
logs. Employ advanced techniques like multimodal data fusion to integrate these
disparate sources, enabling more comprehensive analysis and prediction of
accident severity and causation.

4. Explainable AI (XAI) for Transparency: Implement Explainable AI


techniques to ensure transparency and interpretability of the machine learning
models. This would help aviation experts and investigators understand how the
models arrive at their predictions, aiding in trust-building and decision-making
processes.

5. Adaptive Learning Models: Develop machine learning models that can adapt
and evolve with new data and changing circumstances. Implement continual
learning techniques so that the models can improve and stay relevant as they

60
encounter new patterns or scenarios in flight safety data.

6. Human Factor Integration: Incorporate insights from human factors studies


into the machine learning models. Consider pilot behavior, crew dynamics, and
human-machine interaction to create a more holistic understanding of potential
accident causes and severity prediction.

7. Collaborative Data Sharing: Encourage collaboration and data sharing among


airlines, aviation authorities, and researchers to create larger, more diverse
datasets. This can improve the accuracy and robustness of machine learning
models by providing access to a broader range of scenarios and incidents.

8. Predictive Maintenance: Extend the use of machine learning beyond accident


prediction to predict maintenance needs and potential system failures in aircraft.
This proactive approach can significantly enhance flight safety by addressing
issues before they escalate into accidents.

9. Ethical and Legal Considerations: Address ethical implications, privacy


concerns, and legal frameworks surrounding the use of machine learning in
aviation safety. Ensure compliance with regulations and guidelines while
maintaining a balance between innovation and safety.

10. Simulation and Scenario Modeling: Develop advanced simulation models


using machine learning to simulate various scenarios and potential accidents.
This could aid in understanding the impact of different variables and in training
pilots and crew to handle unforeseen situations.

61
CHAPTER 9

BIBLIOGRAPHY

[1] "Aviation Accident Analysis Using Data Mining Techniques" by Jianfeng Zhang
and Hao Jiang in the Journal of Transportation Technologies (2012)
[2] "Data Mining Techniques for Aviation Safety" by Iryna Yevseyeva and Nataliia
Kovtun in the International Journal of Applied Engineering Research (2016)
[3] "Analysis of Aviation Safety Data Using Data Mining Techniques" by Anjali
Tiwari and Swati Puranik in the International Journal of Computer Science and Mobile
Computing (2015)
[4] "Data Mining Techniques for Air Traffic Control" by Milena Janjevic and Ivana
Bagic in the Journal of Air Traffic Control (2014)
[5] "A Data Mining Approach for Detecting Aviation Safety Trends" by Roberto
Perini and Francesco Rizzo in the Journal of Safety Research (2014)
[6] "Data Mining Techniques for Aviation Maintenance" by Ramazan Bayindir and
M. Hakan Karabas in the International Journal of Industrial Engineering Research and
Development (2014)
[7] "A Data Mining Approach for Analyzing Aircraft Performance Data" by Ian R.
McAndrew and Peter J. Stordy in the Journal of Aircraft (2015)
[8] "Data Mining for Airline Operations" by Miguel A. Ortega-Ferreira and José Rui
Figueira in the Journal of Air Transport Management (2011)
[9] "A Data Mining Approach to Airline Pricing" by Stefan Wörner and Christof
Weinhardt in the Journal of Revenue and Pricing Management (2011)
[10] "Data Mining in Airline Revenue Management" by Martin E. Roth and Andreas
Schmid in the Journal of Revenue and Pricing Management (2010)
[11] Sreedhar, B., BE, M. S., & Kumar, M. S. (2020, October). A comparative study
of melanoma skin cancer detection in traditional and current image processing
techniques. In 2020 Fourth International Conference on I-SMAC (IoT in Social, Mobile,
Analytics and Cloud)(I-SMAC) (pp. 654-658). IEEE.

62
[12] Ganesh, D., Kumar, T. P., & Kumar, M. S. (2021). Optimised Levenshtein
centroid cross-layer defence for multi-hop cognitive radio networks. IET
Communications, 15(2), 245-256.
[13] Balaji, K., P. Sai Kiran, and M. Sunil Kumar. "Resource aware virtual machine
placement in IaaS cloud using bio-inspired firefly algorithm." Journal of Green
Engineering 10 (2020): 9315-9327.
[14] Kumar, M. Sunil, and K. Jyothi Prakash. "Internet of things: IETF protocols,
algorithms and applications." Int. J. Innov. Technol. Explor. Eng 8.11 (2019):
2853-2857.
[15] AnanthaNatarajan, V., Kumar, M. S., & Tamizhazhagan, V. (2020). Forecasting
of Wind Power using LSTM Recurrent Neural Network. Journal of Green Engineering,
10.
[16] Sangamithra, B., Neelima, P., & Kumar, M. S. (2017, April). A memetic
algorithm for multi objective vehicle routing problem with time windows. In 2017 IEEE
International Conference on Electrical, Instrumentation and Communication
Engineering (ICEICE) (pp. 1-8). IEEE.

63
CHAPTER 10

APPENDICES

Admin View.py
from django.shortcuts import render
from django.contrib import messages
from users.forms import UserRegistrationForm
from users.models import UserRegistrationModel

# Create your views here.


def AdminLoginCheck(request):
if request.method == 'POST':
usrid = request.POST.get('loginid')
pswd = request.POST.get('pswd')
print("User ID is = ", usrid)
if usrid == 'admin' and pswd == 'admin':
return render(request, 'admins/AdminHome.html')
else:
messages.success(request, 'Please Check Your Login Details')
return render(request, 'AdminLogin.html', {})

def AdminHome(request):
return render(request, 'admins/AdminHome.html',{})

def RegisterUsersView(request):
data = UserRegistrationModel.objects.all()
return render(request,'admins/viewregisterusers.html',{'data':data})

def ActivaUsers(request):

64
if request.method == 'GET':
id = request.GET.get('uid')
status = 'activated'
print("PID = ", id, status)
UserRegistrationModel.objects.filter(id=id).update(status=status)
data = UserRegistrationModel.objects.all()
return render(request,'admins/viewregisterusers.html',{'data':data})

base.html:

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">

<title>Arsha Bootstrap Template - Index</title>


<meta content="" name="description">
<meta content="" name="keywords">

<!-- Favicons -->


<link href="{% static 'assets/img/favicon.png' %}" rel="icon">
<link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon">

<!-- Google Fonts -->


<link href="https://fonts.googleapis.com/css?
family=Open+Sans:300,300i,400,400i,600,600i,700,700i|
Jost:300,300i,400,400i,500,500i,600,600i,700,700i|
Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

<!-- Vendor CSS Files -->


<link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}"
rel="stylesheet">

65
<link href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"
rel="stylesheet">
<link href="{% static 'assets/vendor/boxicons/css/boxicons.min.css' %}"
rel="stylesheet">
<link href="{% static 'assets/vendor/glightbox/css/glightbox.min.css' %}"
rel="stylesheet">
<link href="{% static 'assets/vendor/remixicon/remixicon.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/swiper/swiper-bundle.min.css' %}"
rel="stylesheet">

<!-- Template Main CSS File -->


<link href="{% static 'assets/css/style.css' %}" rel="stylesheet">

<!-- =======================================================
* Template Name: Arsha - v4.11.0
* Template URL: https://bootstrapmade.com/arsha-free-bootstrap-html-template-
corporate/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>

<body>
<style>
span{
color:deeppink;
}
header{
background-color:GREEN;
}
body{
background-image: url('{% static 'assets/img/bunny.webp' %}');
}
</style>

<!-- ======= Header ======= -->


<header id="header" class="fixed-top ">

66
<div class="container d-flex align-items-center">

<h1 class="logo me-auto"><a href="index.html"><span>Severity Level Prediction


In Flight Accident Using Ml</span></a></h1>
<!-- Uncomment below if you prefer to use an image logo -->
<!-- <a href="index.html" class="logo me-auto"><img src="assets/img/logo.png"
alt="" class="img-fluid"></a>-->

<nav id="navbar" class="navbar">


<ul>
<li><a class="nav-link scrollto active" href="{% url 'index' %}">Home</a></li>
<li><a class="nav-link scrollto" href="{% url 'AdminLogin' %}">Admin</a></
li>
<li><a class="nav-link scrollto" href="{% url 'UserLogin' %}">User</a></li>
<li><a class="nav-link scrollto" href="{% url 'UserRegister' %}">Register</
a></li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav><!-- .navbar -->

</div>
</header><!-- End Header -->

{% block contents %}

{% endblock %}

<!-- ======= Footer ======= -->


<footer id="footer">

</footer><!-- End Footer -->

<div id="preloader"></div>
<a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i
class="bi bi-arrow-up-short"></i></a>

<!-- Vendor JS Files -->

67
<script src="{% static 'assets/vendor/aos/aos.js' %}"></script>
<script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></
script>
<script src="{% static 'assets/vendor/glightbox/js/glightbox.min.js' %}"></script>
<script src="{% static 'assets/vendor/isotope-layout/isotope.pkgd.min.js' %}"></
script>
<script src="{% static 'assets/vendor/swiper/swiper-bundle.min.js' %}"></script>
<script src="{% static 'assets/vendor/waypoints/noframework.waypoints.js' %}"></
script>
<script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script>

<!-- Template Main JS File -->


<script src="{% static 'assets/js/main.js' %}"></script>
</body>
</html>

User Views.py
from ast import alias

from concurrent.futures import process


from django.shortcuts import render

# Create your views here.


from django.shortcuts import render, HttpResponse
from django.contrib import messages

import Severity_Level_Prediction_In_Flight_Accident_Using_ML

from .forms import UserRegistrationForm


from .models import UserRegistrationModel
from django.conf import settings
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

68
import datetime as dt
from sklearn import preprocessing, metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier

# Create your views here.

def UserRegisterActions(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
print('Data is Valid')
form.save()
messages.success(request, 'You have been successfully registered')
form = UserRegistrationForm()
return render(request, 'UserRegistrations.html', {'form': form})
else:
messages.success(request, 'Email or Mobile Already Existed')
print("Invalid form")
else:
form = UserRegistrationForm()
return render(request, 'UserRegistrations.html', {'form': form})

def UserLoginCheck(request):
if request.method == "POST":
loginid = request.POST.get('loginid')
pswd = request.POST.get('pswd')
print("Login ID = ", loginid, ' Password = ', pswd)
try:
check = UserRegistrationModel.objects.get(
loginid=loginid, password=pswd)
status = check.status

69
print('Status is = ', status)
if status == "activated":
request.session['id'] = check.id
request.session['loggeduser'] = check.name
request.session['loginid'] = loginid
request.session['email'] = check.email
print("User id At", check.id, status)
return render(request, 'users/UserHomePage.html', {})
else:
messages.success(request, 'Your Account Not at activated')
return render(request, 'UserLogin.html')
except Exception as e:
print('Exception is ', str(e))
pass
messages.success(request, 'Invalid Login id and password')
return render(request, 'UserLogin.html', {})

def UserHome(request):

return render(request, 'users/UserHomePage.html', {})

def DatasetView(request):
path = settings.MEDIA_ROOT + "//" + 'airplane_accident_severity.csv'
df = pd.read_csv(path, nrows=100)
df = df.to_html
return render(request, 'users/viewdataset.html', {'data': df})

def ml(request):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'C:\Users\DATA_POINT_INFO\OneDrive\Desktop\projects-
Naveen\flight\Severity_Level_Prediction_In_Flight_Accident_Using_ML\media\airpla
ne_accident_severity.csv')
df.head()
df.info()

70
df.isnull().sum()
df.describe()
df['Severity'].value_counts()
col = ['Severity','Violations','Accident_Type_Code']
train = pd.read_csv(r'C:\Users\DATA_POINT_INFO\OneDrive\Desktop\projects-
Naveen\flight\Severity_Level_Prediction_In_Flight_Accident_Using_ML\media\airpla
ne_accident_severity.csv')
train[col].astype('object').describe()
plt.figure(figsize=(12, 6))
chart = sns.boxplot(x = 'Severity', y = 'Safety_Score', data = train)
chart.set_xticklabels(chart.get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()
import warnings
warnings.filterwarnings('ignore',category=FutureWarning)
h = train.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(h)
plt.show()
from sklearn.preprocessing import LabelEncoder
en = LabelEncoder()
train['Severity']= en.fit_transform(train['Severity'])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(train.drop(['Severity'], axis=1),
train['Severity'], test_size=0.15,random_state=101)
print(X_train.shape)
print(X_test.shape)

# =========Decision Tree============

from sklearn.tree import DecisionTreeClassifier


dtc = DecisionTreeClassifier(criterion='entropy',
max_depth=10,
random_state=101)
dtc.fit(X_train, y_train)
dtc.score(X_train, y_train) * 100
dtc.score(X_test, y_test) * 100
from sklearn.metrics import classification_report, confusion_matrix

71
Decisiontree = classification_report(y_test, dtc.predict(X_test))
Decisiontreeclassifier = confusion_matrix(y_test, dtc.predict(X_test))

# ======== Random Forest ================

from sklearn.ensemble import RandomForestClassifier


rfc = RandomForestClassifier(criterion='entropy',
n_estimators=100,
max_depth=10,
random_state=101)
rfc.fit(X_train,y_train)
rfc.score(X_train, y_train) * 100
rfc.score(X_test, y_test) * 100
randomforest = classification_report(y_test, rfc.predict(X_test))
randomforestclassifier = confusion_matrix(y_test, rfc.predict(X_test))

# =========GradientBoosting===================

from sklearn.ensemble import GradientBoostingClassifier


gbc = GradientBoostingClassifier(n_estimators=100,
max_depth=10,
learning_rate=0.2,
random_state=101)
gbc.fit(X_train, y_train)
gbc.score(X_train, y_train) * 100
gbc.score(X_test, y_test) * 100
GradianBoosting = classification_report(y_test, gbc.predict(X_test)),
confusion_matrix(y_test, gbc.predict(X_test))

# =========xg boost===============

from numpy import loadtxt


from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
xgb = XGBClassifier()
xgb.fit(X_train, y_train)
y_pred = xgb.predict(X_test)

72
predictions = [round(value) for value in y_pred]
accuracy = accuracy_score(y_test, predictions)
XGB = accuracy * 100.0

from sklearn.preprocessing import LabelEncoder


en = LabelEncoder()
train['Severity']= en.fit_transform(train['Severity'])
train1 = train.drop(['Safety_Score'], axis=1)
train1.head()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(train1.drop(['Severity'], axis=1),
train1['Severity'], test_size=0.15,random_state=101)
print(X_train.shape)
print(X_test.shape)

return render(request,'users/ml.html',
{'Decisiontree':Decisiontree,'Decisiontreeclassifier':Decisiontreeclassifier,'randomforest'
:randomforest,

'randomforestclassifier':randomforestclassifier,'GradianBoosting':GradianBoosting})

def predictTrustWorthy(request):
if request.method == 'POST':
# Extracting data from the POST request
Accident_ID = request.POST.get("Accident_ID")
Safety_Score = request.POST.get("Safety_Score")
Days_Since_Inspection = request.POST.get("Days_Since_Inspection")
Total_Safety_Complaints = request.POST.get("Total_Safety_Complaints")
Control_Metric = request.POST.get("Control_Metric")
Turbulence_In_gforces = request.POST.get("Turbulence_In_gforces")
Cabin_Temperature = request.POST.get("Cabin_Temperature")
Accident_Type_Code = request.POST.get("Accident_Type_Code")
Max_Elevation = request.POST.get("Max_Elevation")
Violations = request.POST.get("Violations")
Adverse_Weather_Metric = request.POST.get("Adverse_Weather_Metric")

# Loading the dataset

73
path = settings.MEDIA_ROOT + '/' + 'airplane_accident_severity.csv'
df = pd.read_csv(path)
data = df.dropna()

# Check and remove unexpected values in 'passed' column


data['Severity'] = data['Severity'].apply(lambda x: 1 if x == 'yes' else 0)

# Selecting relevant columns for training


features = ['Accident_ID', 'Safety_Score', 'Days_Since_Inspection',
'Total_Safety_Complaints',
'Control_Metric', 'Turbulence_In_gforces', 'Cabin_Temperature',
'Accident_Type_Code',
'Max_Elevation', 'Violations','Adverse_Weather_Metric']

X = pd.get_dummies(data[features])

# Creating the test set


test_set = {'Accident_ID': Accident_ID, 'Safety_Score': Safety_Score,
'Days_Since_Inspection': Days_Since_Inspection, 'Total_Safety_Complaints':
Total_Safety_Complaints,
'Control_Metric': Control_Metric, 'Turbulence_In_gforces':
T u r b u l e n c e _ I n _ g f o r c e s , ' C a b i n _ Te m p e r a t u r e ' : C a b i n _ Te m p e r a t u r e ,
'Accident_Type_Code': Accident_Type_Code,
'Max_Elevation': Max_Elevation, 'Violations': Violations,
'Adverse_Weather_Metric': Adverse_Weather_Metric}

# Creating a DataFrame for the test set


test_df = pd.DataFrame([test_set])

# One-hot encoding the test set


test_df = pd.get_dummies(test_df)

# Matching the columns between the training and test sets


missing_cols = set(X.columns) - set(test_df.columns)
for col in missing_cols:
test_df[col] = 0

74
# Reordering the columns to match the training set
test_df = test_df[X.columns]

# Preparing the data for training


y = data['Severity']
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2,
random_state=101)

# Initializing and training the model


OBJ = RandomForestClassifier(n_estimators=10, criterion='entropy')
OBJ.fit(X_train, Y_train)

# Making predictions
print(test_df.values)
y_pred = OBJ.predict(test_df.values)
print(y_pred)

# Converting the prediction to 'yes' or 'no'


if y_pred[0] == 1:
msg = 'Significant_Damage_And_Fatalities'
elif y_pred[0] == 2:
msg = 'Significant_Damage_And_Serious_Injuries'
elif y_pred[0] == 3:
msg = 'Minor_Damage_And_Injuries'
else:
msg = 'No_Significant_Damage'

return render(request, "users/predictForm.html", {"msg": msg})


else:
return render(request, 'users/predictForm.html', {})

75

You might also like