-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
147 lines (115 loc) · 4.71 KB
/
main.py
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
'''
# -----------------------
# Import Libraries
# -----------------------
'''
# OS
# -----------------------
import os
# Data Manipulation
# -----------------------
import pandas as pd
import numpy as np
# Data Visualisation
# -----------------------
import matplotlib.pyplot as plt
import seaborn as sns
# Machine Learning
# -----------------------
# scikit-learn
# -----------------------
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, \
mean_absolute_error
from sklearn.model_selection import RandomizedSearchCV
import xgboost as xgb # XGBoost
from xgboost import cv
'''
# -----------------------
# Main
# -----------------------
'''
if __name__ == "__main__":
# Set path
# -----------------------
# Dataset: https: // www.kaggle.com / datasets / maryam1212 / money - laundering - data?resource = download
df = pd.read_csv(r'C:\Users\cstevens\Desktop\Anti Money Laundering\archive\ML.csv')
df.drop('isfraud', axis=1, inplace=True)
df.describe()
df.info()
df.isnull().sum()
df.dropna(inplace=True)
# Feature Selection
# -----------------------
X = df.drop('typeoffraud', axis=1)
y = df['typeoffraud']
X.head()
y.head()
# Train-test Split
# -----------------------
X = pd.get_dummies(X).to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
'''
# Model Selection: XGBoost
# -----------------------
## General Parameters:
# -----------------------
booster: The type of booster to use, e.g., gbtree (tree-based models) or gblinear (linear models).
silent: Whether to print messages while running the model (default=1, set to 0 for verbose output).
nthread: Number of threads to use for parallel processing.
## Tree Booster Parameters:
# -----------------------
eta or learning_rate: Step size shrinkage to prevent overfitting.
min_child_weight: Minimum sum of instance weight needed in a child, used to control overfitting.
max_depth: Maximum depth of a tree, controls the complexity of the model.
gamma: Minimum loss reduction required to make a further partition on a leaf node.
subsample: Subsample ratio of the training instances to prevent overfitting.
colsample_bytree: Subsample ratio of columns when constructing each tree.
lambda or reg_lambda: L2 regularization term on weights.
alpha or reg_alpha: L1 regularization term on weights.
scale_pos_weight: Control the balance of positive and negative weights in the dataset for imbalanced classes.
## Linear Booster Parameters:
# -----------------------
lambda or reg_lambda: L2 regularization term on weights.
alpha or reg_alpha: L1 regularization term on weights.
lambda_bias: L2 regularization term on the bias term.
Learning Task Parameters:
objective: The learning task and corresponding objective function (e.g., binary:logistic for binary classification).
eval_metric: Evaluation metric used for early stopping and model evaluation (e.g., auc, error, logloss).
## Cross-validation Parameters:
# -----------------------
num_boost_round: The number of boosting rounds (trees) for training.
early_stopping_rounds: Activates early stopping, based on a validation set's performance.
evals: List of datasets to be used for early stopping.
'''
# Cross Validation
# -----------------------
classifier = xgb.XGBClassifier()
params = {
'learning_rate': [0.05, 0.10, 0.15, 0.20, 0.25, 0.30],
'max_depth': [3, 4, 5, 6, 8, 10, 12, 15],
'min_child_weight': [1, 3, 5, 7],
'gamma': [0.0, 0.1, 0.2, 0.3, 0.4],
'colsample_bytree': [0.3, 0.4, 0.5, 0.7]
}
rs_model = RandomizedSearchCV(classifier, param_distributions=params, n_iter=5, scoring='neg_log_loss',
n_jobs=-1, cv=5, verbose=3)
# Model Training
# -----------------------
rs_model.fit(X_train, y_train)
# Model Evaluation
# -----------------------
y_pred = rs_model.best_estimator_.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='micro')
recall = recall_score(y_test, y_pred, average='micro')
f1 = f1_score(y_test, y_pred, average='micro')
conf_matrix = confusion_matrix(y_test, y_pred)
print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("Confusion Matrix:\n", conf_matrix)