Machine Learning Practice
There are broadly two types of APIs based on their functionality:
Specific
Generic
Uses gradient descent for opt
Specialized solvers for opt
Need to specify loss function
All sklearn estimators for classification implement a few common methods for model training, prediction and evaluation.
Model training
fit(X, y[, coef_init, intercept_init, …])
Prediction
predict(X)
decision_function(X)
predicts class label for samples
predicts confidence score for samples.
Evaluation
score(X, y[, sample_weight])
Return the mean accuracy on the given test data and labels.
There a few common miscellaneous methods as follows:
get_params([deep])
gets parameter for this estimator.
converts coefficient matrix to dense array format.
set_params(**params)
densify()
sparsify()
sets the parameters of this estimator.
converts coefficient matrix to sparse format.
Now let's study how to implement different classifiers with sklearn APIs.
Let's start with implementation of least square classification (LSC) with RidgeClassifier API.
Binary classification:
Multiclass classification:
Step 1: Instantiate a classification estimator without passing any arguments to it. This creates a ridge classifier object.
from sklearn.linear_model import RidgeClassifier
ridge_classifier = RidgeClassifier()
Step 2: Call fit method on ridge classifier object with training feature matrix and label vector as arguments.
Note: The model is fitted using X_train and y_train.
# Model training with feature matrix X_train and
# label vector or matrix y_train
ridge_classifier.fit(X_train, y_train)
Set alpha
to float value. The default value is 0.1.
from sklearn.linear_model import RidgeClassifier
ridge_classifier = RidgeClassifier(alpha=0.001)
Using one of the following solvers
svd
cholesky
sparse_cg
lsqr
sag
, saga
uses a Singular Value Decomposition of the feature matrix to compute the Ridge coefficients.
lbfgs
uses scipy.linalg.solve
function to obtain the closed-form solution
uses the conjugate gradient solver of scipy.sparse.linalg.cg
.
uses the dedicated regularized least-squares routine scipy.sparse.linalg.lsqr
and it is fastest.
uses a Stochastic Average Gradient descent iterative procedure
'saga' is unbiased and more flexible version of 'sag'
uses L-BFGS-B algorithm implemented in scipy.optimize.minimize
.
can be used only when coefficients are forced to be positive.
sparse_cg
' solver.When both n_samples
and n_features
are large, use ‘sag
’ or ‘saga
’ solvers.
Note that fast convergence is only guaranteed on features with approximately the same scale.
auto
chooses the solver automatically based on the type of data
ridge_classifier = RidgeClassifier(solver=auto)
if solver == 'auto':
if return_intercept:
# only sag supports fitting intercept directly
solver = "sag"
elif not sparse.issparse(X):
solver = "cholesky"
else:
solver = "sparse_cg"
Default choice for solver is auto
.
If data is already centered, set fit_intercept as false, so that no intercept will be used in calculations.
ridge_classifier = RidgeClassifier(fit_intercept=True)
Default:
Use predict
method to predict class labels for samples
# Predict labels for feature matrix X_test
y_pred = ridge_classifier.predict(X_test)
Other classifiers also use the same predict method.
Step 2: Call predict method on classifier object with feature matrix as an argument.
Step 1: Arrange data for prediction in a feature matrix of shape (#samples, #features) or in sparse matrix format.
RidgeClassifierCV implements RidgeClassifier with built-in cross validation.
Let's implement perceptron classifier with Perceptron API.
It is a simple classification algorithm suitable for large-scale learning.
SGDClassifier
Perceptron uses SGD for training.
Perceptron()
SGDClassifier(loss="perceptron", eta0=1, learning_rate="constant", penalty=None)
Step 1: Instantiate a Perceptron estimator without passing any arguments to it to create a classifier object.
from sklearn.linear_model import Perceptron
perceptron_classifier = Perceptron()
Step 2: Call fit method on perceptron estimator object with training feature matrix and label vector as arguments.
# Model training with feature matrix X_train and
# label vector or matrix y_train
perceptron_classifier.fit(X_train, y_train)
Perceptron can be further customized with the following parameters:
penalty
(default = 'l2')
alpha
(default = 0.0001)
l1_ratio
(default = 0.15)
fit_intercept
(default = True)
max_iter
(default = 1000)
tol
(default = 1e-3)
eta0
(default = 1)
early_stopping
(default = False)
validation_fraction
(default = 0.1)
n_iter_no_change
(default = 5)
Let's implement logistic regression classifier with LogisticRegression API.
Step 1: Instantiate a classifier estimator without passing any arguments to it. This creates a logistic regression object.
from sklearn.linear_model import LogisticRegression
logit_classifier = LogisticRegression()
Step 2: Call fit method on logistic regression classifier object with training feature matrix and label vector as arguments
# Model training with feature matrix X_train and
# label vector or matrix y_train
logit_classifier.fit(X_train, y_train)
Logistic regression uses specific algorithms for solving the optimization problem in training. These algorithms are known as solvers.
The choice of the solver depends on the classification problem set up such as size of the dataset, number of features and labels.
solver
newton-cg
’, ‘sag
’, ‘saga
’ and ‘lbfgs
’ handle multinomial loss.liblinear
’ is limited to one-versus-rest schemes‘newton-cg
’
‘lbfgs
’
‘liblinear
’
‘sag
‘saga
’
logit_classifier = LogisticRegression(solver='lbfgs')
liblinear
', 'lbfgs
' and 'newton-cg
' are robust.By default, logistic regression uses lbfgs solver.
Regularization is applied by default because it improves numerical stability.
penalty
logit_classifier = LogisticRegression(penalty='l2')
By default, it uses L2 penalty.
L2 penalty is supported by all solvers
L1 penalty is supported only by a few solvers.
Solver | Penalty |
---|---|
‘newton-cg ’ |
[‘l2’, ‘none’] |
‘lbfgs ’ |
[‘l2’, ‘none’] |
‘liblinear ’ |
[‘l1’, ‘l2’] |
‘sag ’ |
[‘l2’, ‘none’] |
‘saga ’ |
[‘elasticnet’, ‘l1’, ‘l2’, ‘none’] |
LogisticRegression classifier has a class_weight parameter in its constructor.
What purpose does it serve?
Exercise: Read stack overflow discussion on this parameter.
This parameter is available in classifier estimators in sklearn.
LogisticRegressionCV implements logistic regression with in built cross validation support to find the best values of C and l1_ratio parameters according to the specified scoring attribute.
These classifiers can also be implemented with a generic SGDClassifier API by setting the loss parameter appropriately.
Let's study SGDClassifier API.
We need to set loss parameter appropriately to build train classifier of our interest with SGDClassifier
loss
parameter
'hinge' - (soft-margin) linear Support Vector Machine
'modified_huber' - smoothed hinge loss brings tolerance to outliers as well as probability estimates
'log' - logistic regression
'squared_hinge' - like hinge but is quadratically penalized
'perceptron' - linear loss used by the perceptron algorithm
‘squared_error’, ‘huber’, ‘epsilon_insensitive’, or ‘squared_epsilon_insensitive’ - regression losses
By default SGDClassifier uses hinge loss and hence trains linear support vector machine classifier.
SGDClassifier(loss='log')
LogisticRegression(solver='sgd')
SGDClassifier(loss='hinge')
Linear Support vector machine
Advantages:
Disadvantages:
Step 1: Instantiate a SGDClassifer estimator by setting appropriate loss parameter to define classifier of interest. By default it uses hinge loss, which is used for training linear support vector machine.
from sklearn.linear_model import SGDClassifier
SGD_classifier = SGDClassifier(loss='log')
Step 2: Call fit method on SGD classifier object with training feature matrix and label vector as arguments.
# Model training with feature matrix X_train and
# label vector or matrix y_train
SGD_classifier.fit(X_train, y_train)
Here we have used `log` loss that defines a logistic regression classifier.
penalty
(1 - l1_ratio) * L2 + l1_ratio * L1
SGD_classifier = SGDClassifier(penalty='l2')
(l1_ratio
controls the convex combination of L1 and L2 penalty. default=0.15)
Default:
alpha
SGD_classifier = SGDClassifier(max_iter=100)
Default:
max_iter = 1000
The maximum number of passes over the training data (aka epochs) is an integer that can be set by the max_iter
parameter.
learning_rate
Stopping criteria
warm_start
‘constant’
‘optimal’
‘invscaling’
‘adaptive’
average
‘True’
‘False’
tol
n_iter_no_change
max_iter
early_stopping
validation_fraction
We learnt how to implement the following classifiers with sklearn APIs:
Alternatively we can use SGDClassifier with appropriate loss setting for implementing these classifiers:
Classification estimators implements a few common methods like fit, score, decision_function, and predict.
Let's extend these classifiers to multi-learning (multi-class, multi-label & multi-output) settings.
Multilabel
total #labels = 2
Multiclass multioutput
total #labels > 2
We will refer both these models as multi-label classification models, where # of output labels > 1.
Multiclass, multilabel, multioutput problems are referred to as multi-learning problems.
Multiclass classification
(sklearn.multiclass)
Multilabel classification
(sklearn.multioutput)
problem types
meta-estimators
OneVsOneClassifier
OneVsRestClassifier
OutputCodeClassifier
MultiOutputClassifier
ClassifierChain
Inherently multiclass
Multiclass as OVO
Multiclass as OVR
Multilabel
Inherently multiclass
Multilabel
LogisticRegression (multi_class = 'multinomial')
RidgeClassifier
LogisticRegressionCV (multi_class = 'multinomial')
RidgeClassifierCV
Multiclass as OVR
Perceptron
LogisticRegression (multi_class = 'ovr')
SGDClassifier
LogisticRegressionCV (multi_class = 'ovr')
RidgeClassifier
RidgeClassifierCV
First we will study multiclass APIs in sklearn.
In Iris dataset,
In MNIST digit recognition dataset,
from sklearn.preprocessing import LabelBinarizer
y = np.array(['apple', 'pear', 'apple', 'orange'])
y_dense = LabelBinarizer().fit_transform(y)
[[1 0 0] [0 0 1] [1 0 0] [0 1 0]]
Let's say, you are given labels as part of the training set, how do we check if they are is suitable for multi-class classification?
from sklearn.utils.multiclass import type_of_target
type_of_target(y)
type_of_target can determine different types of multi-learning targets.
target_type
‘multiclass’
‘multiclass-multioutput’
‘unknown’
y
‘multilabel-indicator’
>>> type_of_target([1, 0, 2])
'multiclass'
>>> type_of_target([1.0, 0.0, 3.0])
'multiclass'
>>> type_of_target(['a', 'b', 'c'])
'multiclass'
>>> type_of_target(np.array([[1, 2], [3, 1]]))
'multiclass-multioutput'
multiclass
multiclass-multioutput
multilabel-indicator
type_of_target(np.array([[0, 1], [1, 1]]))
'multilabel-indicator'
>>> type_of_target([[1, 2]])
'multilabel-indicator'
Apart from these, there are three more types, type_of_target can determine targets corresponding to regression and binary classification.
All classifiers in scikit-learn perform multiclass classification out-of-the-box.
OneVsRest classifier also supports multilabel classification. We need to supply labels as indicator matrix of shape \((n, k)\).
from sklearn.multiclass import OneVsRestClassifier
OneVsRestClassifier(LinearSVC(random_state=0)).fit(X, y)
OneVsOne classifier processes subset of data at a time and is useful in cases where the classifier does not scale with the data.
from sklearn.multiclass import OneVsOneClassifier
OneVsOneClassifier(LinearSVC(random_state=0)).fit(X, y)
OneVsRestClassifier
OneVsOneClassifier
Fits one classifier per pair of classes.
At prediction time, the class which received the most votes is selected.
Input Feature Matrix (X)
Classifier #1
Classifier #2
Classifier #k
Class #1
Class #2
Class #k
MultiOutputClassifier
ClassifierChain
So far we learnt how to train classifiers for binary, multi-class and multi-label/output cases.
We will learn how to evaluate these classifiers with different scoring functions and with cross-validation.
We will also study how to set hyper-parameters for classifiers.
Many cross-validation and HPT methods discussed in the regression context are also applicable in classifiers.
There may be issues like class imbalance in classification, which tend to impact the cross validation folds.
The overall class distribution and the ones in folds may be different and this has implications in effective model training.
sklearn.model_selection module provides three stratified APIs to create folds such that the overall class distribution is replicated in individual folds.
sklearn.model_selection module provides the following three stratified APIs to create folds such that the overall class distribution is replicated in individual folds.
Note: Folds obtained via StratifiedShuffleSplit may not be completely different.
cv specifies cross validation iterator
scoring specifies scoring function to use for HPT
cs specifies regularization strengths to experiment with.
refit = True
refit = False
Scores averaged across folds, values corresponding to the best score are selected and final refit with these parameters
the coefs, intercepts and C that correspond to the best scores across folds are averaged.
Now let's look at classification metrics implemented in sklearn.
sklearn.metrics implements a bunch of classification scoring metrics based on true labels and predicted labels as inputs.
accuracy_score
balanced_accuracy_score
top_k_accuracy_score
roc_auc_score
precision_score
recall_score
f1_score
score(actual_labels, predicted_labels)
confusion_matrix
evaluates classification accuracy by computing the confusion matrix with each row corresponding to the true class.from sklearn.metrics import confusion_matrix
confusion_matrix(y_true, y_predicted)
Entry \(i,j\) in a confusion matrix
Example:
number of observations actually in group \(i\), but predicted to be in group \(j\).
Confusion matrix can be displayed with ConfusionMatrixDisplay API in sklearn.metrics.
ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=clf.classes_)
ConfusionMatrixDisplay.from_estimator(clf, X_test, y_test)
ConfusionMatrixDisplay.from_predictions(y_test, y_pred)
The classification_report
function builds a text report showing the main classification metrics.
from sklearn.metrics import classification_report
print(classification_report(y_true, y_predicted))
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_true, y_predicted)
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_scores, pos_label=2)
average
parameter.
calculates the mean of the binary metrics
computes the average of binary metrics in which each class’s score is weighted by its presence in the true data sample.
gives each sample-class pair an equal contribution to the overall metric
calculates the metric over the true and predicted classes for each sample in the evaluation data, and returns their average
returns an array with the score for each class
macro
weighted
micro
samples
None