# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import sys
import numpy
import pandas
import matplotlib
import scipy
import seaborn
import sklearn

print("python : {}".format(sys.version))
print("numpy : {}".format(numpy.__version__))
print("pandas : {}".format(pandas.__version__))
print("matplotlib : {}".format(matplotlib.__version__))
print("scipy : {}".format(scipy.__version__))
print("seaborn : {}".format(seaborn.__version__))
print("sklearn : {}".format(sklearn.__version__))
# -

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


# +
#loading data sets  download it  from kaggle  approx.of size 150mb 
data=pd.read_csv("creditcard.csv")

#exploring datasets
print(data.shape)
print(data.columns)

#"class" in columns has  two value 0=credit_card_transaction; 1=fraudaluent_transaction
# -

print(data.describe())

#minimising data to 10%
data=data.sample(frac=0.1,random_state=1)
print(data.shape)

#ploting histogram of each parameter  of  data
data.hist(figsize= (20,20))
plt.show()

# +
#determining no. of fraud cases in datasets
fraud=data[data['Class']==1]
valid=data[data['Class']==0]

outlier_fraction =len(fraud)/float(len(valid))
print(outlier_fraction)

print("Fraud cases: {}".format(len(fraud)))
print("Valid cases: {}".format(len(valid)))

# +
#correlation matrix
corrmap=data.corr()
fig=plt.figure(figsize=(12,9))

sns.heatmap(corrmap,vmax=.8,square=True)
plt.show()
# -

#getting all  the column fromthe  dataframe
columns=data.columns.tolist()
print(columns)

# +
# filtering the data-column which we do not need
columns=[c for c in columns if c not in ['Class']]
print(columns)

# store  the  variable  we'll be  predicting
target="Class"

X=data[columns]  # columns in whichwe are intrested in
Y=data[target] #  target  column  0= valid transaction; 1=fraud transaction

# print the shape
print(X.shape)
print(Y.shape)

# +
from sklearn.metrics  import classification_report,accuracy_score
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor #calculates on the density  of loacls

# define random-state
state=1

# define the outlier detection methods  in  Dictionary data-type

classifiers = {
    "Isolation Forest": IsolationForest(max_samples=len(X),
                                       contamination = outlier_fraction,
                                       random_state=state),
    "Local Outlier Factor": LocalOutlierFactor(
        n_neighbors =  20,
        contamination = outlier_fraction )
}


# +
#  fitting the model
n_outliers=len(fraud)

for i, (clf_name, clf) in enumerate(classifiers.items()):
    
    #fit  the  data and tag outliers
    
    if clf_name=="Local Outlier Factor":
        y_pred=clf.fit_predict(X)
        score_pred=clf.negative_outlier_factor_
    else:
        clf.fit(X)
        score_pred=clf.decision_function(X)
        y_pred=clf.predict(X)
        
    #reshape the  prediction values to 0 for valid and 1  for fraud
    y_pred[y_pred == 1] = 0
    y_pred[y_pred == -1] = 1
    
    n_errors=(y_pred !=Y).sum()
    
    # Run the classification matrix
    print("(): {}".format(clf_name,n_errors))
    print(accuracy_score(Y,y_pred))
    print(classification_report(Y,y_pred))
# -



StarcoderdataJupyterScriptsDedupFiltered