The Wayback Machine - https://web.archive.org/web/20241004223639/https://www.geeksforgeeks.org/loan-approval-prediction-using-machine-learning/
Open In App

Loan Approval Prediction using Machine Learning

Last Updated : 23 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

LOANS are the major requirement of the modern world. By this only, Banks get a major part of the total profit. It is beneficial for students to manage their education and living expenses, and for people to buy any kind of luxury like houses, cars, etc.

But when it comes to deciding whether the applicant’s profile is relevant to be granted with loan or not. Banks have to look after many aspects.

So, here we will be using Machine Learning with Python to ease their work and predict whether the candidate’s profile is relevant or not using key features like Marital Status, Education, Applicant Income, Credit History, etc.

Loan Approval Prediction using Machine Learning

You can download the used data by visiting this link.

The dataset contains 13 features : 

1 Loan A unique id 
2 Gender Gender of the applicant Male/female
3 Married Marital Status of the applicant, values will be Yes/ No
4 Dependents It tells whether the applicant has any dependents or not.
5 Education It will tell us whether the applicant is Graduated or not.
6 Self_Employed This defines that the applicant is self-employed i.e. Yes/ No
7 ApplicantIncome Applicant income
8 CoapplicantIncome Co-applicant income
9 LoanAmount Loan amount (in thousands)
10 Loan_Amount_Term Terms of loan (in months)
11 Credit_History Credit history of individual’s repayment of their debts
12 Property_Area Area of property i.e. Rural/Urban/Semi-urban 
13 Loan_Status Status of Loan Approved or not i.e. Y- Yes, N-No 

Importing Libraries and Dataset

Firstly we have to import libraries : 

  • Pandas – To load the Dataframe
  • Matplotlib – To visualize the data features i.e. barplot
  • Seaborn – To see the correlation between features using heatmap

Python3




import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
  
data = pd.read_csv("LoanApprovalPrediction.csv")


Once we imported the dataset, let’s view it using the below command.

Python3




data.head(5)


Output:

 

Data Preprocessing and Visualization

Get the number of columns of object datatype.

Python3




obj = (data.dtypes == 'object')
print("Categorical variables:",len(list(obj[obj].index)))


Output :

Categorical variables: 7 

As Loan_ID is completely unique and not correlated with any of the other column, So we will drop it using .drop() function.

Python3




# Dropping Loan_ID column
data.drop(['Loan_ID'],axis=1,inplace=True)


Visualize all the unique values in columns using barplot. This will simply show which value is dominating as per our dataset.

Python3




obj = (data.dtypes == 'object')
object_cols = list(obj[obj].index)
plt.figure(figsize=(18,36))
index = 1
  
for col in object_cols:
  y = data[col].value_counts()
  plt.subplot(11,4,index)
  plt.xticks(rotation=90)
  sns.barplot(x=list(y.index), y=y)
  index +=1


Output:

 

As all the categorical values are binary so we can use Label Encoder for all such columns and the values will change into int datatype.

Python3




# Import label encoder
from sklearn import preprocessing
    
# label_encoder object knows how 
# to understand word labels.
label_encoder = preprocessing.LabelEncoder()
obj = (data.dtypes == 'object')
for col in list(obj[obj].index):
  data[col] = label_encoder.fit_transform(data[col])


Again check the object datatype columns. Let’s find out if there is still any left.

Python3




# To find the number of columns with 
# datatype==object
obj = (data.dtypes == 'object')
print("Categorical variables:",len(list(obj[obj].index)))


Output : 

Categorical variables: 0

Python3




plt.figure(figsize=(12,6))
  
sns.heatmap(data.corr(),cmap='BrBG',fmt='.2f',
            linewidths=2,annot=True)


Output:

 

The above heatmap is showing the correlation between Loan Amount and ApplicantIncome. It also shows that Credit_History has a high impact on Loan_Status.

Now we will use Catplot to visualize the plot for the Gender, and Marital Status of the applicant.

Python3




sns.catplot(x="Gender", y="Married",
            hue="Loan_Status", 
            kind="bar", 
            data=data)


Output:

 

Now we will find out if there is any missing values in the dataset using below code.

Python3




for col in data.columns:
  data[col] = data[col].fillna(data[col].mean()) 
    
data.isna().sum()


Output:

Gender               0
Married              0
Dependents           0
Education            0
Self_Employed        0
ApplicantIncome      0
CoapplicantIncome    0
LoanAmount           0
Loan_Amount_Term     0
Credit_History       0
Property_Area        0
Loan_Status          0

As there is no missing value then we must proceed to model training.

Splitting Dataset 

Python3




from sklearn.model_selection import train_test_split
  
X = data.drop(['Loan_Status'],axis=1)
Y = data['Loan_Status']
X.shape,Y.shape
  
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
                                                    test_size=0.4,
                                                    random_state=1)
X_train.shape, X_test.shape, Y_train.shape, Y_test.shape


Output:

((598, 11), (598,))
((358, 11), (240, 11), (358,), (240,))

Model Training and Evaluation

As this is a classification problem so we will be using these models : 

To predict the accuracy we will use the accuracy score function from scikit-learn library.

Python3




from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
  
from sklearn import metrics
  
knn = KNeighborsClassifier(n_neighbors=3)
rfc = RandomForestClassifier(n_estimators = 7,
                             criterion = 'entropy',
                             random_state =7)
svc = SVC()
lc = LogisticRegression()
  
# making predictions on the training set
for clf in (rfc, knn, svc,lc):
    clf.fit(X_train, Y_train)
    Y_pred = clf.predict(X_train)
    print("Accuracy score of ",
          clf.__class__.__name__,
          "=",100*metrics.accuracy_score(Y_train, 
                                         Y_pred))


Output  :

Accuracy score of  RandomForestClassifier = 98.04469273743017

Accuracy score of  KNeighborsClassifier = 78.49162011173185

Accuracy score of  SVC = 68.71508379888269

Accuracy score of  LogisticRegression = 80.44692737430168

Prediction on the test set:

Python3




# making predictions on the testing set
for clf in (rfc, knn, svc,lc):
    clf.fit(X_train, Y_train)
    Y_pred = clf.predict(X_test)
    print("Accuracy score of ",
          clf.__class__.__name__,"=",
          100*metrics.accuracy_score(Y_test,
                                     Y_pred))


Output : 

Accuracy score of  RandomForestClassifier = 82.5

Accuracy score of  KNeighborsClassifier = 63.74999999999999

Accuracy score of  SVC = 69.16666666666667

Accuracy score of  LogisticRegression = 80.83333333333333

Conclusion : 

Random Forest Classifier is giving the best accuracy with an accuracy score of 82% for the testing dataset. And to get much better results ensemble learning techniques like Bagging and Boosting can also be used.



Previous Article
Next Article

Similar Reads

Loan Eligibility prediction using Machine Learning Models in Python
Have you ever thought about the apps that can predict whether you will get your loan approved or not? In this article, we are going to develop one such model that can predict whether a person will get his/her loan approved or not by using some of the background information of the applicant like the applicant's gender, marital status, income, etc. I
5 min read
Parkinson Disease Prediction using Machine Learning - Python
Parkinson's disease is a progressive disorder that affects the nervous system and the parts of the body controlled by the nerves. Symptoms are also not that sound to be noticeable. Signs of stiffening, tremors, and slowing of movements may be signs of Parkinson's disease. But there is no ascertain way to tell whether a person has Parkinson's diseas
6 min read
Adenovirus Disease Prediction for Child Healthcare Using Machine Learning
The major uniqueness of this proposed work is recognizing the Adenovirus disease from the human body with the help of data so that people can be health conscious and take precautions to prevent the Adenovirus infection. Using data and Machine Learning methods, we will create a model to detect Adenovirus disease in the human body. Our goal is to rai
8 min read
Flight Fare Prediction Using Machine Learning
In this article, we will develop a predictive machine learning model that can effectively predict flight fares. Why do we need to predict flight fares?There are several use cases of flight fare prediction, which are discussed below: Trip planning apps: Several Travel planning apps use airfare calculators to help users find the best time to book fli
5 min read
Click-Through Rate Prediction using Machine Learning
Predicting the click-through Rate (CTR) is crucial for optimizing online advertising campaigns. By accurately estimating the likelihood of a user clicking on an ad, businesses can make informed decisions about ad placement and design, ultimately maximizing their return on investment (ROI). In this article, we will explore how to use the eXtreme Gra
5 min read
Netflix Stock Price Prediction & Forecasting using Machine Learning in R
Recently, many people have been paying attention to the stock market as it offers high risks and high returns. In simple words, "Stock" is the ownership of a small part of a company. The more stock you have the bigger the ownership is. Using machine learning algorithms to predict a company's stock price aims to forecast the future value of the comp
9 min read
Autism Prediction using Machine Learning
Autism is a neurological disorder that affects a person's ability to interact with others, make eye contact with others, learn capacity, and other behavioral and social capabilities of a person. But there is no ascertain way to tell whether a person has Autism or not because there are no such diagnostics methods available to diagnose this disorder.
10 min read
Disease Prediction Using Machine Learning
This article aims to implement a robust machine-learning model that can efficiently predict the disease of a human, based on the symptoms that he/she possesses. Let us look into how we can approach this machine-learning problem: Approach: Gathering the Data: Data preparation is the primary step for any machine learning problem. We will be using a d
10 min read
Medical Insurance Price Prediction using Machine Learning - Python
You must have heard some advertisements regarding medical insurance that promises to help financially in case of any medical emergency. One who purchases this type of insurance has to pay premiums monthly and this premium amount varies vastly depending upon various factors.  Medical Insurance Price Prediction using Machine Learning in PythonIn this
7 min read
Waiter's Tip Prediction using Machine Learning
If you have recently visited a restaurant for a family dinner or lunch and you have tipped the waiter for his generous behavior then this project might excite you. As in this article, we will try to predict what amount of tip a person will give based on his/her visit to the restaurant using some features related to the same. Let's start by importin
7 min read
House Price Prediction using Machine Learning in Python
We all have experienced a time when we have to look up for a new house to buy. But then the journey begins with a lot of frauds, negotiating deals, researching the local areas and so on. House Price Prediction using Machine LearningSo to deal with this kind of issues Today we will be preparing a MACHINE LEARNING Based model, trained on the House Pr
6 min read
Rainfall Prediction using Machine Learning - Python
Today there are no certain methods by using which we can predict whether there will be rainfall today or not. Even the meteorological department's prediction fails sometimes. In this article, we will learn how to build a machine-learning model which can predict whether there will be rainfall today or not based on some atmospheric factors. This prob
7 min read
Titanic Survival Prediction Using Machine Learning
In this article, we will learn to predict the survival chances of the Titanic passengers using the given information about their sex, age, etc. As this is a classification task we will be using random forest. There will be three main steps in this experiment: Feature EngineeringImputationTraining and PredictionDatasetThe dataset for this experiment
7 min read
Stock Price Prediction using Machine Learning in Python
Machine learning proves immensely helpful in many industries in automating tasks that earlier required human labor one such application of ML is predicting whether a particular trade will be profitable or not. In this article, we will learn how to predict a signal that indicates whether buying a particular stock will be helpful or not by using ML.
8 min read
Gold Price Prediction using Machine Learning
In This article, We will be making a project from scratch about Gold price prediction. To build any data science project We have to follow certain steps that need not be in the same order. In our project, We will go through these steps sequentially. Problem Formulation Data preprocessing Data wranglingModel DevelopmentModel ExplainabilityModel Depl
15+ min read
Bitcoin Price Prediction using Machine Learning in Python
Machine learning proves immensely helpful in many industries in automating tasks that earlier required human labor one such application of ML is predicting whether a particular trade will be profitable or not. In this article, we will learn how to predict a signal that indicates whether buying a particular stock will be helpful or not by using ML.
7 min read
Calories Burnt Prediction using Machine Learning
In this article, we will learn how to develop a machine learning model using Python which can predict the number of calories a person has burnt during a workout based on some biological measures. Importing Libraries and DatasetPython libraries make it easy for us to handle the data and perform typical and complex tasks with a single line of code. P
5 min read
Microsoft Stock Price Prediction with Machine Learning
In this article, we will implement Microsoft Stock Price Prediction with a Machine Learning technique. We will use TensorFlow, an Open-Source Python Machine Learning Framework developed by Google. TensorFlow makes it easy to implement Time Series forecasting data. Since Stock Price Prediction is one of the Time Series Forecasting problems, we will
5 min read
Django - Machine Learning Placement Prediction Project
In this article, we will create  Placement Prediction Project using the Django framework using Python. In this project, we are using logistic regression algorithm of Python machine learning to predict the Placement of students by observing the input values filled by students according to their study background. Placement Prediction Project in Djang
7 min read
Machine Learning Diabetes Prediction Project in Django
In this article, we will create Diabetes Prediction Project using the Django framework using Python. In this project, we are using a logistic regression algorithm of Python machine learning to predict Diabetes diseases in a person by observing the input values filled by the person according to their health. Diabetes Prediction Project in Django Bas
8 min read
Machine Learning Heart Disease Prediction Project in Django
Introduction-In this article, we will implement a Machine Learning Heart disease Prediction Project using the Django framework using Python. Here, we will convert the code of the heart diseases prediction into a web form with the help of the Django framework basically we will create a form by using the Django framework and add the dataset of heart
9 min read
Prediction Intervals for Machine Learning
Prediction intervals are an essential concept in machine learning and statistics, providing a range within which a future observation is expected to fall with a certain probability. Unlike confidence intervals, which estimate the uncertainty of a population parameter, prediction intervals focus on the uncertainty of individual predictions. This art
9 min read
Wine Quality Prediction - Machine Learning
Here we will predict the quality of wine on the basis of given features. We use the wine quality dataset available on Internet for free. This dataset has the fundamental features which are responsible for affecting the quality of the wine. By the use of several Machine learning models, we will predict the quality of the wine. Importing libraries an
5 min read
Dogecoin Price Prediction with Machine Learning
Dogecoin is a cryptocurrency, like Ethereum or Bitcoin — despite the fact that it's totally different than both of these famous coins. Dogecoin was initially made to some extent as a joke for crypto devotees and took its name from a previously well-known meme. In this article, we will be implementing a machine learning model which can predict the p
4 min read
Getting started with Machine Learning || Machine Learning Roadmap
Machine Learning (ML) represents a branch of artificial intelligence (AI) focused on enabling systems to learn from data, uncover patterns, and autonomously make decisions. In today's era dominated by data, ML is transforming industries ranging from healthcare to finance, offering robust tools for predictive analytics, automation, and informed deci
11 min read
Heart Disease Prediction using Support Vector Machine
Heart disease is a significant health concern worldwide, and early detection plays a crucial role in effective treatment and prevention. Machine learning algorithms, such as Support Vector Machines (SVM), have shown promising results in predicting heart disease based on patient data. SVM stands for Support Vector Machine are a set of supervised lea
4 min read
IPL Score Prediction using Deep Learning
In the modern era of cricket analytics, where each run and decision can change the outcome, the application of Deep Learning for IPL score prediction stands at the forefront of innovation. This article explores the cutting-edge use of advanced algorithms to forecast IPL score in live matches with unprecedented accuracy. Exploring the analysis of hi
9 min read
Flight Delay Prediction using Deep Learning
Air travel has become an important part of our lives, and with this comes the problem of flights being delayed. Deep learning models can automatically learn hierarchical representations from data, making them best for flight delay prediction. In the article, we will build a flight delay predictor using TensorFlow framework. How can we use deep lear
5 min read
Prediction of Wine type using Deep Learning
We use deep learning for the large data sets but to understand the concept of deep learning, we use the small data set of wine quality. You can find the wine quality data set from the UCI Machine Learning Repository which is available for free. The aim of this article is to get started with the libraries of deep learning such as Keras, etc and to b
4 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read