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

ML | Credit Card Fraud Detection

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Fraudulent credit card transactions are a significant challenge for financial institutions and consumers alike. Detecting these fraudulent activities in real-time is important to prevent financial losses and protect customers from unauthorized charges.

In this article we will explore how to build a machine learning model to detect fraudulent credit card transactions using Python.

Step 1: Importing all the necessary Libraries

We begin by importing the necessary Python libraries: numpy, pandas, matplotlib and seaborn for data handling, visualization and model building.

Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import gridspec

Step 2: Loading the Data

Load the dataset into a pandas DataFrame and examine its structure. The dataset contains 284,807 transactions with 31 features including:

  • Time: Seconds elapsed between each transaction and the first transaction in the dataset.
  • V1-V28: Anonymized features obtained via PCA.
  • Amount: Transaction amount.
  • Class: Target variable (0 for normal transactions, 1 for fraudulent transactions).
Python
data = pd.read_csv("credit.csv")
print(data.head())

Output:

Credit card data received

Now, let’s explore more about the dataset using df.describe() method.

Python
print(data.describe())

Output :

Screenshot-2025-03-21-160335

Step 3: Analyze Class Distribution

The next step is to check the distribution of fraudulent vs. normal transactions.

Python
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])))

Output:

Screenshot-2025-03-21-160615

Since the dataset is highly imbalanced (with only 0.02% fraudulent transactions), we’ll first try to build a model without balancing the dataset. If we don’t get satisfactory results, we will explore ways to handle the imbalance.

Step 4: Visualize Transaction Amounts

Let’s compare the transaction amounts for fraudulent and normal transactions. This will help us understand if there are any significant differences in the monetary value of fraudulent transactions.

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

Output :

Screenshot-2025-03-21-161041 Python
print(“details of valid transaction”)
valid.Amount.describe()

Output :

Screenshot-2025-03-21-161336

From the output, we observe that fraudulent transactions tend to have higher average amounts, which is critical in fraud detection.

Step 5: Correlation Matrix

We can visualize the correlation between features using a heatmap. This will give us an understanding of how the different features are correlated and which ones may be more relevant for prediction.

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

Output:

Most features do not correlate strongly with others, but some features (e.g., V2 and V5) have a negative correlation with the Amount feature. This provides valuable insights into how the features are related to the transaction amounts.

Step 6: Prepare the Data

Separate the input features (X) and target variable (Y), then split the data into training and testing sets

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

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)

Output :

(156612, 30)
(156612,)

Step 7: Build and Train the Model

Train a Random Forest Classifier to predict fraudulent transactions.

Python
from sklearn.ensemble import RandomForestClassifier

rfc = RandomForestClassifier()
rfc.fit(xTrain, yTrain)
# predictions
yPred = rfc.predict(xTest)

Step 8: Handling Missing Values

Before proceeding with model evaluation, it’s important to ensure that the dataset does not contain any missing or invalid values (e.g., NaN).

If your dataset contains missing values in the target variable (yTest), you can use the SimpleImputer from sklearn.impute to handle them.

Python
from sklearn.impute import SimpleImputer
print("NaN values in yTest before imputation:", np.isnan(yTest).sum())

imputer = SimpleImputer(strategy='most_frequent')  
yTest = imputer.fit_transform(yTest.reshape(-1, 1)).flatten()
print("NaN values in yTest after imputation:", np.isnan(yTest).sum())

Step 9: Evaluate the Model

After training the model, we need to evaluate its performance using various metrics, such as accuracy, precision, recall, F1-score, and the Matthews correlation coefficient.

Python
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef, confusion_matrix # Evaluation metrics
accuracy = accuracy_score(yTest, yPred)
precision = precision_score(yTest, yPred)
recall = recall_score(yTest, yPred)
f1 = f1_score(yTest, yPred)
mcc = matthews_corrcoef(yTest, yPred)

print("Model Evaluation Metrics:")
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-Score: {f1:.4f}")
print(f"Matthews Correlation Coefficient: {mcc:.4f}")

# Confusion matrix
conf_matrix = confusion_matrix(yTest, yPred)
plt.figure(figsize=(8, 6))
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues",
            xticklabels=['Normal', 'Fraud'], yticklabels=['Normal', 'Fraud'])
plt.title("Confusion Matrix")
plt.xlabel("Predicted Class")
plt.ylabel("True Class")
plt.show()

Output :

Model Evaluation Metrics:
Accuracy: 0.9996
Precision: 0.9138
Recall: 0.8833
F1-Score: 0.8983
Matthews Correlation Coefficient: 0.8982

The model accuracy is high due to class imbalance so, we will have computed precision, recall and f1 score to get a more meaningful understanding. We observe:

  • high frequency that means the model is good at not incorrectly marking legitimate transactions as fraud.
  • high recall means the model is good at identifying fraudulent transactions.
  • F1-score balances these two, indicating a strong performance.
  • MCC of 0.8982 confirms that the model’s predictions are well-aligned with the true outcomes, even in the case of imbalanced data.

Get complete notebook link here:

Notebook Link : click here.

Dataset Link : click here.



Next Article

Similar Reads