The Wayback Machine - https://web.archive.org/web/20240930161128/https://www.geeksforgeeks.org/ml-credit-card-fraud-detection/
Open In App

ML | Credit Card Fraud Detection

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

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:

  1. Enormous Data is processed every day and the model build must be fast enough to respond to the scam in time.
  2. Imbalanced Data i.e most of the transactions (99.8%) are not fraudulent which makes it really hard for detecting the fraudulent ones
  3. Data availability as the data is mostly private.
  4. Misclassified Data can be another major issue, as not every fraudulent transaction is caught and reported.
  5. Adaptive techniques used against the model by the scammers.

How to tackle these challenges?

  1. The model used must be simple and fast enough to detect the anomaly and classify it as a fraudulent transaction as quickly as possible.
  2. Imbalance can be dealt with by properly using some methods which we will talk about in the next paragraph
  3. For protecting the privacy of the user the dimensionality of the data can be reduced.
  4. A more trustworthy source must be taken which double-check the data, at least for training the model.
  5. We can make the model simple and interpretable so that when the scammer adapts to it with just some tweaks we can have a new model up and running to deploy.

Before going to the code it is requested to work on a jupyter notebook. If not installed on your machine you can use Google colab. You can download the dataset from Kaggle.

Code : Importing all the necessary Libraries

Python
# import the necessary packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import gridspec

Code : Loading the Data

Python
# Load the dataset from the csv file using pandas
# best way is to mount the drive on colab and 
# copy the path for the csv file
data = pd.read_csv("credit.csv")

Code : Understanding the Data

Python
# Grab a peek at the data
data.head()

Credit card data received

Code : Describing the Data

Python
# Print the shape of the data
# data = data.sample(frac = 0.1, random_state = 48)
print(data.shape)
print(data.describe())

Output :

(284807, 31)
Time V1 ... Amount Class
count 284807.000000 2.848070e+05 ... 284807.000000 284807.000000
mean 94813.859575 3.919560e-15 ... 88.349619 0.001727
std 47488.145955 1.958696e+00 ... 250.120109 0.041527
min 0.000000 -5.640751e+01 ... 0.000000 0.000000
25% 54201.500000 -9.203734e-01 ... 5.600000 0.000000
50% 84692.000000 1.810880e-02 ... 22.000000 0.000000
75% 139320.500000 1.315642e+00 ... 77.165000 0.000000
max 172792.000000 2.454930e+00 ... 25691.160000 1.000000

[8 rows x 31 columns]

Code : Imbalance in the data

Time to explain the data we are dealing with.

Python
# Determine number of fraud cases in dataset
fraud = data[data['Class'] == 1]
valid = data[data['Class'] == 0]
outlierFraction = len(fraud)/float(len(valid))
print(outlierFraction)
print('Fraud Cases: {}'.format(len(data[data['Class'] == 1])))
print('Valid Transactions: {}'.format(len(data[data['Class'] == 0])))

Only 0.17% fraudulent transaction out all the transactions. The data is highly Unbalanced. Lets first apply our models without balancing it and if we don’t get a good accuracy then we can find a way to balance this dataset. But first, let’s implement the model without it and will balance the data only if needed.

Code : Print the amount details for Fraudulent Transaction

Python
print(“Amount details of the fraudulent transaction”)
fraud.Amount.describe()

Output :

Amount details of the fraudulent transaction
count 492.000000
mean 122.211321
std 256.683288
min 0.000000
25% 1.000000
50% 9.250000
75% 105.890000
max 2125.870000
Name: Amount, dtype: float64

Code : Print the amount details for Normal Transaction

Python
print(“details of valid transaction”)
valid.Amount.describe()

Output :

Amount details of valid transaction
count 284315.000000
mean 88.291022
std 250.105092
min 0.000000
25% 5.650000
50% 22.000000
75% 77.050000
max 25691.160000
Name: Amount, dtype: float64

As we can clearly notice from this, the average Money transaction for the fraudulent ones is more. This makes this problem crucial to deal with.

Code : Plotting the Correlation Matrix

The correlation matrix graphically gives us an idea of how features correlate with each other and can help us predict what are the features that are most relevant for the prediction.

Python
# Correlation matrix
corrmat = data.corr()
fig = plt.figure(figsize = (12, 9))
sns.heatmap(corrmat, vmax = .8, square = True)
plt.show()

Correlation Matrix

In the HeatMap we can clearly see that most of the features do not correlate to other features but there are some features that either has a positive or a negative correlation with each other. For example, V2 and V5 are highly negatively correlated with the feature called Amount. We also see some correlation with V20 and Amount. This gives us a deeper understanding of the Data available to us.

Code : Separating the X and the Y values

Dividing the data into inputs parameters and outputs value format

Python
# dividing the X and the Y from the dataset
X = data.drop(['Class'], axis = 1)
Y = data["Class"]
print(X.shape)
print(Y.shape)
# getting just the values for the sake of processing 
# (its a numpy array with no columns)
xData = X.values
yData = Y.values

Output :

 
(284807, 30)
(284807, )

Training and Testing Data Bifurcation

We will be dividing the dataset into two main groups. One for training the model and the other for Testing our trained model’s performance.

Python
# Using Scikit-learn to split data into training and testing sets
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
xTrain, xTest, yTrain, yTest = train_test_split(
        xData, yData, test_size = 0.2, random_state = 42)

Code : Building a Random Forest Model using scikit learn

Python
# Building the Random Forest Classifier (RANDOM FOREST)
from sklearn.ensemble import RandomForestClassifier
# random forest model creation
rfc = RandomForestClassifier()
rfc.fit(xTrain, yTrain)
# predictions
yPred = rfc.predict(xTest)

Code : Building all kinds of evaluating parameters

Python
# Evaluating the classifier
# printing every score of the classifier
# scoring in anything
from sklearn.metrics import classification_report, accuracy_score 
from sklearn.metrics import precision_score, recall_score
from sklearn.metrics import f1_score, matthews_corrcoef
from sklearn.metrics import confusion_matrix

n_outliers = len(fraud)
n_errors = (yPred != yTest).sum()
print("The model used is Random Forest classifier")

acc = accuracy_score(yTest, yPred)
print("The accuracy is {}".format(acc))

prec = precision_score(yTest, yPred)
print("The precision is {}".format(prec))

rec = recall_score(yTest, yPred)
print("The recall is {}".format(rec))

f1 = f1_score(yTest, yPred)
print("The F1-Score is {}".format(f1))

MCC = matthews_corrcoef(yTest, yPred)
print("The Matthews correlation coefficient is{}".format(MCC))

Output :

The model used is Random Forest classifier
The accuracy is 0.9995611109160493
The precision is 0.9866666666666667
The recall is 0.7551020408163265
The F1-Score is 0.8554913294797689
The Matthews correlation coefficient is0.8629589216367891

Code : Visualizing the Confusion Matrix

Python
# printing the confusion matrix
LABELS = ['Normal', 'Fraud']
conf_matrix = confusion_matrix(yTest, yPred)
plt.figure(figsize =(12, 12))
sns.heatmap(conf_matrix, xticklabels = LABELS, 
            yticklabels = LABELS, annot = True, fmt ="d");
plt.title("Confusion matrix")
plt.ylabel('True class')
plt.xlabel('Predicted class')
plt.show()

Output :

Random Forest Classifier Confusion Matrix


Comparison with other algorithms without dealing with the imbalancing of the data.

Comparison with the other Algorithm.

As you can see with our Random Forest Model we are getting a better result even for the recall which is the most tricky part.

Get complete notebook link here:

Notebook Link : click here.

Dataset Link : click here.



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
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
Online Payment Fraud Detection using Machine Learning in Python
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
5 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 Number Validator using ReactJS
Credit card validation is an important step in every application in order to authenticate the user's credit card number so that the application can proceed to the payment process if needed. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user entered credit card number and check whether it i
2 min read
JUnit - Testcases for Credit Card Validation as a Maven Project
In this article let us see a much-required functionality that is credit card validation as well as its relevant JUnit test cases for given credit card numbers. In an e-commerce project, credit card payment is the valid and much desired required functionality. We need to have a proper validation mechanism for that. So, by using the "Luhn algorithm",
6 min read
Credit Card Validator using Bootstrap & JavaScript
A credit card validator checks if a given number adheres to the format and algorithm of credit card numbers, typically ensuring it's the correct length, and passes mathematical validation such as the Luhn algorithm, helping to verify its authenticity. PrerequisitesHTMLBootstrapJavaScriptApproachThis HTML file contains a credit card validation form.
2 min read
Analyzing Credit Card Transactions using R
Analyzing credit card transactions is crucial for identifying fraudulent activities and protecting users from unauthorized transactions. Here, we'll explore the steps to analyze a credit card transaction dataset using R, focusing on data preprocessing, exploration, and building a simple predictive model. Overview of Credit Card Transactions using R
7 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
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
Credit Suisse Internship Interview Experience | On-Campus 2021
Registration Process: The interested students from Computer Science and Information Technology Branch were asked to submit their details for the Credit Suisse Technical Analyst Intern position (Summer 2022). After all the students submitted their details, the students who had secured more than 8.0 CGPA in their semesters were allowed to sit for the
4 min read
OpenCV C++ Program for coin detection
The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV. Things to know: The code will only compile in Linux environment. To run in windows, please use the file: 'coin.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious ch
4 min read
Project Idea (Augmented Reality - ARuco Code Detection and Estimation)
Project Idea : A project based on scanning and detecting Aruco codes. Implementing Homography for estimation of intrinsic and extrinsic camera calibration parameters and inclusion of Pose Estimation for the implementation of augmented Reality projects in further future projects. For Qr Code Detection Visit : this linkFor more Projects visit : Sahil
4 min read
Project Idea | Driver distraction and drowsiness detection system - DCube
Project Title: DCube Introduction:Car accident is the major cause of death in which around 1.3 million people die every year. Majority of these accidents are caused because of distraction or the drowsiness of driver. Construction of high-speed highway roads had diminished the margin of error for the driver. The countless number of people drives for
3 min read
Project Idea | Domain term detection and Hierarchical concept creation
Project Title: Domain term detection and Hierarchical concept creation Introduction: Domain Term Detection and Hierarchical Concept Creation in which given set of documents, main aims is to identify domain-specific term which mean that from given large set articles, tried to extract the domain for each article, and also created hierarchical represe
3 min read
Project Idea | Pavement distress detection using Drone Imaging
Project Title: Pavement Distress Detection Using Drone Imaging Introduction: Street pavement construction and repair includes a huge part of Indian metropolitan spending budgets. Survey and monitoring upkeep are crucial and important measures against pavement distress like both holes, blocked drains, etc. that can bring down the money related weigh
5 min read
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read
Car driving using hand detection in Python
In this project, we are going to demonstrate how one can drive a car by just detecting hand gestures on the steering wheel. Let's say the requirement is something like this - If driver wants to start the car then put both of your hands on the steering wheel. If someone having no hands on a steering wheel that means brakes of car will be applied slo
3 min read
Python | Smile detection using OpenCV
Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw
3 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
Python | Haar Cascades for Object Detection
Object Detection is a computer technology related to computer vision, image processing and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades. What are Haar Cascades? Haar Cascade classifiers are an effective way for object detection.
2 min read
OpenCV | Real Time Road Lane Detection
Autonomous Driving Car is one of the most disruptive innovations in AI. Fuelled by Deep Learning algorithms, they are continuously driving our society forward and creating new opportunities in the mobility sector. An autonomous car can go anywhere a traditional car can go and does everything that an experienced human driver does. But it's very esse
15+ min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read
Selective Search for Object Detection | R-CNN
The problem of object localization is the most difficult part of object detection. One approach is that we use sliding window of different size to locate objects in the image. This approach is called Exhaustive search. This approach is computationally very expensive as we need to search for object in thousands of windows even for small image size.
6 min read
YOLO : You Only Look Once - Real Time Object Detection
YOLO was proposed by Joseph Redmond et al. in 2015. It was proposed to deal with the problems faced by the object recognition models at that time, Fast R-CNN is one of the state-of-the-art models at that time but it has its own challenges such as this network cannot be used in real-time, because it takes 2-3 seconds to predicts an image and therefo
6 min read
YOLO v2 - Object Detection
In terms of speed, YOLO is one of the best models in object recognition, able to recognize objects and process frames at the rate up to 150 FPS for small networks. However, In terms of accuracy mAP, YOLO was not the state of the art model but has fairly good Mean average Precision (mAP) of 63% when trained on PASCAL VOC2007 and PASCAL VOC 2012. How
6 min read
Gun Detection using Python-OpenCV
Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations. Prerequisites: Python OpenCV OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Re
4 min read
Python - Eye blink detection project
In this tutorial you will learn about detecting a blink of human eye with the feature mappers knows as haar cascades. Here in the project, we will use the python language along with the OpenCV library for the algorithm execution and image processing respectively. The haar cascades we are going to use in the project are pretrained and stored along w
4 min read