Switch to unified view

a b/conditional_probability/logistic.py
1
import numpy as np
2
from sklearn.linear_model import LogisticRegression
3
from sklearn.metrics import roc_auc_score
4
from util import roc_results, results
5
6
7
def lr_training(x_train, y_train):
8
    """
9
    :param x_train: the x-values we want to train on (2D numpy array)
10
    :param y_train: the y-values that correspond to x_train (1D numpy array)
11
    :return: sklearn LogisticRegression object that can now be used for predictions
12
    """
13
    prob = LogisticRegression(penalty='l1', C=0.185, solver='saga', fit_intercept=True, random_state=0)
14
    prob.fit(x_train, y_train)
15
    return prob
16
17
18
def lr_probability(prob, x_test):
19
    """
20
    :param prob: trained sklearn LogisticRegression object
21
    :param x_test: the x-values we want to get predictions on (2D numpy array)
22
    :return: a 2D numpy array containing the probabilities for both classes
23
    """
24
    return prob.predict_proba(x_test)
25
26
27
def lr_classification(y_pred, threshold=0.5):
28
    """
29
    :param y_pred: a 1D numpy array containing the probabilities of x belonging to the positive class
30
    :param threshold: determines which class a probability estimate belongs to
31
    :return: a 1D numpy array containing the predictions
32
    """
33
    for i in range(y_pred.shape[0]):
34
        y_pred[i] = 1 if y_pred[i] > threshold else -1
35
    return y_pred
36
37
38
def lr_pipeline(x_train, y_train, x_test, y_test):
39
    """
40
    :param x_train: the x-values we want to train on (2D numpy array)
41
    :param y_train: the y-values that correspond to x_train (1D numpy array)
42
    :param x_test:  the x-values we want to test on (2D numpy array)
43
    :param y_test:  the y-values that correspond to x_test (1D numpy array)
44
    :return: the roc auc score
45
    """
46
    prob = lr_training(x_train, y_train)
47
    y_pred = lr_probability(prob, x_test)
48
    y_pred_class = lr_classification(np.copy(y_pred[:, 1]), threshold=0.436)
49
    roc_results(y_pred[:, 1], y_test, 'Logistic Regression')
50
    return roc_auc_score(y_test, y_pred[:, 1]), results(y_pred_class, y_test)