The goal of this tutorial is to introduce you to the scikit libraries for classification. We will also cover the topic of feature normalization, and evaluation.
import numpy as np
import scipy.sparse as sp_sparse
import matplotlib.pyplot as plt
import sklearn as sk
import sklearn.datasets as sk_data
import sklearn.metrics as metrics
from sklearn import preprocessing
import seaborn as sns
%matplotlib inline
Python provides some functionality for normalizing and standardizing the data. Be careful though, some operations work only with dense data.
http://scikit-learn.org/stable/modules/preprocessing.html#preprocessing
Normalize by removing the mean and dividing by the standard deviation. This is done per feature, that is, per column of the dataset.
X = np.array([[ 1., -1., 2.],
[ 2., 0., 1.],
[ 0., 1., -1.]])
print(X.mean(axis = 0))
print(X.std(axis = 0))
X_scaled = preprocessing.scale(X)
print(X_scaled)
print(X_scaled.mean(axis=0))
print(X_scaled.var(axis = 0))
The same can be done with the StandardScaler.
The function fit() computes the parameters for scaling, and transform() applies the scaling
std_scaler = preprocessing.StandardScaler().fit(X)
print(std_scaler.mean_)
print(std_scaler.scale_)
X_std = std_scaler.transform(X)
print(X_std)
The advantage is the we can now apply the transform to new data.
For example, we compute the parameters for the training data and we apply the scaling to the test data.
y = np.array([[2.,3.,1.],
[1.,2.,1.]])
print(std_scaler.transform(y))
The MinMaxScaler subbtracts from each column the minimum and then divides by the max-min.
min_max_scaler = preprocessing.MinMaxScaler()
X_minmax = min_max_scaler.fit_transform(X)
print(X_minmax)
print(min_max_scaler.transform(y))
The MaxAbsScaler divides with the maximum absolute value.
The MaxAbsScaler can work with sparse data, since it does not destroy the data sparseness. For the other datasets, removing the mean (or min) can destroy the sparseness of the data.
Sometimes we may choose to normalize only the non-zero values. This should be done manually.
# works with sparse data
max_abs_scaler = preprocessing.MaxAbsScaler()
X_maxabs = max_abs_scaler.fit_transform(X)
X_maxabs
The normalize function normalizes the rows so that they become unit vectors in some norm that we specify. It can be applied to sparse matrices without destroying the sparsity.
#works with sparse data
X_normalized = preprocessing.normalize(X, norm='l2')
X_normalized
The OneHotEncoder can be used for categorical data to transform them into binary, where for each attribute value we have 0 or 1 depending on whether this value appears in the feature vector. It works with numerical categorical values.
X = [[0,1,2],
[1,2,3],
[0,1,4]]
enc = preprocessing.OneHotEncoder()
enc.fit(X)
enc.transform([[0,2,4],[1,1,2]]).toarray()
We can also apply it selectively to some columns of the data
#works with sparse data
X = [[0, 10, 45100],
[1, 20, 45221],
[0, 20, 45212]]
enc = preprocessing.OneHotEncoder(categorical_features=[2]) #only the third column is categorical
enc.fit(X)
enc.transform([[5,13,45212],[4,12,45221]]).toarray()
Feature selection is about finding the best features for your classifier. This may be important if you do not have enough training data. The idea is to find metrics that either characterize the features by themselves, or with respect to the class we want to predict, or with respect to other features.
http://scikit-learn.org/stable/modules/feature_selection.html
The VarianceThreshold selection drops features whose variance is below some threshold. If we have binary features we can estimate the treshold exactly so as to guarantee a specific ratio of 0's and 1's
from sklearn.feature_selection import VarianceThreshold
X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]]
print(np.array(X))
sel = VarianceThreshold(threshold=(.8 * (1 - .8)))
sel.fit_transform(X)
A more sophisticated feature selection technique uses the chi-square test to determine if a feature and the class label are independent.
https://en.wikipedia.org/wiki/Chi-squared_test
In this case the feature will have high score and low p-value. The features with the lowest values are rejected.
The chi-square test is usually applied on categorical data.
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape)
print(X[1:10,:],y[1:10])
sel = SelectKBest(chi2, k=2)
X_new = sel.fit_transform(X, y)
print(X_new[1:10])
print(sel.scores_)
c,p = sk.feature_selection.chi2(X, y)
print(c)
print(p)
http://scikit-learn.org/stable/supervised_learning.html#supervised-learning
Python has classes and objects that implement the different classification techniques that we described in class.
Regardless of the choice of classifier, each classifier has two methods:
The method fit() takes the training data and labels and trains the model
The method predict() takes as input the test data and applies the model.
Here we load the data, randomly shuffle it, and select a part of the data for training and a part for testing
from sklearn.datasets import load_iris
import sklearn.utils as utils
iris = load_iris()
print(iris.data[:5,:])
print(iris.target)
print(iris.target_names)
X, y = utils.shuffle(iris.data, iris.target, random_state=1)
print(X.shape)
print(y.shape)
print(y)
train_set_size = 100
X_train = X[:train_set_size] # selects first 100 rows (examples) for train set
y_train = y[:train_set_size]
X_test = X[train_set_size:] # selects from row 100 until the last one for test set
y_test = y[train_set_size:]
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)
from sklearn import tree
dtree = tree.DecisionTreeClassifier()
dtree = dtree.fit(X_train, y_train)
print(dtree.score(X_test,y_test))
y_pred = dtree.predict(X_test)
y_prob = dtree.predict_proba(X_test)
print(y_pred[:10])
print(y_prob[:10])
print(metrics.accuracy_score(y_test,y_pred))
print(metrics.confusion_matrix(y_test,y_pred))
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train,y_train)
print(knn.score(X_test,y_test))
y_pred = knn.predict(X_test)
print(metrics.confusion_matrix(y_test,y_pred))
from sklearn import svm
#svm_clf = svm.LinearSVC()
#svm_clf = svm.SVC(kernel = 'poly')
svm_clf = svm.SVC()
svm_clf.fit(X_train,y_train)
print(svm_clf.score(X_test,y_test))
y_pred = svm_clf.predict(X_test)
print(metrics.confusion_matrix(y_test,y_pred))
import sklearn.linear_model as linear_model
lr_clf = linear_model.LogisticRegression()
lr_clf.fit(X_train, y_train)
print(lr_clf.score(X_test,y_test))
y_pred = lr_clf.predict(X_test)
print(metrics.confusion_matrix(y_test,y_pred))
probs = lr_clf.predict_proba(X_test)
print (probs)
print (probs.argmax(axis = 1))
print (probs.max(axis = 1))
p,r,f,s = metrics.precision_recall_fscore_support(y_test,y_pred)
print(p)
print(r)
print(f)
report = metrics.classification_report(y_test,y_pred)
print(report)
y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])
precision, recall, thresholds = metrics.precision_recall_curve(y_true,y_scores)
plt.scatter(recall,precision)
print(recall)
print(precision)
print(thresholds)
fpr, tpr, ths = metrics.roc_curve(y_true,y_scores)
print(metrics.roc_auc_score(y_true,y_scores))
import sklearn.cross_validation as cross_validation
scores = cross_validation.cross_val_score(#lr_clf,
#svm_clf,
#knn,
dtree,
X,
y,
scoring='accuracy',
cv=5)
print (scores)
print (scores.mean())