1.Machine Learning

# Introduction

Machine learning studies how to learn patterns from data and predict characteristics of unknown data.
According whether the predicted variable is known, machine learning generally fall into two categories: supervised learning and unsupervised learning.
In supervised learning, the model takes features and class labels or targer values as input to build the model. If the target variable (the variable to predict) is a categorical (e.g. positive/negative), the problem is called classification. If the target variable is continous (e.g. height), the problem is called regression. Most supervised learning problems fall into these two categories, however, combination of continous output and categorical output or structured output are also possible.
In unsupervised learning, the target variables are not specified. The objective is to identify internal structures (clusters) of the data. After model fitting, we can assign new samples to clusters or generate samples with similar distribution as the original data. Unsupervised learning are also useful as a data preprocessing step prior to supervised learning.

# Import data

Datasets for machine learning can be loaded from a variety of souces. Tabular data can be loaded through the pandas package in various formats:
Format Type
Data Description
Writer
text
CSV
text
JSON
text
HTML
text
Local clipboard
binary
MS Excel
binary
HDF5 Format
You can refer to Pandas IO Tools for more usage of data importing using pandas.
For large datasets, it is recommended to use binary formats such as HDF5 and NPZ for more efficient reading and writing and also reducing disk usage.
HDF5 format can be read to or write from numpy arrays conveniently using the h5py package:
1
import h5py
2
# read data assuming that datasets 'X' and 'y' exists in HDF5 file input_file
3
with h5py.File(input_file, 'r') as f:
4
X = f['X'][:]
5
y = f['y'][:]
6
# write data to HDF5 file output_file
7
# X and y are numpy arrays
8
with h5py.File(output_file, 'w') as f:
9
f.create_dataset('X', data=X)
10
f.create_dataset('y', data=y)
Copied!
NPZ format is native format for numpy. NPZ/NPY format can be read from file using numpy.load and write to file using numpy.save or numpy.savez.

# Import required Python packages

Documentation for required Python packages:
For Jupyter Notebook users, run the following magic command to display images inline.
1
# This is a magic funtion in IPython/Jupyter that import many functions and modules
2
# from matplotlib, numpy, scipy, which is roughly equivalent to:
3
#
4
# import numpy as np
5
# import numpy.ma as ma
6
# import matplotlib as mpl
7
# from matplotlib import cbook, mlab, pyplot as plt
8
# from matplotlib.pyplot import *
9
# from numpy import *
10
# from numpy.fft import *
11
# from numpy.random import *
12
# from numpy.linalg import *
13
%pylab inline
Copied!
1
Populating the interactive namespace from numpy and matplotlib
Copied!
If you run Python/IPython interactively or in a script, please run the following code instead.
1
from pylab import *
Copied!
1
from collections import defaultdict
2
# For data importing
3
import pandas as pd
4
# For machine learning
5
from sklearn.datasets import make_classification, make_regression, make_circles, make_moons, make_gaussian_quantiles
6
from sklearn.preprocessing import StandardScaler
7
from sklearn.linear_model import LogisticRegression
8
from sklearn.ensemble import RandomForestClassifier
9
from sklearn.neighbors import KNeighborsClassifier
10
from sklearn.tree import DecisionTreeClassifier
11
from sklearn.cluster import KMeans
12
from sklearn.svm import SVC, LinearSVC
13
from sklearn.gaussian_process import GaussianProcessClassifier
14
from sklearn.decomposition import PCA
15
from sklearn.model_selection import KFold, train_test_split, GridSearchCV, cross_val_score
16
from sklearn.metrics import accuracy_score, roc_auc_score, f1_score, recall_score, precision_score, \
17
roc_curve, precision_recall_curve, average_precision_score, matthews_corrcoef, confusion_matrix
18
19
# For plotting
20
import seaborn as sns
21
sns.set()
22
sns.set_style('whitegrid')
23
from matplotlib.colors import to_hex
Copied!

# Initialize random seed

We fix the random seed of numpy in this tutorial to make the results reproducible.
1
random_state = np.random.RandomState(1289237)
Copied!

# Generate datasets

You can start with simple datasets that is easy to understand and visualize before handling realistic datasets. scikit-learn provides many functions (sklearn.datasets) for generating datasets easily.

## Classification dataset

For example, sklearn.datasets.make_classification generates samples from a mixture of Gaussian distributions with parameters to specify the number of classes, number of features, number of classes, etc. The following example generate a two-class classification dataset of 1000 samples with 2 features for visualization. Samples are generated from two independent 2D Gaussian distributions. This dataset is suitable for linear classifier.
1
X, y = make_classification(n_samples=1000, n_classes=2, n_features=2,
2
n_informative=2, n_redundant=0, n_clusters_per_class=1,
3
random_state=random_state, class_sep=0.9)
4
fig, ax = plt.subplots(figsize=(7, 7))
5
for label in np.unique(y):
6
ax.scatter(X[y == label, 0], X[y == label, 1], s=10, label=str(label))
7
ax.legend(title='Class')
Copied!
png

## Regression dataset

You can also use make_regression to generate a simple regression dataset. The following dataset consists of 1000 samples with 1 feature and 1 response variable. A Gaussian noise 10 is added to each response variable.
1
X, y = make_regression(n_samples=1000, n_features=1, n_informative=1, noise=10, random_state=random_state)
2
fig, ax = plt.subplots(figsize=(7, 7))
3
ax.scatter(X[:, 0], y, s=5, label=str(label))
4
ax.set_xlabel('X')
5
ax.set_ylabel('y')
Copied!
1
Text(0,0.5,'y')
Copied!
png

## Specialized datasets

scikit-learn also provides sample generators for specialized classification/regression/clustering problems, e.g. make_circles, make_moons, make_gaussian_quantiles. These datasets can be used to demonstrate cases where simple classifier or clustering algorithms don't work but non-linear and more complicated algorithms work better.
1
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
2
3
for i, f in enumerate((make_circles, make_moons, make_gaussian_quantiles)):
4
if f == make_gaussian_quantiles:
5
X, y = f(n_samples=1000, random_state=random_state)
6
else:
7
X, y = f(n_samples=1000, noise=0.03,
8
random_state=random_state)
9
for label in np.unique(y):
10
axes[i].scatter(X[y == label, 0], X[y == label, 1], s=5, label=str(label))
11
axes[i].legend(title='Class')
12
axes[i].set_title(f.__name__)
Copied!
png

## The digits dataset

scikit-learn also includes some commonly used public datasets that is useful for exploring machine learning algorithms in the package. For example, the digits dataset is a small handwriting image dataset of 10 digits.
1
2
3
4
fig, ax = plt.subplots(figsize=(10, 11))
5
data = np.swapaxes(X[:16].reshape((-1, 8, 8)), 0, 1).reshape((8, -1))
6
with plt.rc_context({'axes.grid': False}):
7
ax.imshow(data, cmap='Greys')
8
ax.set_axis_off()
Copied!
png

## Dataset used in this tutorial

We use sklearn.datasets.make_classification to generate a dataset with 2 features
1
X, y = make_classification(n_samples=1000, n_classes=2, n_features=4,
2
n_informative=2, n_redundant=0, n_clusters_per_class=1,
3
class_sep=0.9, random_state=random_state)
Copied!

# Single feature analysis

## Analyze the separability of classes using individual features

Plot the distribution of feature values of each feature. A good feature should separate the two class well. The following plot shows that each individual feature can largely separate the two classes, though not perfectly.
1
fig, axes = plt.subplots(1, X.shape[1], figsize=(15, 4))
2
for i in range(X.shape[1]):
3
for label in (0, 1):
4
sns.kdeplot(X[y == label, i], label=str(label), ax=axes[i])
5
axes[i].legend(title='class')
6
axes[i].set_xlabel('Feature x[{}]'.format(i))
7
axes[i].set_ylabel('Density')
Copied!
png

## Feature correlation analysis

Sometimes highly correlated features may be detrimental to model performance and feature selection. A redundant feature does not provide more information, but introduces extra parameters to the model to make the model prone to overfitting. For feature selection, the model may assign a small weight to each redundant features too many redundant features may dilute the contribution of individual features. Although the impact of redundant features on model performance depends on the machine learning algorithm used, it is a good practice to identify these features and remove/merge redundant features.
1
data = pd.DataFrame(X, columns=['x[{}]'.format(i) for i in range(X.shape[1])])
2
data.loc[:, 'classes'] = y.astype('U')
3
g = sns.PairGrid(data, hue='classes', vars=['x[{}]'.format(i) for i in range(X.shape[1])])
4
g.map_offdiag(plt.scatter, s=3)
5
g.map_diag(sns.kdeplot)
6
Copied!
png

# PCA analysis

A dataset with more than 3 features cannot be visualized directly. We can use dimension reduction to embed the data on a 2D or 3D space. A dimension reduction algorithm maps data points in high dimension to low dimension while preserve distance in their original space as well as possible.
Principal Component Analysis (PCA) is the most common algorithm for dimension reduction. It maps data to a new space by linear combination of original features such that new features are linearly independent and the total variance is maximized.
If samples can be separated well in a PCA plot, a linear classifier also works well. Otherwise, a non-linear classifier may improve classification performance.
1
X_scaled = StandardScaler().fit_transform(X)
2
pca = PCA()
3
X_pca = pca.fit_transform(X)
4
fig, axes = plt.subplots(1, 2, figsize=(15, 8))
5
axes[0].plot(np.arange(0.5, X.shape[1] + 0.5), pca.explained_variance_ratio_, marker='o')
6
axes[0].set_xticks(np.arange(0.5, X.shape[1] + 0.5))
7
axes[0].set_xticklabels(np.arange(1, X.shape[1] + 1))
8
axes[0].set_xlabel('PC rank')
9
axes[0].set_ylabel('Explained variance ratio')
10
axes[0].set_ylim(0, 1)
11
axes[0].set_xlim(0, X.shape[1])
12
13
for label in np.unique(y):
14
axes[1].scatter(X_pca[y == label, 0], X_pca[y == label, 1], label=label, s=10)
15
axes[1].set_xlabel('PC1 ({:.02f}%)'.format(pca.explained_variance_ratio_[0]*100))
16
axes[1].set_ylabel('PC2 ({:.02f}%)'.format(pca.explained_variance_ratio_[1]*100))
Copied!
1
Text(0,0.5,'PC2 (26.05%)')
Copied!
png

# Data scaling

For most machine learning algorithms, it is recommended to scale the features to a common small scale. Features of large or small scale increase the risk of numerical instability and also make the loss function harder to optimize. Feature selection based on fitted coefficients of a linear model assumes that the input features are in the same scale. Performance and convergence speed of gradient-based algorithms such as neural networks are largely degraded if the data is not properly scaled. Decision tree and random forest, however, are less sensitive to data scale because they use rule-based criteria.
Common data scaling methods include standard/z-score scaling, min-max scaling, robust scaling and abs-max scaling.
Standard/z-score scaling first shift features to their centers(mean) and then divide by their standard deviation. This method is suitable for most continous features of approximately Gaussian distribution.
$\text{zscore}(x_{ij}^{'}) = \frac{x_{ij} - \mu _{ij}}{\sigma _i}$
Min-max scaling method scales data into range [0, 1]. This method is suitable for data concentrated within a range and preserves zero values for sparse data. Min-max scaling is also sensitive to outliers in the data. Try removing outliers or clip data into a range before scaling.
Max-abs scaling method is similar to min-max scaling, but scales data into range [-1, 1]. It does not shift/center the data and thus preserves signs (positive/negative) of features. Like min-max, max-abs is sensitive to outliers.
Robust scaling method use robust statistics (median, interquartile range) instead of mean and standard deviation. Median and IQR are less sensitive to outliers. For features with large numbers of outliers or largely deviates from normal distribution, robust scaling is recommended.
1
x = random_state.normal(10, 2, size=1000)
2
fig, ax = plt.subplots(figsize=(8, 6))
3
sns.distplot(x, ax=ax)
4
sns.distplot(np.ravel(StandardScaler().fit_transform(x.reshape((-1, 1)))), ax=ax)
Copied!
png
1
# Generate features with different distribution
2
x = np.zeros((1000, 4))
3
x[:, 0] = random_state.normal(10, 2, size=x.shape[0])
4
x[:, 1] = random_state.gamma(shape=3, scale=4, size=x.shape[0])
5
x[:, 2] = random_state.poisson(5, size=x.shape[0])
6
x[:, 3] = random_state.uniform(-3, 6, size=x.shape[0])
7
8
from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler
9
scalers = {
10
'Standard': StandardScaler(),
11
'MinMax': MinMaxScaler(),
12
'MaxAbs': MaxAbsScaler(),
13
'Robust': RobustScaler()
14
}
15
fig, axes = plt.subplots(5, x.shape[1], figsize=(16, 20))
16
for i in range(x.shape[1]):
17
sns.distplot(x[:, i], ax=axes[0, i])
18
axes[0, i].set_title('Original feature {}'.format(i + 1))
19
for j, scaler_name in enumerate(scalers.keys()):
20
x_scaled = scalers[scaler_name].fit_transform(x)
21
for i in range(x.shape[1]):
22
sns.distplot(x_scaled[:, i], ax=axes[j + 1, i])
23
axes[j + 1, i].set_title('{} for feature {}'.format(scaler_name, i + 1))
Copied!
png
1
X = StandardScaler().fit_transform(X)
Copied!

# Split data into training and test set

We should split the dataset into a training and test set to evaluate model performance. During model training, the model overfits to the data to some extent, and so model performance on the training set is generally biases and higher than on the test set. The overfitting issue can be resolved by adding more independent samples to the dataset. The difference of training and test performance decreases with the increase of sample size.
Here, we use train_test_split to randomly set 80% of the samples as training set and 20% as test set.
1
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state)
2
print('number of training samples: {}, test samples: {}'.format(X_train.shape[0], X_test.shape[0]))
Copied!
1
number of training samples: 800, test samples: 200
Copied!

# Train the model

During model training, the parameters of the model is adjusted to minimize a loss function.

## Logistic regression

Logistic regression is a linear model for classification. It first forms linear combination of input features and then map the combined value to class probability between 0 and 1 through a non-linear sigmoid function. During model training, the weights of the model are adjusted such that the cross-entropy between model prediction and true labels is minimized.
$p(y_i | \mathbf{x}_i) = \frac{1}{1 + \text{exp} \left( \sum_{j=1}^M x_{ij} w_{j} + b \right)}$
1
model = LogisticRegression()
2
_ = model.fit(X_train, y_train)
Copied!

# Model inspection

## Feature importance

For linear models (e.g. Logistic regression, linear regression, linear SVM), feature importance is usually defined as the square of coefficients:
$\text{FeatureImportance}_j = w_{j}^2$
1
fig, ax = plt.subplots(figsize=(4, 4))
2
feature_importance = np.square(np.ravel(model.coef_))
3
ax.bar(np.arange(1, X.shape[1] + 1).astype('U'), feature_importance)
4
ax.set_xlabel('Feature')
5
_ = ax.set_ylabel('Feature importance')
Copied!
png

## Decision boundary

We can inspect decision boundaries of a model by predict class labels on a 2D grid of sample points. You can see that the decision boundary of Logistic regression is a straight line while other classifiers create non-linear and irregular decision boundaries.
1
X_grid, Y_grid = np.mgrid[-5:5:0.1, -5:5:0.1]
2
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
3
4
from matplotlib.colors import ListedColormap
5
cmap = sns.diverging_palette(252, 17, n=2)
6
cmap = ListedColormap(cmap)
7
8
# Use top 2 features
9
selected_features = np.argsort(-feature_importance)[:2]
10
for n, model_class in enumerate((LogisticRegression, SVC,
11
DecisionTreeClassifier, KNeighborsClassifier,
12
GaussianProcessClassifier, RandomForestClassifier)):
13
i, j = n//3, n%3
14
model_n = model_class()
15
model_n.fit(X_train[:, selected_features], y_train)
16
labels_grid = model_n.predict(np.column_stack([np.ravel(X_grid), np.ravel(Y_grid)]))
17
18
axes[i, j].pcolor(X_grid, Y_grid, labels_grid.reshape(X_grid.shape),
19
cmap=cmap, linewidth=0, edgecolor='face', alpha=0.3)
20
axes[i, j].set_title(model_class.__name__)
21
for label in np.unique(y):
22
axes[i, j].scatter(X_train[y_train == label, selected_features[0]],
23
X_train[y_train == label, selected_features[1]],
24
s=3, label=str(label))
25
axes[i, j].legend(title='class')
Copied!
png

# Evaluate the model

## Predict labels on the test dataset

To evaluate performance of the model, we use the predict method of the estimator to predict class labels of test data. This will return an integer array indicating class labels.
1
y_pred = model.predict(X_test)
Copied!

## Confusion matrix

The most common way to evaluate classification performance is to construct a confusion matrix.
A confusion matrix summarizes the number of correctly or wrongly predicted samples and is usually made up of four entries:
Predicted
Negative
Positive
True
Negative
True Negative (TN)
False Negative (FN)
Positive
False Positive (FP)
True Positive (TP)
1
pd.DataFrame(confusion_matrix(y_test, y_pred),
2
columns=pd.Series(['Negative', 'Positive'], name='Predicted'),
3
index=pd.Series(['Negative', 'Positive'], name='True'))
Copied!
Predicted
Negative
Positive
True
Negative
81
8
Positive
27
84

## Evaluation metrics for classification

A variety of metrics can be calculate from entries in the confusion matrix.
Accuracy (0 ~ 1) summarizes both positive and negative predictions, but is biased if the classes are imbalanced:
$\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}$
Recall/sensitivity (0 ~ 1) summarizes how well the model finds out positive samples:
$\text{Recall/Sensitivity} = \frac{TP}{TP + FN}$
Precision/positive predictive value (0 ~ 1) summarizes how well the model finds out negative samples:
$\text{Precision/Positive Predictive Value} = \frac{TP}{TP + FP}$
F1 score (0 ~ 1) balances between positive predictive value (PPV) and true positive rate (TPR) and is more suitable for imbalanced dataset:
$\text{F1 score} = 2 \frac{PPV \cdot TPR}{PPV + TPR}$
Matthews correlation coefficient (MCC) (-1 ~ 1) is another metric that balances between recall and precision:
$\text{MCC} = \frac{TP \times TN - FP \times FN} {(TP + FN)(TP + FP)(TN + FP)(TN + FN)}$
1
scorers = {'accuracy': accuracy_score,
2
'recall': recall_score,
3
'precision': precision_score,
4
'f1': f1_score,
5
'mcc': matthews_corrcoef
6
}
7
for metric in scorers.keys():
8
print('{} = {}'.format(metric, scorers[metric](y_test, y_pred)))
Copied!
1
accuracy = 0.825
2
recall = 0.7567567567567568
3
precision = 0.9130434782608695
4
f1 = 0.8275862068965518
5
mcc = 0.6649535460625479
Copied!

## Predict class probability

Many classifiers first predict a continous value for each sample indicating confidence/probability of the prediction and then choose a fixed cutoff (e.g. 0.5 for probability values) to convert the continous values to binary labels. We can get the raw prediction values through the predict_proba method.
1
y_score = model.predict_proba(X_test)
Copied!

## ROC curve and precision-recall curve

Sometimes a single fixed cutoff is insufficient to evaluate model performance. Receiver Operating Characterisic (ROC) curve and Precision-Recall curve are useful tools to inspect the model performance with different cutoffs. ROC curve and precision-recall curve are also less sensitive to class imbalance. Compared to ROC curve, precision-recall curve are more suitable for extremely imbalanced datasets.
The area under the ROC curve (AUROC) or average precision (AP) is a single value that summarizes average model performance under different cutoffs and are very commonly used to report classification performance.
1
fig, axes = plt.subplots(1, 2, figsize=(14, 7))
2
# ROC curve
3
fpr, tpr, thresholds = roc_curve(y_test, y_score[:, 1])
4
ax = axes[0]
5
ax.plot(fpr, tpr, label='ROAUC = {:.4f}'.format(roc_auc_score(y_test, y_score[:, 1])))
6
ax.plot([0, 1], [0, 1], linestyle='dashed')
7
ax.set_xlabel('False positive rate')
8
ax.set_ylabel('True positive rate')
9
ax.set_title('ROC curve')
10
ax.legend()
11
# predision-recall curve
12
precision, recall, thresholds = precision_recall_curve(y_test, y_score[:, 1])
13
ax = axes[1]
14
ax.plot(precision, recall, label='AP = {:.4f}'.format(average_precision_score(y_test, y_score[:, 1])))
15
ax.plot([0, 1], [1, 0], linestyle='dashed')
16
ax.set_xlabel('Precision')
17
ax.set_ylabel('Recall')
18
ax.set_title('Precision-recall curve')
19
ax.legend()
Copied!
png

# Cross-validation

For very large datasets, a single split of the dataset into a training set and a test set is sufficient to evaluate the model performance. However, for small dataset, the test samples represent only a small proportion of samples in future predictions. The model performance evaluated on the test samples varies greatly between resamplings of the dataset.

## K-fold cross-validation

Cross-validation is a commonly used technique for model evaluation on small dataset. In k-fold cross-validation, the dataset is evenly divided into k partitions(folds). In each round of validation, the model is tested on one parition and trained on remaining (k-1)/k partitions. K-fold cross-validation ensures that there is no overlap between training and test samples but can have overlaps between rounds. Each sample is set as test sample for exactly once. Finally, the average performance is calculated across k rounds.
scikit-learn provides [many functions for splitting datasets] (http://scikit-learn.org/stable/modules/classes.html#module-sklearn.model_selection).
Here, we use KFold to create 10-fold cross-validation datasets. 5 and 10 are commonly used values for k. Use 10-fold cross-validation if the sample size and computation burden permits.
The following code illustrates how KFold splits the dataset. Black boxes indicates test samples in each round.
1
n_splits = 10
2
3
kfold = KFold(n_splits=n_splits, random_state=random_state)
4
is_train = np.zeros((n_splits, X.shape[0]), dtype=np.bool)
5
for i, (train_index, test_index) in enumerate(kfold.split(X, y)):
6
is_train[i, train_index] = 1
7
8
fig, ax = plt.subplots(figsize=(15, 3))
9
ax.pcolormesh(is_train)
10
ax.set_yticks(np.arange(n_splits) + 0.5)
11
ax.set_yticklabels(np.arange(n_splits) + 1)
12
ax.set_ylabel('Round')
13
ax.set_xlabel('Sample')
Copied!
1
Text(0.5,0,'Sample')
Copied!
png
Then we train the model on each training set and predict labels and scores on the whole dataset.
1
predictions = np.zeros((n_splits, X.shape[0]), dtype=np.int32)
2
predicted_scores = np.zeros((n_splits, X.shape[0]))
3
4
for i in range(n_splits):
5
model.fit(X[is_train[i]], y[is_train[i]])
6
predictions[i] = model.predict(X)
7
predicted_scores[i] = model.predict_proba(X)[:, 1]
Copied!

## Collect evaluation metrics

Next, we evaluates the model using K-fold cross-validation.
1
cv_metrics = pd.DataFrame(np.zeros((n_splits*2, len(scorers) + 2)),
2
columns=list(scorers.keys()) + ['roc_auc', 'average_precision'])
3
cv_metrics.loc[:, 'dataset'] = np.empty(n_splits*2, dtype='U')
4
for i in range(n_splits):
5
for metric in scorers.keys():
6
cv_metrics.loc[i*2 + 0, metric] = scorers[metric](y[is_train[i]], predictions[i, is_train[i]])
7
cv_metrics.loc[i*2 + 1, metric] = scorers[metric](y[~is_train[i]], predictions[i, ~is_train[i]])
8
cv_metrics.loc[i*2 + 0, 'roc_auc'] = roc_auc_score(y[is_train[i]], predicted_scores[i, is_train[i]])
9
cv_metrics.loc[i*2 + 1, 'roc_auc'] = roc_auc_score(y[~is_train[i]], predicted_scores[i, ~is_train[i]])
10
cv_metrics.loc[i*2 + 0, 'average_precision'] = average_precision_score(y[is_train[i]],
11
predicted_scores[i, is_train[i]])
12
cv_metrics.loc[i*2 + 1, 'average_precision'] = average_precision_score(y[~is_train[i]],
13
predicted_scores[i, ~is_train[i]])
14
cv_metrics.loc[i*2 + 0, 'dataset'] = 'train'
15
cv_metrics.loc[i*2 + 1, 'dataset'] = 'test'
16
17
Copied!
accuracy
recall
precision
f1
mcc
roc_auc
average_precision
dataset
0
0.832222
0.797386
0.863208
0.828992
0.666847
0.908640
0.931433
train
1
0.810000
0.809524
0.755556
0.781609
0.614965
0.882184
0.844361
test
2
0.818889
0.781737
0.843750
0.811561
0.639439
0.898143
0.915890
train
3
0.900000
0.961538
0.862069
0.909091
0.804601
0.985176
0.988980
test
4
0.828889
0.796909
0.853428
0.824201
0.659380
0.905196
0.924640
train

## Summarize evaluate metrics

Take average of model performance across cross-validation runs:
1
cv_metrics_mean = cv_metrics.groupby('dataset').mean()
2
cv_metrics_mean
Copied!
accuracy
recall
precision
f1
mcc
roc_auc
average_precision
dataset
test
0.831000
0.794919
0.861380
0.823425
0.667898
0.903903
0.921943
train
0.833778
0.795302
0.862274
0.827428
0.669625
0.906041
0.924631
1
fig, ax = plt.subplots(figsize=(10, 5))
2
plot_data = pd.melt(cv_metrics, id_vars=['dataset'], var_name='metric', value_name='value')
3
sns.stripplot(x='metric', y='value', hue='dataset',
4
dodge=True, jitter=True, data=plot_data, size=4, ax=ax)
5
#sns.pointplot(x='metric', y='value', hue='dataset', data=plot_data, markers="d",
6
# join=False, ci=None, ax=ax, dodge=True, palette='dark')
7
ax.set_title('Model performance using 10-fold cross-validation')
Copied!
1
Text(0.5,1,'Model performance using 10-fold cross-validation')
Copied!
png

## ROC and PR curves

For each cross-validation run, compute an ROC/PR curve. Then plot the mean and confidence intervals across cross-validation runs.
1
from scipy import interp
2
3
fig, axes = plt.subplots(1, 2, figsize=(14, 7))
4
# ROC curve
5
ax = axes[0]
6
all_fprs = np.linspace(0, 1, 100)
7
roc_curves = np.zeros((n_splits, len(all_fprs), 2))
8
for i in range(n_splits):
9
fpr, tpr, thresholds = roc_curve(y[~is_train[i]], predicted_scores[i, ~is_train[i]])
10
roc_curves[i, :, 0] = all_fprs
11
roc_curves[i, :, 1] = interp(all_fprs, fpr, tpr)
12
roc_curves = pd.DataFrame(roc_curves.reshape((-1, 2)), columns=['fpr', 'tpr'])
13
sns.lineplot(x='fpr', y='tpr', data=roc_curves, ci='sd', ax=ax,
14
label='Test AUC = {:.4f}'.format(cv_metrics_mean.loc['test', 'roc_auc']))
15
#ax.plot(fpr, tpr, label='ROAUC = {:.4f}'.format(roc_auc_score(y_test, y_score[:, 1])))
16
#ax.plot([0, 1], [0, 1], linestyle='dashed')
17
ax.set_xlabel('False positive rate')
18
ax.set_ylabel('True positive rate')
19
ax.plot([0, 1], [0, 1], linestyle='dashed', color='gray')
20
ax.set_title('ROC curve')
21
ax.legend()
22
23
# predision-recall curve
24
ax = axes[1]
25
all_precs = np.linspace(0, 1, 100)
26
pr_curves = np.zeros((n_splits, len(all_precs), 2))
27
for i in range(n_splits):
28
fpr, tpr, thresholds = precision_recall_curve(y[~is_train[i]], predicted_scores[i, ~is_train[i]])
29
pr_curves[i, :, 0] = all_precs
30
pr_curves[i, :, 1] = interp(all_precs, fpr, tpr)
31
pr_curves = pd.DataFrame(pr_curves.reshape((-1, 2)), columns=['precision', 'recall'])
32
sns.lineplot(x='precision', y='recall', data=pr_curves, ci='sd', ax=ax,
33
label='Test AP = {:.4f}'.format(cv_metrics_mean.loc['test', 'average_precision']))
34
35
ax.set_xlabel('Precision')
36
ax.set_ylabel('Recall')
37
ax.plot([0, 1], [1, 0], linestyle='dashed', color='gray')
38
ax.set_title('Precision-recall curve')
39
ax.legend()
Copied!
png

# Homework

1.
Understand and run all code in this tutorial using Jupyter. You can generate different types of dataset or use a real dataset.
2.
Try different classifiers (SVC, random forest, logistic regression, KNN) and compare model performance.
3.
Try different K's in K-fold cross-validation and compare mean and variance of model performance.
4.
Try different class ratios and compare model performance.

## Books

1.
Trevor Hastie, Robert Tibshirani, Jerome Friedman. (2009). The Elements of Statistical Learning.
2.
Christopher Bishop. (2006). Pattern Recognition and Machine Learning.
3.
Kevin P. Murphy. (2012). Machine Learning A Probabilisitic Perspective.
4.
Sergios Theodoridis. (2009). Pattern Recognition.

## Class imbalance

1.
He, H., and Garcia, E.A. (2009). Learning from Imbalanced Data. IEEE Transactions on Knowledge and Data Engineering 21, 1263–1284.
2.
Batista, G.E.A.P.A., Prati, R.C., and Monard, M.C. (2004). A Study of the Behavior of Several Methods for Balancing Machine Learning Training Data. SIGKDD Explor. Newsl. 6, 20–29.
3.
Chawla, N.V., Bowyer, K.W., Hall, L.O., and Kegelmeyer, W.P. (2002). SMOTE: Synthetic Minority Over-sampling Technique. J. Artif. Int. Res. 16, 321–357.

## Machine learning in R

The caret package (a tutorial in GitBook): http://topepo.github.io/caret