2014-07-14 22:51:07 +08:00
|
|
|
"""
|
|
|
|
|
====================================================================
|
|
|
|
|
Normal and Shrinkage Linear Discriminant Analysis for classification
|
|
|
|
|
====================================================================
|
|
|
|
|
|
|
|
|
|
Shows how shrinkage improves classification.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import division
|
|
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
from sklearn.datasets import make_blobs
|
2014-07-14 22:51:07 +08:00
|
|
|
from sklearn.lda import LDA
|
|
|
|
|
|
|
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
n_train = 20 # samples for training
|
|
|
|
|
n_test = 200 # samples for testing
|
2014-07-14 22:51:07 +08:00
|
|
|
n_averages = 50 # how often to repeat classification
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_data(n_samples, n_features):
|
2014-10-06 21:18:57 +08:00
|
|
|
"""Generate `n_samples` samples of data with 1 discriminative features
|
2014-07-14 22:51:07 +08:00
|
|
|
and n_`features` non-discriminative features."""
|
2014-10-06 21:18:57 +08:00
|
|
|
X, y = make_blobs(n_samples=n_samples, n_features=1, centers=[[-2], [2]])
|
|
|
|
|
|
|
|
|
|
# add non-discriminative features
|
|
|
|
|
if n_features > 1:
|
|
|
|
|
X = np.hstack([X, np.random.randn(n_samples, n_features - 1)])
|
2014-07-14 22:51:07 +08:00
|
|
|
return X, y
|
|
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
acc_clf1, acc_clf2 = [], []
|
|
|
|
|
m_range = range(1, 100)
|
2014-07-14 22:51:07 +08:00
|
|
|
for m in m_range:
|
2014-10-06 21:18:57 +08:00
|
|
|
score_clf1, score_clf2 = 0, 0
|
2014-07-14 22:51:07 +08:00
|
|
|
for i in range(n_averages):
|
|
|
|
|
X, y = generate_data(n_train, m)
|
|
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
clf1 = LDA(solver='lsqr', alpha='ledoit_wolf').fit(X, y)
|
|
|
|
|
clf2 = LDA(solver='lsqr', alpha=None).fit(X, y)
|
2014-07-14 22:51:07 +08:00
|
|
|
|
|
|
|
|
X, y = generate_data(n_test, m)
|
2014-10-06 21:18:57 +08:00
|
|
|
score_clf1 += clf1.score(X, y)
|
|
|
|
|
score_clf2 += clf2.score(X, y)
|
2014-07-14 22:51:07 +08:00
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
acc_clf1.append(score_clf1 / n_averages)
|
|
|
|
|
acc_clf2.append(score_clf2 / n_averages)
|
2014-07-14 22:51:07 +08:00
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
m_range = np.array(m_range) / n_train
|
2014-07-14 22:51:07 +08:00
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
plt.plot(m_range, acc_clf1, linewidth=2, label="LDA with shrinkage", color='r')
|
|
|
|
|
plt.plot(m_range, acc_clf2, linewidth=2, label="LDA", color='g')
|
2014-07-14 22:51:07 +08:00
|
|
|
|
|
|
|
|
plt.xlabel('n_features / n_samples')
|
|
|
|
|
plt.ylabel('Classification accuracy')
|
|
|
|
|
|
2014-10-06 21:18:57 +08:00
|
|
|
plt.legend(loc=1, prop={'size': 8})
|
|
|
|
|
plt.suptitle('LDA vs shrinkage LDA (1 discriminative feature)')
|
2014-07-14 22:51:07 +08:00
|
|
|
plt.show()
|