Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test
In questa pagina 3
Code for Model Selection and Validation - Hold-Out, k-Fold and Statistical TestsTo decide which of two models is better, fix their hyper-parameters, train each on a training set (this fits the parameters, the vector w or theta) and measure a performance score such as F1 on a separate test set; one split is too fragile, so the hold-out is repeated K times (or K-fold cross-validation is used) and the paired scores of the two models are compared with a statistical test. The null hypothesis H0 is that the two models perform equally; the significance level alpha is fixed before the experiment, and the p-value is the probability of observing the obtained differences under H0. Parametric test: t-test; non-parametric: Wilcoxon.Model Selection and Validation - Hold-Out, k-Fold and Statistical Tests → with the metrics of Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →. Algorithms behind the models: Halfspaces and the Perceptron AlgorithmA perceptron computes h(x) = sign(w^T x) where x includes a constant coordinate x0 = 1 that absorbs the threshold into the bias weight w0; its decision boundary is the hyperplane w^T x = 0 (a line in the plane, x2 = -(w1/w2) x1 - w0/w2). The Perceptron Learning Algorithm scans the data and, on every misclassified point, replaces w by w + y x. A single perceptron cannot separate the exclusive-or pattern; two perceptrons feeding a third give a multilayer network.Halfspaces and the Perceptron Algorithm → (Perceptron), Logistic RegressionLogistic regression models the probability p of the positive class: the logit (log of the odds p/(1-p)) is assumed linear in the input, logit(p) = w^T x = z. Inverting it gives p = 1/(1 + e^(-z)), the logistic sigmoid; an object goes to class 1 when the sigmoid exceeds 0.5, i.e. when z > 0. The parameters are learned by maximising the Bernoulli log-likelihood, equivalently minimising the cost J = -y log(yhat) - (1 - y) log(1 - yhat), by gradient descent with gradient (1/m) X^T (h(x) - y).Logistic Regression → (LogisticRegression), Nearest NeighbourK-nearest neighbours (KNN) has an almost empty training phase (the data are just stored) and does all the work at test time: given a point, compute its distance from all training points, sort the distances, keep the K shortest and predict the (weighted) majority class among them. The course source has one handwritten page on it; the notebooks use it as one of six scikit-learn classifiers, and the model-comparison example contrasts KNN with K=1 and K=5.Nearest Neighbour → (KNeighborsClassifier). The decision tree, support vector classifier and random forest are used as black boxes: the course source has no lecture material on them.
Note on the source. In the copies of the notebooks available for these notes the indentation of the code is flattened and the outputs are missing; the code is reproduced with the indentation restored by hand and no result is quoted.
1. First example: types of rice (two classes)
Statement. Classification of two types of rice (the Cammeo and Osmancik data set of the UCI repository, id 545). First install the package ucimlrepo (pip install ucimlrepo); the example uses the "Import example" code of the repository.
#!pip install ucimlrepo
from ucimlrepo import fetch_ucirepo
# fetch dataset
rice_cammeo_and_osmancik = fetch_ucirepo(id=545)
# data (as pandas dataframes)
X = rice_cammeo_and_osmancik.data.features
y = rice_cammeo_and_osmancik.data.targets
# metadata
print(rice_cammeo_and_osmancik.metadata)
# variable information
print(rice_cammeo_and_osmancik.variables)Check the data set:
X.head()
yAlternative: a local copy. If the data set is downloaded, it is in the ARFF format, which read_csv cannot read; install scipy and use:
import pandas as pd
from scipy.io import arff
# code
arff_file = arff.loadarff('./rice+cammeo+and+osmancik/Rice_Cammeo_Osmancik.arff')
df = pd.DataFrame(arff_file[0])
df.head()The last column is a byte-encoded string; decode it with UTF-8, then build the data set and the labels:
df['Class'] = df['Class'].str.decode('utf-8')
X = df.loc[:, df.columns[:-1]]
y = df.ClassEncoding the labels. Models need numbers:
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)
print(y[:10])
print(le.inverse_transform(y[:10]))fit_transform maps the class names to integers; inverse_transform goes back to the names.
Simple hold-out (training and test only)
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Perceptron
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import seaborn as snsStep 1: prepare the data set (the notebook asks in a comment: "do we need to set the random state?").
# train_test proportion
test_proportion = 0.2
x_train, x_test, y_train, y_test = train_test_split(X,
y,
test_size = test_proportion,
shuffle = True)Step 2: create the models.
lr = LogisticRegression()
per = Perceptron()
knn = KNeighborsClassifier()
dt = DecisionTreeClassifier()
svc = SVC()
rf = RandomForestClassifier()Step 3: train the models.
lr.fit(x_train, y_train)
per.fit(x_train, y_train)
knn.fit(x_train, y_train)
dt.fit(x_train, y_train)
svc.fit(x_train, y_train)
rf.fit(x_train, y_train)
print("")Step 4: test the models.
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_scorelr_pred = lr.predict(x_test)
per_pred = per.predict(x_test)
knn_pred = knn.predict(x_test)
dt_pred = dt.predict(x_test)
svc_pred = svc.predict(x_test)
rf_pred = rf.predict(x_test)lr_f1 = f1_score(lr_pred, y_test)
per_f1 = f1_score(per_pred, y_test)
knn_f1 = f1_score(knn_pred, y_test)
dt_f1 = f1_score(dt_pred, y_test)
svc_f1 = f1_score(svc_pred, y_test)
rf_f1 = f1_score(rf_pred, y_test)
f1_results = [lr_f1, per_f1, knn_f1, dt_f1, svc_f1, rf_f1]
f1_resultsThe notebook passes the predictions first and the true labels second, while the scikit-learn convention is (true labels, predictions); for the score the result is the same, because exchanging the two arguments exchanges precision and recall and is symmetric in them. The last example of the course uses the conventional order.
Plots of the six scores (several versions in the notebook, the last one with labelled ticks):
import matplotlib.pyplot as plt
import numpy as np
plt.scatter(range(5), f1_results, c = np.random.rand(5), alpha=0.5)import matplotlib.pyplot as plt
ticks = [1, 2, 3, 4, 5, 6]
labels = ["lr", "per", "knn", "dt", "svc", "rf"]
fig = plt.figure() #Step 2
ax = fig.add_subplot(111) #Step 3
ax.scatter(ticks,
f1_results,
color= 'darkgreen',
marker= '^' )
ax.set_ylim(0, 1)
ax.set_xlim(0, 6.5)
ax.set_xticks(ticks, labels)
plt.savefig('foo2.png' ) #Step 5
plt.show() #Step 6A single hold-out gives a single number per model: to see whether differences are real we need several scores per model.
"Simple" k-fold cross-validation (no separate test set)
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_validate
num_folds = 10
k_fold = KFold(n_splits = num_folds, shuffle = True, random_state=1)
# do we need random seed?cv_lr = cross_validate(estimator = lr,
X = X,
y = y,
cv = k_fold,
scoring = ('f1_macro'),
return_train_score = False)
cv_per = cross_validate(estimator = per, X = X, y = y, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_knn = cross_validate(estimator = knn, X = X, y = y, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_dt = cross_validate(estimator = dt, X = X, y = y, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_svc = cross_validate(estimator = svc, X = X, y = y, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_rf = cross_validate(estimator = rf, X = X, y = y, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)cross_validate trains and tests the model on each of the 10 folds (all models use the same k_fold object, hence the same splits: the scores are paired); scoring = 'f1_macro' is the computed per class and then averaged; the per-fold test scores are in cv_*['test_score']. Collect them in a table:
import pandas as pd
f1_perf = pd.DataFrame({
'Model': ['lr'] * num_folds + ['per'] * num_folds + ['knn'] * num_folds + ['dt'] * num_folds + ['svc'] * num_folds + ['rf'] * num_folds,
'Performance': list(cv_lr['test_score']) + list(cv_per['test_score']) + list(cv_knn['test_score']) + list(cv_dt['test_score']) + list(cv_svc['test_score']) + list(cv_rf['test_score'])
})Box plot with the single fold scores on top:
fig = plt.figure() #Step 2
ax = fig.add_subplot(111) #Step 3
sns.boxplot(data = f1_perf, x='Model', y='Performance')
sns.stripplot(data = f1_perf, x='Model', y='Performance', color='darkred', size=4, alpha=0.7)
ax.set(ylim = (0.8, 1.0))
plt.show()Wilcoxon signed-rank test on two models (here decision tree against SVC):
from scipy.stats import wilcoxon
model_1 = "dt"
model_2 = "svc"
# perform Wilcoxon signed-rank test
wilcoxon_stat, wilcoxon_pval = wilcoxon(f1_perf[f1_perf['Model'] == model_1]['Performance'],
f1_perf[f1_perf['Model'] == model_2]['Performance'],
alternative = 'two-sided',
zero_method = 'wilcox',
correction = True,
mode = 'approx')# display test results
print("Wilcoxon Signed-Rank Test:")
print(f"p-value: {wilcoxon_pval}")The two arguments are the paired lists of fold scores of the two models; alternative = 'two-sided' tests "different" in either direction (the two tails and of the lecture); the p-value is compared with the chosen in advance.
2. Second example: letter recognition (many classes)
The text of this notebook repeats the title "types of rice" by mistake; the data set is Letter Recognition (UCI id 59), a multi-class problem. The loading cell is the same with fetch_ucirepo(id=59) and letter_recognition:
from ucimlrepo import fetch_ucirepo
# fetch dataset
letter_recognition = fetch_ucirepo(id=59)
# data (as pandas dataframes)
X = letter_recognition.data.features
y = letter_recognition.data.targets
# metadata
print(letter_recognition.metadata)
# variable information
print(letter_recognition.variables)Then X.head(), y, the LabelEncoder cells and the imports of the models as above. Differences with the first example:
Hold-out with stratification and macro F1.
# train_test proportion
test_proportion = 0.2
x_train, x_test, y_train, y_test = train_test_split(X,
y,
test_size = test_proportion,
stratify = y,
shuffle = True)stratify = y keeps the proportion of each class equal in training and test sets. With many classes the score is averaged over the classes:
lr_f1 = f1_score(lr_pred, y_test, average="macro")
per_f1 = f1_score(per_pred, y_test, average="macro")
knn_f1 = f1_score(knn_pred, y_test, average="macro")
dt_f1 = f1_score(dt_pred, y_test, average="macro")
svc_f1 = f1_score(svc_pred, y_test, average="macro")
rf_f1 = f1_score(rf_pred, y_test, average="macro")
f1_results = [lr_f1, per_f1, knn_f1, dt_f1, svc_f1, rf_f1]Cross-validation on the whole data, 3 folds. The same cells as before with num_folds = 3 and random_state=1; the box plot without the ylim line; Wilcoxon for dt against svc.
K-fold cross-validation with a test set. First the test set is set aside (with a fixed random state), and the cross-validation uses only the training part:
# train_test proportion
test_proportion = 0.2
x_train, x_test, y_train, y_test = train_test_split(X,
y,
test_size = test_proportion,
stratify = y,
shuffle = True,
random_state = 11
)#train validation proportion
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_validate
num_folds = 3
k_fold = KFold(n_splits = num_folds,
shuffle = True,
random_state=1)
# do we need random seed?(StratifiedKFold is imported but KFold is used.) Try a different solver for logistic regression, then run cross_validate on x_train, y_train:
lr = LogisticRegression(max_iter=100, solver="liblinear")cv_lr = cross_validate(estimator = lr,
X = x_train,
y = y_train,
cv = k_fold,
scoring = ('f1_macro'),
return_train_score = False)cv_per = cross_validate(estimator = per, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_knn = cross_validate(estimator = knn, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_dt = cross_validate(estimator = dt, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_svc = cross_validate(estimator = svc, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_rf = cross_validate(estimator = rf, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)The table f1_perf, the box plot and the Wilcoxon test are repeated, now for rf against knn (model_1 = "rf", model_2 = "knn", same arguments as before).
More folds on the best models. "Let's try to increase the number of folds on the best models":
#train validation proportion
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_validate
num_folds = 5
k_fold = KFold(n_splits = num_folds,
shuffle = True,
random_state=1)cv_knn = cross_validate(estimator = knn, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_svc = cross_validate(estimator = svc, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)
cv_rf = cross_validate(estimator = rf, X = x_train, y = y_train, cv = k_fold, scoring = ('f1_macro'), return_train_score = False)f1_perf = pd.DataFrame({
'Model': ['knn'] * num_folds + ['svc'] * num_folds + ['rf'] * num_folds,
'Performance': list(cv_knn['test_score']) + list(cv_svc['test_score']) + list(cv_rf['test_score'])
})Box plot as before, then Wilcoxon for rf against svc with correction = False and mode = 'auto':
from scipy.stats import wilcoxon
model_1 = "rf"
model_2 = "svc"
# perform Wilcoxon signed-rank test
wilcoxon_stat, wilcoxon_pval = wilcoxon(f1_perf[f1_perf['Model'] == model_1]['Performance'],
f1_perf[f1_perf['Model'] == model_2]['Performance'],
alternative = 'two-sided',
zero_method = 'wilcox',
correction = False,
mode = 'auto')A markdown cell says "Stop here and decide the alpha value" (before looking at the p-value, as in the lecture), and then the p-value is printed and the two score lists are inspected:
# display test results
print("Wilcoxon Signed-Rank Test:")
print(f"p-value: {wilcoxon_pval}")f1_perf[f1_perf['Model'] == model_1]['Performance']
f1_perf[f1_perf['Model'] == model_2]['Performance']A one-pair example is also tried:
l1 = [0.95]
l2 = [0.91]
wilcoxon(x = l1, y = l2)(a single pair of scores; the notebook gives no comment on it.)
Decide for the best model and test it. Cell of the notebook: "Let's say that the best model is Random Forest, but since our computational power is limited it allows us to run experiments with knn only." Then the chosen model is trained on the whole training set and tested once on the test set:
knn.fit(x_train, y_train)
test_knn = knn.predict(x_test)
f1_score(y_test, test_knn, average="macro")
np.max(cv_knn["test_score"])The last line compares the test score with the best fold score. The notebook closes with the question "Do you really want to try if Random Forest performs better if trained on the whole dataset?":
rf.fit(x_train, y_train)
test_rf = rf.predict(x_test)
f1_score(y_test, test_rf, average="macro")3. Wilcoxon test on random samples
A short notebook to see the test at work on data where the null hypothesis is true: two samples drawn from the same normal distribution.
import numpy as np
from scipy.stats import wilcoxon
import matplotlib.pyplot as plt
N = 10
data1 = np.random.normal(loc = 0.0, scale = 1.0, size = N)
data2 = np.random.normal(loc = 0.0, scale = 1.0, size = N)
plt.scatter(data1, np.zeros(N), c = 'r') # plot first line
plt.scatter(data2, np.zeros(N) + 1, c = 'b') # plot first line
datax = [data1, data2]
datay = [np.zeros(N), (np.zeros(N) + 1)]
_ = plt.plot(datax, datay, 'yo', linestyle="--", alpha = 0.2)
stat, p = wilcoxon(data1, data2, mode="approx")
print('p-value=%.3f' % (p))
if p > 0.05:
print('Probably the same distribution')
else:
print('Probably different distributions')The two samples are drawn in two rows and the dashed lines join the pairs; the rule is means probably the same distribution. Then the experiment is repeated 100 times with 20 points:
N = 20
for i in range(100):
data1 = np.random.normal(loc = 0.0, scale = 1.0, size = N)
data2 = np.random.normal(loc = 0.0, scale = 1.0, size = N)
stat, p = wilcoxon(data1, data2, mode="approx")
if p > 0.05:
#print('Probably the same distribution')
continue
else:
print('Probably different distributions ' + str(i))
print('p-value = ' + str(p))
#print(stat, p)
continue
plt.scatter(data1, np.zeros(N), c = 'r') # plot first line
plt.scatter(data2, np.zeros(N) + 1, c = 'b') # plot first line
datax = [data1, data2] #, np.concatenate(np.zeros[10], np.zeros[10] + 1)]
datay = [np.zeros(N), (np.zeros(N) + 1)]
_ = plt.plot(datax, datay, 'yo', linestyle="--", alpha = 0.2)The loop prints the repetitions in which the test "finds" a difference although both samples come from the same distribution; reading with the tail areas of the lecture, such false alarms are expected in a small fraction of the repetitions, about the fraction (my reading of the purpose of the cell; the notebook does not state it). Finally the differences of the pairs are plotted, the quantity on which the test works:
plt.scatter(data1 - data2, np.zeros(N))
plt.xlim(-5, 5)
_ = plt.hist(data1 - data2, )
plt.xlim(xmin=-5, xmax = 5)Versione ripasso
- Six models:
LogisticRegression(), Perceptron(), KNeighborsClassifier(), DecisionTreeClassifier(), SVC(), RandomForestClassifier();fit(x_train, y_train),predict(x_test). - Labels:
LabelEncoder().fit_transform(y),inverse_transform. ARFF files:scipy.io.arff.loadarff; UCI data viafetch_ucirepo(id=...)(545 rice, 59 letters). - Hold-out:
train_test_split(X, y, test_size=0.2, shuffle=True); multi-class:stratify=yandf1_score(y_true, y_pred, average="macro"). - k-fold:
KFold(n_splits=k, shuffle=True, random_state=1);cross_validate(estimator=m, X=X, y=y, cv=k_fold, scoring='f1_macro')['test_score']; samek_foldfor all models = paired scores. - Table
f1_perf(columnsModel,Performance);sns.boxplot+sns.stripplot. - Wilcoxon:
wilcoxon(scores_1, scores_2, alternative='two-sided', zero_method='wilcox', correction=True, mode='approx')returns statistic and p-value; decide first; : no evidence of difference. - Final procedure: test set aside; cross-validation on the training set (3, then 5 folds); Wilcoxon on the best models;
fitthe chosen model on the whole training set; one test on the test set. - Random-sample notebook: two samples from the same normal; about of 100 repetitions flagged at (false alarms).
- Typical errors: using the test set for selection; different folds for different models; forgetting
average="macro"on multi-class labels.