<jupyter_start><jupyter_text>Credit Card Fraud Detection  Importing all necessary modules<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
import itertools

from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, precision_score, confusion_matrix, recall_score, f1_score, classification_report
df = pd.read_csv("creditcard.csv")
df.sample(10)<jupyter_output><empty_output><jupyter_text>EDA analysis<jupyter_code>#checking for null values
pd.set_option('max_rows', 100)
df.isnull().sum()
df.info()
df.describe().T
df["Amount"].describe().T
non_fraud = len(df[df.Class == 0])
fraud = len(df[df.Class == 1])
fraud_percent = (fraud / (fraud + non_fraud)) * 100

print("Number of Genuine transactions: ", non_fraud)
print("Number of Fraud transactions: ", fraud)
print("Percentage of Fraud transactions: {:.4f}".format(fraud_percent))
import seaborn as sns
labels = ["Genuine", "Fraud"]
sns.countplot(df['Class'], palette = 'pink')
plt.title("Visualization of Labels", fontsize = 20)
plt.ylabel("Count")
plt.xticks(range(2), labels)
plt.show()
scaler = MinMaxScaler()
df["NormalizedAmount"] = scaler.fit_transform(df["Amount"].values.reshape(-1, 1))
df.drop(["Amount", "Time"], inplace= True, axis= 1)

y = df["Class"]
X = df.drop(["Class"], axis= 1)
X.head()
y.head()
X_train,X_test,y_train,y_test = train_test_split(X, y, test_size= 0.3, random_state= 42)

print("Shape of train_X: ", X_train.shape)
print("Shape of test_X: ", X_test.shape)<jupyter_output>Shape of train_X:  (199364, 29)
Shape of test_X:  (85443, 29)<jupyter_text>Here 0 and 1 counts are varying, So we should perform minority sampling using SMOTE for better score<jupyter_code>y_train.value_counts()
y_test.value_counts()
from imblearn.over_sampling import SMOTE
smote  = SMOTE(sampling_strategy='minority')
X_sm,y_sm = smote.fit_resample(X,y)<jupyter_output><empty_output><jupyter_text>Now we can see, all the values are equal<jupyter_code>y_sm.value_counts()
X_train1,X_test1,y_train1,y_test1 = train_test_split(X_sm, y_sm, test_size= 0.3, stratify=y_sm ,random_state= 42)

print("1. Shape of train_X: ", X_train1.shape)
print("2. Shape of test_X: ", X_test1.shape)
print("3. Value counts of y_test\n", y_test1.value_counts())
print("4. Value counts of y_train\n",y_train1.value_counts())<jupyter_output>1. Shape of train_X:  (398041, 29)
2. Shape of test_X:  (170589, 29)
3. Value counts of y_test
 0    85295
1    85294
Name: Class, dtype: int64
4. Value counts of y_train
 1    199021
0    199020
Name: Class, dtype: int64<jupyter_text>Decision Tree Classifier<jupyter_code># Decision Tree Classifier
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train1, y_train1)

predictions_dt = decision_tree.predict(X_test1)
decision_tree_score = decision_tree.score(X_test1, y_test1) * 100
print(decision_tree_score)<jupyter_output>99.79775952728488<jupyter_text>Random Forest<jupyter_code># Random Forest
random_forest = RandomForestClassifier(n_estimators= 100)
random_forest.fit(X_train1, y_train1)

predictions_rf = random_forest.predict(X_test1)
random_forest_score = random_forest.score(X_test1, y_test1) * 100
print(random_forest_score)<jupyter_output>99.98475868901278<jupyter_text>Confusion Matrix for Decision Tree<jupyter_code>import seaborn as sns
import tensorflow as tf
cm = tf.math.confusion_matrix(labels=y_test1,predictions=predictions_dt.round())

plt.figure(figsize = (10,7))
sns.heatmap(cm, annot=True, fmt='d')
plt.xlabel('Predicted')
plt.ylabel('Truth')<jupyter_output><empty_output><jupyter_text>Confusion Matrix for Random Forest<jupyter_code>cm = tf.math.confusion_matrix(labels=y_test1,predictions=predictions_rf.round())

plt.figure(figsize = (10,7))
sns.heatmap(cm, annot=True, fmt='d')
plt.xlabel('Predicted')
plt.ylabel('Truth')
def metrics(actuals, predictions):
    print("Accuracy: {:.5f}".format(accuracy_score(actuals, predictions)))
    print("Precision: {:.5f}".format(precision_score(actuals, predictions)))
    print("Recall: {:.5f}".format(recall_score(actuals, predictions)))
    print("F1-score: {:.5f}".format(f1_score(actuals, predictions)))
print("Evaluation of Decision Tree Model")
print()
metrics(y_test1, predictions_dt.round())
print("Evaluation of Random Forest Model")
print()
metrics(y_test1, predictions_rf.round())
print(classification_report(y_test1,predictions_dt.round()))
print(classification_report(y_test1,predictions_rf.round()))<jupyter_output>precision    recall  f1-score   support

           0       1.00      1.00      1.00     85295
           1       1.00      1.00      1.00     85294

    accuracy                           1.00    170589
   macro avg       1.00      1.00      1.00    170589
weighted avg       1.00      1.00      1.00    170589
{'fraction_non_alphanumeric': 0.1234842360549717, 'fraction_numerical': 0.04951495553759094, 'mean_word_length': 5.980253878702397, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '627795', 'license': 'Apache-2.0', 'n_tokens_mistral': 1978, 'n_tokens_neox': 1782, 'n_words': 375, 'path': 'Credit Card Fraud detection.ipynb', 'repo_name': 'sankarsh1905/Credit_card_fraud_detection', 'size': '4948'}