Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9ebc6fe

Browse files
committed
Merge pull request #5216 from JPFrancoia/master
Creation of the attribute LDA.explained_variance_ratio_, for the eige…
2 parents 7e2453a + 6e7e9d3 commit 9ebc6fe

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

sklearn/lda.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,12 @@ class LDA(BaseEstimator, LinearClassifierMixin, TransformerMixin):
180180
covariance_ : array-like, shape (n_features, n_features)
181181
Covariance matrix (shared by all classes).
182182
183+
explained_variance_ratio_ : array, shape (n_components,)
184+
Percentage of variance explained by each of the selected components.
185+
If ``n_components`` is not set then all components are stored and the
186+
sum of explained variances is equal to 1.0. Only available when eigen
187+
solver is used.
188+
183189
means_ : array-like, shape (n_classes, n_features)
184190
Class means.
185191
@@ -316,6 +322,7 @@ class scatter). This solver supports both classification and
316322
Sb = St - Sw # between scatter
317323

318324
evals, evecs = linalg.eigh(Sb, Sw)
325+
self.explained_variance_ratio_ = np.sort(evals / np.sum(evals))[::-1]
319326
evecs = evecs[:, np.argsort(evals)[::-1]] # sort eigenvectors
320327
# evecs /= np.linalg.norm(evecs, axis=0) # doesn't work with numpy 1.6
321328
evecs /= np.apply_along_axis(np.linalg.norm, 0, evecs)

sklearn/tests/test_lda.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,21 @@ def test_lda_coefs():
8585
assert_array_almost_equal(clf_lda_eigen.coef_, clf_lda_lsqr.coef_, 1)
8686

8787

88+
def test_lda_explained_variance_ratio():
89+
# Test if the sum of the normalized eigen vectors values equals 1
90+
n_features = 2
91+
n_classes = 2
92+
n_samples = 1000
93+
X, y = make_blobs(n_samples=n_samples, n_features=n_features,
94+
centers=n_classes, random_state=11)
95+
96+
clf_lda_eigen = lda.LDA(solver="eigen")
97+
98+
clf_lda_eigen.fit(X, y)
99+
100+
assert_almost_equal(clf_lda_eigen.explained_variance_ratio_.sum(), 1.0, 3)
101+
102+
88103
def test_lda_transform():
89104
# Test LDA transform.
90105
clf = lda.LDA(solver="svd", n_components=1)

0 commit comments

Comments
 (0)