Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flask project for Loan approve prediction #10

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
368 changes: 368 additions & 0 deletions loan prediction/Test.csv

Large diffs are not rendered by default.

615 changes: 615 additions & 0 deletions loan prediction/Train.csv

Large diffs are not rendered by default.

79 changes: 79 additions & 0 deletions loan prediction/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from flask import Flask, request, jsonify, render_template
import pickle
import copy
import pandas as pd
from sklearn.preprocessing import LabelEncoder
l1= LabelEncoder()

app = Flask(__name__)
model = pickle.load(open('loan_model.pkl', 'rb'))

# read in csv file as a DataFrame
tr_df = pd.read_csv("https://raw.githubusercontent.com/Kirti-kn/AgroInOne/master/loan%20prediction/Train.csv")
tr_df.drop('Loan_ID',axis=1,inplace=True)

null_cols = ['Credit_History', 'Self_Employed', 'LoanAmount','Dependents', 'Loan_Amount_Term', 'Gender', 'Married']
for col in null_cols:
tr_df[col] = tr_df[col].fillna(tr_df[col].dropna().mode().values[0])

# categorial columns
cat = tr_df.select_dtypes('object').columns.to_list()

train_data= copy.deepcopy(tr_df)

l1=LabelEncoder()

for i in cat:
train_data[i]=l1.fit_transform(train_data[i])

oi_dict ={}

for i in cat:
for j,k in zip(tr_df[i],train_data[i]):
oi_dict[j]=k

credits_dict = {'No dues':1.0,'Dues left':0.0}


@app.route('/')
def index():
# Define your dictionary of dropdown values
Gen_dd = sorted(set(tr_df['Gender']))
married = sorted(set(tr_df['Married']))
dependents = sorted(set(tr_df['Dependents']))
education = sorted(set(tr_df['Education']))
self_emp = sorted(set(tr_df['Self_Employed']))
prop_area = sorted(set(tr_df['Property_Area']))
credit_hist =['No dues','Dues left']
return render_template('index.html', gd=Gen_dd,md=married,dd=dependents,ed=education,spd=self_emp,pd=prop_area,cd=credit_hist)

@app.route('/get_selected_value', methods=['POST'])
def get_selected_value():
# loan_id = request.form['selected_state']
gender = request.form['gender']
married = request.form['married']
dependent = request.form['dependent']
education = request.form['education']
self_emp = request.form['self_emp']
ap_income = int(request.form['ap_income'])
coap_income = float(request.form['coap_income'])
loan_amount = float(request.form['loan_amount'])
loan_term = float(request.form['loan_term'])
credit_history = request.form['credit_history']
prop_area = request.form['prop_area']

input= [[oi_dict[gender],oi_dict[married],oi_dict[dependent],oi_dict[education],oi_dict[self_emp],ap_income,coap_income,loan_amount,loan_term,credits_dict[credit_history],oi_dict[prop_area]]]
prediction = model.predict(input)
result = prediction[0]
if result==1:
txt = "Can be Approved"
else:
txt = "Cannot be Approved"
# Use the selected value for further processing
# For example, return it as a response, store it in a database, etc.
return render_template('index.html',pred_text= txt)


# Run the Flask application
if __name__ == '__main__':
app.run(debug=True)
Binary file added loan prediction/loan_model.pkl
Binary file not shown.
52 changes: 52 additions & 0 deletions loan prediction/loan_pmodel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import numpy as np # linear algebra
import pandas as pd # data processing
import copy
import pickle

#relevant ML libraries
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split

#ML model
from sklearn.linear_model import LogisticRegression

# read in csv file as a DataFrame
tr_df = pd.read_csv("https://raw.githubusercontent.com/Kirti-kn/AgroInOne/master/loan%20prediction/Train.csv")
# explore the first 5 rows
#tr_df.head()

# read in csv file as a DataFrame
te_df = pd.read_csv("https://raw.githubusercontent.com/Kirti-kn/AgroInOne/master/loan%20prediction/Test.csv")
# explore the first 5 rows
#te_df.head()

#the Id column is not needed, let's drop it for both test and train datasets
tr_df.drop('Loan_ID',axis=1,inplace=True)
te_df.drop('Loan_ID',axis=1,inplace=True)

# tr_df = pd.concat([tr_df, te_df], ignore_index=True)

#filling the missing data
null_cols = ['Credit_History', 'Self_Employed', 'LoanAmount','Dependents', 'Loan_Amount_Term', 'Gender', 'Married']
for col in null_cols:
tr_df[col] = tr_df[col].fillna(tr_df[col].dropna().mode().values[0])

# categorial columns
cat = tr_df.select_dtypes('object').columns.to_list()

train_data= copy.deepcopy(tr_df)
l1=LabelEncoder()

for i in cat:
train_data[i]=l1.fit_transform(train_data[i])

y = train_data['Loan_Status']
X = train_data.drop('Loan_Status', axis = 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)

LR = LogisticRegression()
LR.fit(X_train, y_train)

final_model = LR

pickle.dump(final_model,open('loan_model.pkl','wb'))
219 changes: 219 additions & 0 deletions loan prediction/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
body {
background-image: url('https://raw.githubusercontent.com/mohantyrohan3/AgroInOne/master/frontend/src/images/farmer.jpg');
background-size: cover;
background-position: top;
background-repeat: no-repeat;
background-color: rgb(138, 98, 61);
}

.wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}

content {
flex-grow: 1;
}

.form-container {
background-color: rgba(255, 255, 255, 0.7); /* White background with 70% opacity */
padding: 20px; /* Add padding to the form container */
width: 80% ;
height: auto ;
margin: auto; /* Center the form container horizontally */
position: absolute; /* Set position to absolute for centering horizontally */
top: 0; /* Set top position to 0 for aligning with the top of the window */
left: 50%; /* Set left position to 50% for centering horizontally */
transform: translateX(-50%);
}


.form-group {
margin-bottom: 10px; /* Add margin at the bottom of each form group */
}

label {
display: block; /* Display labels as block elements */
margin-bottom: 5px; /* Add margin at the bottom of each label */
}

select, textarea {
width: 100%; /* Set the width of select and textarea to 100% */
padding: 5px; /* Add padding to select and textarea */
}

input[type="submit"] {
background-color: #007bff; /* Set background color for submit button */
color: #fff; /* Set text color for submit button */
border: none; /* Remove border from submit button */
padding: 10px; /* Add padding to submit button */
cursor: pointer; /* Add cursor pointer to submit button */
margin-top: 10px; /* Add margin at the top of submit button */
}

input[type="submit"]:hover {
background-color: #0056b3; /* Set background color for submit button on hover */
}
</style>
<title>Loan Approval Prediction</title>
</head>
<body>

<div class="form-container">
<h2>Fill up the details (all details are compulsory to fill)</h2>
<form method="post" action="/get_selected_value">
<div class="form-group">
<label for="myTextarea">Enter Loan:</label>
<!-- Create a textarea element for accepting float values -->
<textarea class="form-control" id="myTextarea" name="loan_id" rows="1" placeholder="Loan ID (Ex: LP00xxxx)"></textarea>
</div>


<div class="form-group">
<label for="myDropdown">Gender:</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="gender">
<option value="" selected disabled hidden>
Select Gender
</option>
{% for value in gd %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myDropdown">Marital Status:</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="married">
<option value="" selected disabled hidden>
Select Marital Status
</option>
{% for value in md %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myDropdown">No of Dependents:</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="dependent">
<option value="" selected disabled hidden>
People dependent on your income
</option>
{% for value in dd %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myDropdown">EDucation Level:</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="education">
<option value="" selected disabled hidden>
Select education
</option>
{% for value in ed %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myDropdown">Are you self Employed?</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="self_emp">
<option value="" selected disabled hidden>
Self Employed status
</option>
{% for value in spd %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myTextarea">Enter your income:</label>
<!-- Create a textarea element for accepting float values -->
<textarea class="form-control" id="myTextarea" name="ap_income" rows="1" placeholder="Anual income"></textarea>
</div>

<div class="form-group">
<label for="myTextarea">Enter your partner/co-applicant income:</label>
<!-- Create a textarea element for accepting float values -->
<textarea class="form-control" id="myTextarea" name="coap_income" rows="1" placeholder="Anual income"></textarea>
</div>

<div class="form-group">
<label for="myTextarea">Enter Loan amount:</label>
<!-- Create a textarea element for accepting float values -->
<textarea class="form-control" id="myTextarea" name="loan_amount" rows="1" placeholder="Loan amount"></textarea>
</div>

<div class="form-group">
<label for="myTextarea">Enter term of lean in months:</label>
<!-- Create a textarea element for accepting float values -->
<textarea class="form-control" id="myTextarea" name="loan_term" rows="1" placeholder="Loan amount term"></textarea>
</div>

<div class="form-group">
<label for="myDropdown">Status of credit</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="credit_history">
<option value="" selected disabled hidden>
Any dues left or completed?
</option>
{% for value in cd %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<div class="form-group">
<label for="myDropdown">Type of area of property:</label>
<!-- Create a select element for the dropdown -->
<select class="form-control" id="myDropdown" name="prop_area">
<option value="" selected disabled hidden>
Property Area Type
</option>
{% for value in pd %}
<option value="{{ value }}">{{ value }}</option>
{% endfor %}
</select>
</div>

<input type="submit" value="Submit">
</form>

<br>
<p>
<h3>Loan Status : {{ pred_text }}</h3>
</p>
</div>

<!-- <div class="wrapper">
<div class="content">
</div>
<footer class="bg-dark text-white text-center py-3">
<p>© 2023 My Website. All rights reserved.</p>
</footer>
</div> -->

<!-- Include Bootstrap JavaScript -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>

</body>
</html>