In this post, we will examine one approach to automating parameter settings when developing a robust model for fraud detection. Once the parameters are tuned, we are one step closer to detecting instances of fraud.
Libraries
Below are the various libraries we are using in this post.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score
from sklearn.model_selection import GridSearchCV
import pandas as pd
import numpy as np
The RandomForestClassifier() is the algorithm we are using. The train_test_split() function will be used to divide our data into training and testing sets. The confusion_matrix(), classification_report(), and the roc_auc_score() functions will be used to assess the model. The GridSearchCV() function allows us to explore various values for different model parameters. Lastly, pandas and numpy will be used for data preparation purposes.
Data Prep
The data is dummy data that allows us to predict instances of fraud. The data is not available online. There are 30 variables in the dataset with generic column names (V1, V2, etc). For our purposes, columns 2 to 29 are our independent variables and column 30 is our dependent variable. We are going to separate the independent and dependent variables into two objects, as shown below.
X = df.iloc[:, 1:30]
X = np.array(X).astype('float')
y = df.iloc[:, 30]
y=np.array(y).astype('float')
The code shows how the columns were separated. Once they were separated, each object was converted to an array, as this is required for the algorithm we are using. In the code below, we create our train and test sets.
# Split your data into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=0)
The train and test sets consist of a total of 4 objects, 2 objects for the X values and t for the y value. The test sets for both objects represent 30% of the data, as shown with the argument test_size = 0.3. The random_state is also set in case we want to reproduce the results.
Model Development
Model development will involve creating a parameter grid. The purpose of the parameter grid is to provide several different values for different parameters that Python can test for to determine the best combination. Below is the code
# Define the parameter sets to test
param_grid = {'n_estimators': [15, 30],'max_features': ['sqrt', 'log2'], 'max_depth': [4, 8], 'criterion': ['gini', 'entropy']}
In the code above, we are setting values for the following parameters.
- n_estimators: Number of trees to create
- max_features: number of features to consider when searching for the best split at each node
- max_depth: How deep the tree can go
- Criterion: Measure of impurity
All of these values will be stored in an object called param_grid
Below, we will create an instance of the random forest classifier and set the seed number
# Define the model to use
model = RandomForestClassifier(random_state=5)
Next, we combine our work from the two previous lines of code into an object called CV_model. We use the GridSearchCV() function to use the model for the estimator argument and the param_grid object for the param_grid argument. We also set the cross-validation to 5, which means the data set will be divided into 5 parts. Four parts will be used for training, and the fifth part will be used for testing. This process is repeated five times, and the results are averaged. The metric for determining model success is set by the scoring argument, which uses recall. Lastly, the n_jobs parameter is related to processing.
# Combine the parameter sets with the defined model
CV_model = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, scoring='recall', n_jobs=-1)
Now we will fit our model and find what the best combination of parameters is.
# Fit the model to our training data and obtain best parameters
CV_model.fit(X_train, y_train)
CV_model.best_params_
{'criterion': 'gini',
'max_depth': 8,
'max_features': 'sqrt',
'n_estimators': 15}
The results are above. We can now take this information and set the parameters accordingly.
Set Parameters
In the code below, we are going to set our parameters as appropriate. Note also that there are other parameters in the code below that we did not search for. Trying to set multiple parameters can become computationally expensive, so we did not use Python to find values for them.
#Set parameters
model = RandomForestClassifier(class_weight={0:1,1:12}, criterion='gini',
max_depth=8, max_features='log2', min_samples_leaf=10,
n_estimators=15, n_jobs=-1, random_state=5)
With our model set up, we use the .fit() method and find predicted values and their probabilities. All the code below is a review from prior posts.
# Fit your training model to your training set
model.fit(X_train, y_train)
# Obtain the predicted values and probabilities from the model
predicted = model.predict(X_test)
probs = model.predict_proba(X_test)
With this information, we can now assess our model with the testing data
Model Assessment
Below are the results of the model assessment. We start with the roc_auc_score() function, which calculates the ROC value. The closer to 1, the stronger the model is. The score of 0.96 can be good, but it is relative to our purpose and the performance of other models.
Next, we examine the classification_report () and confusion_matrix() functions. The classification report shares the precision, recall, and F1-score. All of these values range from 0 to 1, and the results are good relative to our purposes. The confusion matrix shows us where different examples were classified.
print(roc_auc_score(y_test, probs[:,1]))
print(classification_report(y_test, predicted))
print(confusion_matrix(y_test, predicted))
0.9684596013800397
precision recall f1-score support
0.0 0.99 1.00 1.00 2099
1.0 0.94 0.84 0.88 91
accuracy 0.99 2190
macro avg 0.97 0.92 0.94 2190
weighted avg 0.99 0.99 0.99 2190
[[2094 5]
[ 15 76]]
The recall score indicates that the model struggles with false negatives or examples of fraud that were misclassified as not being fraud. Looking at the confusion matrix indicates that this happened 15 times. Whether or not to address this is a question that depends on the context.
Conclusion
The entire process of allowing the machine to set the parameters and detect fraud is explained here. With this knowledge, a person can also find the best values for their own models.






















































