<jupyter_start><jupyter_text>Credit Card Fraud Using Logistic Regression<jupyter_code>import warnings
warnings.filterwarnings("ignore")

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.preprocessing import power_transform
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, precision_recall_curve, accuracy_score, precision_score, recall_score, f1_score

from yellowbrick.classifier import DiscriminationThreshold
df = pd.read_csv("creditcard.csv")
df.head()
df.info()
df.describe().astype("int")
df["Class"].value_counts(normalize=True)*100
X = df.drop("Class", axis=1)
y = df["Class"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
X_train = X_train.drop("Time", axis=1)
X_test = X_test.drop("Time", axis=1)
sns.distplot(X_train["Amount"])
X_train[["Amount"]] = power_transform(X_train[["Amount"]])
sns.distplot(X_train["Amount"])
X_train["Class"] = y_train
X_train["Class"].value_counts()
X_train.sample(frac=1, random_state=42) # shuffle dataset
X_train_false = X_train[X_train["Class"] == 0].sample(n=356, random_state=42) # select first 356 samples
X_train_true = X_train[X_train["Class"] == 1]

X_train  = pd.concat([X_train_true, X_train_false])
X_train = X_train.sample(frac=1, random_state=42) # shuffle
y_train = X_train["Class"] # assign target variable (after undersampling) back to y_train
X_train = X_train.drop("Class", axis=1)
clf = LogisticRegression(penalty="l2", random_state=42)
clf.fit(X_train, y_train)
sns.heatmap(confusion_matrix(y_true = y_train, y_pred = clf.predict(X_train)), cmap="icefire", annot=True, fmt=".2f");
plt.title("Confusion Matrix of Predicted Train Data")
plt.xlabel("Predicted")
plt.ylabel("Actual");
fig, ax = plt.subplots(nrows=2, ncols=5, figsize=(15, 8))
ax = ax.flatten()
threshold = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
axes = 0

for i in threshold:
    X_train_prob = clf.predict_proba(X_train)
    y_pred = X_train_prob[:,1] # index probability of fraud
    y_pred[y_pred >= i] = 1
    y_pred[y_pred < i] = 0
    ax[axes] = sns.heatmap(confusion_matrix(y_train, y_pred), annot=True, cmap="icefire", fmt=".2f", ax=ax[axes]);
    ax[axes].set_title(f"{round(i, 2)}")
    axes += 1

plt.tight_layout()
threshold = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

for i in threshold:
    X_train_prob = clf.predict_proba(X_train)
    y_pred = X_train_prob[:,1] # index probability of fraud
    y_pred[y_pred >= i] = 1
    y_pred[y_pred < i] = 0
    print(f"========== Classification Report with Threshold as {round(i, 2)} ==========\n")
    print(f"\t\t\tAccuracy: {round(accuracy_score(y_train, y_pred), 2)}")
    print(f"\t\t\tPrecision: {round(precision_score(y_train, y_pred), 2)}")
    print(f"\t\t\tRecall: {round(recall_score(y_train, y_pred), 2)}")
    print(f"\t\t\tF1: {round(f1_score(y_train, y_pred), 2)}")
    print("\n")
visualizer = DiscriminationThreshold(clf, random_state=42)
visualizer.fit(X_train, y_train)
visualizer.show();
X_test["Amount"] = power_transform(X_test[["Amount"]])[:,0]
X_test_prob = clf.predict_proba(X_test)
y_pred = X_test_prob[:,1] # index probability of fraud
y_pred[y_pred >= 0.73] = 1
y_pred[y_pred < 0.73] = 0

sns.heatmap(confusion_matrix(y_test, y_pred), cmap="icefire", annot=True, fmt=".2f");
accuracy_score(y_test, y_pred)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16344767944652638, 'fraction_numerical': 0.03084462381089651, 'mean_word_length': 6.154639175257732, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '281588', 'license': 'MIT', 'n_tokens_mistral': 1456, 'n_tokens_neox': 1368, 'n_words': 271, 'path': 'modeling w logistic.ipynb', 'repo_name': 'Shinyui/Credit-Card-Fraud-Detection', 'size': '3469'}