a b/binary_classification/random_forests.py
1
from sklearn.ensemble import RandomForestClassifier
2
from sklearn.metrics import roc_auc_score
3
from util import roc_results, results
4
5
6
def rf_training(x_train, y_train):
7
    """
8
    :param x_train: the x-values we want to train on (2D numpy array)
9
    :param y_train: the y-values that correspond to x_train (1D numpy array)
10
    :return: sklearn random forest classifier object that can now be used for predictions
11
    """
12
    clf = RandomForestClassifier(n_estimators=100, criterion='gini', max_depth=4, max_features='log2',
13
                                 min_samples_split=25, min_samples_leaf=7, bootstrap=True, random_state=0)
14
    clf.fit(x_train, y_train)
15
    return clf
16
17
18
def rf_classification(clf, x_test):
19
    """
20
    :param clf: trained sklearn random forest classifier object
21
    :param x_test: the x-values we want to get predictions on (2D numpy array)
22
    :return: a 1D numpy array containing the predictions
23
    """
24
    return clf.predict(x_test)
25
26
27
def rf_pipeline(x_train, y_train, x_test, y_test):
28
    """
29
    :param x_train: the x-values we want to train on (2D numpy array)
30
    :param x_test: the y-values that correspond to x_train (1D numpy array)
31
    :param y_train: the x-values we want to test on (2D numpy array)
32
    :param y_test: the y-values that correspond to x_test (1D numpy array)
33
    :return: the roc auc score
34
    """
35
    clf = rf_training(x_train, y_train)
36
    y_pred = rf_classification(clf, x_test)
37
    roc_results(y_pred, y_test, 'Random Forest')
38
    return roc_auc_score(y_test, y_pred), results(y_pred, y_test)