-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysisModel.py
More file actions
200 lines (112 loc) · 4.15 KB
/
Copy pathanalysisModel.py
File metadata and controls
200 lines (112 loc) · 4.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import joblib
warnings.filterwarnings("ignore")
sns.set_theme(style="whitegrid")
df = pd.read_csv(r"C:\Users\dell\OneDrive\Desktop\FraudDetectionSystem\fraudenv\AIML Dataset.csv")
df.head()
# #### This Loads dataset in Chunks
# first_chunk = next(df) ## loading the dataset in chunks
# first_chunk.head()
# for chunk in df:
# print(f"The size of the chunk is {len(chunk)}") ## loading the dataset in chunks
df.info()
df["isFraud"].value_counts()
df["isFlaggedFraud"].value_counts()
df.shape
df.isnull().sum()
round((df["isFraud"].value_counts()[1] / df.shape[0]) * 100, 2) ## percentage of frauds
df["type"].value_counts().plot(kind="bar", title="Transaction Types", color="skyblue")
plt.xlabel("Transaction Types")
plt.ylabel("Counts")
plt.show()
fraud_by_type = df.groupby("type")["isFraud"].mean().sort_values(ascending=False)
fraud_by_type.plot(kind="bar", color="salmon", title="Fraud By Transaction Type")
plt.xlabel("Transaction Type")
plt.ylabel("Fraud Count")
plt.show()
df["amount"].describe().astype(int)
sns.histplot(np.log1p(df["amount"]), kde=True, bins=100, color="green")
plt.title("Transaction Amount Distribution (Log Scale)")
plt.xlabel("Log (Amount+1)")
plt.show()
sns.boxplot(data=df[df["amount"] < 50000], x="isFraud", y="amount")
plt.title("Amount vs Title under 50k")
plt.show()
df.columns
df["BalancedDiffOriginator"] = df["oldbalanceOrg"] - df["newbalanceOrig"]
df["BalancedDiffDestination"] = df["newbalanceDest"] - df["oldbalanceDest"]
(df["BalancedDiffOriginator"] < 0).sum() ## Fund Injection
(df["BalancedDiffDestination"] < 0).sum() ## Fund Injection
frauds_per_step = df[df["isFraud"] == 1]["step"].value_counts().sort_index()
plt.plot(frauds_per_step.index, frauds_per_step.values, label="Frauds Per Step")
plt.xlabel("Step (Time)")
plt.ylabel("Number of Frauds")
plt.title("Frauds Over Time")
plt.grid(True)
plt.show()
df.drop(columns="step", inplace=True)
df.head()
top_sender = df["nameOrig"].value_counts().head(10)
top_sender
top_receivers = df["nameDest"].value_counts().head(10)
top_receivers
fraud_users = df[df["isFraud"] == 1]["nameOrig"].value_counts().head(10)
fraud_users
fraud_types = df[df["type"].isin(["TRANSFER", "CASH_OUT"])]
fraud_types["type"].value_counts()
sns.countplot(data=fraud_types, x="type", hue="isFraud")
plt.title("Fraud Distribution in TRANSFER and CASH_OUT")
plt.show()
corr = df[
[
"amount",
"oldbalanceOrg",
"newbalanceOrig",
"oldbalanceDest",
"newbalanceDest",
"isFraud",
]
].corr()
corr
sns.heatmap(data=corr, cmap="coolwarm", fmt=".2f", annot=True)
plt.title("Correlation Matrix")
plt.show()
zero_after_transfer = df[(df['oldbalanceOrg']>0) & (df['newbalanceOrig']==0) & (df['type'].isin(['TRANSFER','CASH_OUT']))]
zero_after_transfer.head()
df['isFraud'].value_counts()
df_model = df.drop(['nameOrig','nameDest','isFlaggedFraud'],axis=1)
df_model.head()
df_model.shape
categorical = ['type']
numeric = ['amount','oldbalanceOrg','newbalanceOrig','oldbalanceDest','newbalanceDest']
X = df_model.drop(['isFraud'],axis=1)
Y = df_model['isFraud']
X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.3,stratify=Y)
preprocessor = ColumnTransformer(
transformers=[
('Num_Col',StandardScaler(),numeric),
('Cat_Col',OneHotEncoder(drop='first'),categorical)
],
remainder = 'drop'
)
pipeline = Pipeline([
('Prepare',preprocessor),
('Clf',LogisticRegression(class_weight='balanced',max_iter=1000))
])
pipeline.fit(X_train,y_train)
y_pred = pipeline.predict(X_test)
print(classification_report(y_test,y_pred))
confusion_matrix(y_test,y_pred)
pipeline.score(X_test,y_test)*100
joblib.dump(pipeline,'Fraud_detection_pipeline.pkl')