The Wayback Machine - https://web.archive.org/web/20241004223500/https://www.geeksforgeeks.org/online-payment-fraud-detection-using-machine-learning-in-python/
Open In App

Online Payment Fraud Detection using Machine Learning in Python

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

As we are approaching modernity, the trend of paying online is increasing tremendously. It is very beneficial for the buyer to pay online as it saves time, and solves the problem of free money. Also, we do not need to carry cash with us. But we all know that Good thing are accompanied by bad things. 

The online payment method leads to fraud that can happen using any payment app. That is why Online Payment Fraud Detection is very important.

Online Payment Fraud Detection using Machine Learning in Python

Here we will try to solve this issue with the help of machine learning in Python.

The dataset we will be using have these columns – 

Feature Description
step tells about the unit of time
type type of transaction done
amount the total amount of transaction
nameOrg account that starts the transaction 
oldbalanceOrg Balance of the account of sender before transaction
newbalanceOrg Balance of the account of sender after transaction
nameDest account that receives the transaction
oldbalanceDest Balance of the account of receiver before transaction
newbalanceDest Balance of the account of receiver after transaction
isFraud The value to be predicted i.e. 0 or 1

Importing Libraries and Datasets

The libraries used are : 

  • Pandas:  This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Seaborn/Matplotlib: For data visualization.
  • Numpy: Numpy arrays are very fast and can perform large computations in a very short time.

Python3




import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline


The dataset includes the features like type of payment, Old balance , amount paid, name of the destination, etc.

Python3




data = pd.read_csv('new_data.csv')
data.head()


Output : 

Online Payment Fraud Detection using Machine Learning

 

To print the information of the data we can use data.info() command.

Python3




data.info()


Output : 

Online Payment Fraud Detection using Machine Learning - information

 

Let’s see the mean, count , minimum and maximum values of the data.

Python3




data.describe()


Output : 

Online Payment Fraud Detection using Machine Learning - Describe

 

Data Visualization

In this section, we will try to understand and compare all columns. 

Let’s count the columns with different datatypes like Category, Integer, Float. 

Python3




obj = (data.dtypes == 'object')
object_cols = list(obj[obj].index)
print("Categorical variables:", len(object_cols))
 
int_ = (data.dtypes == 'int')
num_cols = list(int_[int_].index)
print("Integer variables:", len(num_cols))
 
fl = (data.dtypes == 'float')
fl_cols = list(fl[fl].index)
print("Float variables:", len(fl_cols))


Output : 

Categorical variables: 3
Integer variables: 2
Float variables: 5

Let’s see the count plot of the Payment type column using Seaborn library.

Python3




sns.countplot(x='type', data=data)


Output : 

Online Payment Fraud Detection using Machine Learning - Count

 

We can also use the bar plot for analyzing Type and amount column simultaneously.

Python3




sns.barplot(x='type', y='amount', data=data)


Output : 

Online Payment Fraud Detection using Machine Learning - Barplot

 

Both the graph clearly shows that mostly the type cash_out and transfer are maximum in count and as well as in amount. 

Let’s check the distribution of data among both the prediction values.

Python3




data['isFraud'].value_counts()


Output : 

0    8000
1    8000

The dataset is already in same count. So there is no need of sampling.

Now let’s see the distribution of the step column using distplot.

Python3




plt.figure(figsize=(15, 6))
sns.distplot(data['step'], bins=50)


Output : 

Online Payment Fraud Detection using Machine Learning - Distplot

 

The graph shows the maximum distribution among 200 to 400 of step.

Now, Let’s find the correlation among different features using Heatmap.

Python3




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


Output :

Online Payment Fraud Detection using Machine Learning - Heatmap

 

Data Preprocessing

This step includes the following : 

  • Encoding of Type column
  • Dropping irrelevant columns like nameOrig, nameDest
  • Data Splitting

Python3




type_new = pd.get_dummies(data['type'], drop_first=True)
data_new = pd.concat([data, type_new], axis=1)
data_new.head()


Output:

Online Payment Fraud Detection using Machine Learning - Modified Data

 

Once we done with the encoding, now we can drop the irrelevant columns. For that, follow the code given below.

Python3




X = data_new.drop(['isFraud', 'type', 'nameOrig', 'nameDest'], axis=1)
y = data_new['isFraud']


Let’s check the shape of extracted data.

Python3




X.shape, y.shape


Output:

((16000, 10), (16000,))

Now let’s split the data into 2 parts : Training and Testing.

Python3




from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42)


Model Training

As the prediction is a classification problem so the models we will be using are :

  • LogisticRegression :  It predicts that the probability of a given data belongs to the particular category or not.
  • XGBClassifier : It refers to Gradient Boosted decision trees. In this algorithm, decision trees are created in sequential form and weights are assigned to all the independent variables which are then fed into the decision tree which predicts results.
  • SVC : SVC is used to find a hyperplane in an N-dimensional space that distinctly classifies the data points. Then it gives the output according the most nearby element.
  • RandomForestClassifier : Random forest classifier creates a set of decision trees from a randomly selected subset of the training set. Then, it collects the votes from different decision trees to decide the final prediction.

Let’s import the modules of the relevant models. 

Python3




from xgboost import XGBClassifier
from sklearn.metrics import roc_auc_score as ras
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier


Once done with the importing, Let’s train the model.

Python3




models = [LogisticRegression(), XGBClassifier(),
          SVC(kernel='rbf', probability=True),
          RandomForestClassifier(n_estimators=7,
                                 criterion='entropy',
                                 random_state=7)]
 
for i in range(len(models)):
    models[i].fit(X_train, y_train)
    print(f'{models[i]} : ')
     
    train_preds = models[i].predict_proba(X_train)[:, 1]
    print('Training Accuracy : ', ras(y_train, train_preds))
     
    y_preds = models[i].predict_proba(X_test)[:, 1]
    print('Validation Accuracy : ', ras(y_test, y_preds))
    print()


Output:

Online Payment Fraud Detection using Machine Learning - Model Accuracy

 

Model Evaluation

The best-performed model is XGBClassifier. Let’s plot the Confusion Matrix for the same.

Python3




from sklearn.metrics import plot_confusion_matrix
 
plot_confusion_matrix(models[1], X_test, y_test)
plt.show()


Output:

Confusion matrix of XGBClassifier

 



Previous Article
Next Article

Similar Reads

Automating the Machine Learning Pipeline for Credit card fraud detection
Before going to the code it is requested to work on a Jupyter notebook or ipython notebook. If not installed on your machine you can use Google Colab.This is one of the best and my personal favorite way of working on a python script to work on a Machine Learning problem. Previous article: Credit Card Fraud Detection using Python Now, I am consideri
4 min read
Financial Fraud Detection in R
In today's digital age, credit card fraud is a big problem that takes away from the convenience of using cashless payments. Luckily, there are some cool ways that machine learning can help detect and prevent fraud. These innovative methods allow banks and other financial institutions to spot suspicious activities in real time and protect people's h
13 min read
Credit Card Fraud Detection in R
Credit card fraud is a major issue that affects both consumers and financial institutions. With the rise of online transactions, detecting fraudulent activities has become increasingly challenging. Here, we will explore the process of detecting credit card fraud using machine learning techniques. We will use a real-world dataset to understand the d
9 min read
ML | Credit Card Fraud Detection
The challenge is to recognize fraudulent credit card transactions so that the customers of credit card companies are not charged for items that they did not purchase. Main challenges involved in credit card fraud detection are: Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time.Imbalanced Dat
6 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
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Alzheimer's detection Using Machine Learning
Alzheimer's disease is a neurodegenerative disorder characterized by progressive cognitive decline and memory loss. Detecting Alzheimer's disease early is crucial for timely intervention and treatment. While I can provide some general information on Alzheimer's detection, it's important to consult medical professionals for accurate diagnosis and ad
5 min read
How to create a Face Detection Android App using Machine Learning KIT on Firebase
Pre-requisites: Firebase Machine Learning kitAdding Firebase to Android AppFirebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let's use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that c
9 min read
Intrusion Detection System Using Machine Learning Algorithms
Problem Statement: The task is to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good normal connections. Introduction: Intrusion Detection System is a software application to detect network intrusion using various machine learning algorithms.IDS monitors a
11 min read
Fake News Detection using Machine Learning
Fake news on different platforms is spreading widely and is a matter of serious concern, as it causes social wars and permanent breakage of the bonds established among people. A lot of research is already going on focused on the classification of fake news. Here we will try to solve this issue with the help of machine learning in Python. Before sta
4 min read
Machine Learning for Anomaly Detection
Anomaly Detection is the technique of identifying rare events or observations which can raise suspicions by being statistically different from the rest of the observations. Such "anomalous" behaviour typically translates to some kind of a problem like a credit card fraud, failing machine in a server, a cyber attack, etc.An anomaly can be broadly ca
4 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 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
Object Detection with Detection Transformer (DETR) by Facebook
Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection mod
7 min read
Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read
Sobel Edge Detection vs. Canny Edge Detection in Computer Vision
Both Sobel and Canny algorithms are popular methods for edge detection in images, but they are suited for different purposes based on their characteristics and the nature of the application. Understanding when to use each can help you achieve better results for specific tasks in image processing. In this article, we are going to explore the differe
9 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Top 5 Open-Source Online Machine Learning Environments
Machine Learning is an area of research that allows machines the ability to learn without being directly programmed. Machine Learning development is in trend as many students, teachers, developers, and data scientists use machine learning to develop various projects and products. However, developing machine learning models require high system requi
3 min read
How is Machine Learning Changing Online Advertising?
Answer: Machine learning (ML) is revolutionizing online advertising by enabling more precise targeting, personalized ad experiences, and improved campaign performance. By analyzing vast amounts of data, ML algorithms can identify patterns and predict user behavior, resulting in more effective and efficient advertising strategies.Let's have a closer
3 min read
10 Best Online Courses For Machine Learning in 2024 [Updated List]
Looking to dive into the exciting world of Machine Learning? You're in the right place! Machine Learning is one of the hottest fields in computer science, with companies across industries embracing its potential. Whether you're a working professional looking to upskill or someone eager to explore new horizons, online courses offer a flexible and af
10 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Practice Tags :