-
-
Notifications
You must be signed in to change notification settings - Fork 26.2k
[MRG+2] Incremental PCA #3285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
[MRG+2] Incremental PCA #3285
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
""" | ||
======================== | ||
IncrementalPCA benchmark | ||
======================== | ||
|
||
Benchmarks for IncrementalPCA | ||
|
||
""" | ||
|
||
import numpy as np | ||
import gc | ||
from time import time | ||
from collections import defaultdict | ||
import matplotlib.pyplot as plt | ||
from sklearn.datasets import fetch_lfw_people | ||
from sklearn.decomposition import IncrementalPCA, RandomizedPCA, PCA | ||
|
||
|
||
def plot_results(X, y, label): | ||
plt.plot(X, y, label=label, marker='o') | ||
|
||
|
||
def benchmark(estimator, data): | ||
gc.collect() | ||
print("Benching %s" % estimator) | ||
t0 = time() | ||
estimator.fit(data) | ||
training_time = time() - t0 | ||
data_t = estimator.transform(data) | ||
data_r = estimator.inverse_transform(data_t) | ||
reconstruction_error = np.mean(np.abs(data - data_r)) | ||
return {'time': training_time, 'error': reconstruction_error} | ||
|
||
|
||
def plot_feature_times(all_times, batch_size, all_components, data): | ||
plt.figure() | ||
plot_results(all_components, all_times['pca'], label="PCA") | ||
plot_results(all_components, all_times['ipca'], | ||
label="IncrementalPCA, bsize=%i" % batch_size) | ||
plot_results(all_components, all_times['rpca'], label="RandomizedPCA") | ||
plt.legend(loc="upper left") | ||
plt.suptitle("Algorithm runtime vs. n_components\n \ | ||
LFW, size %i x %i" % data.shape) | ||
plt.xlabel("Number of components (out of max %i)" % data.shape[1]) | ||
plt.ylabel("Time (seconds)") | ||
|
||
|
||
def plot_feature_errors(all_errors, batch_size, all_components, data): | ||
plt.figure() | ||
plot_results(all_components, all_errors['pca'], label="PCA") | ||
plot_results(all_components, all_errors['ipca'], | ||
label="IncrementalPCA, bsize=%i" % batch_size) | ||
plot_results(all_components, all_errors['rpca'], label="RandomizedPCA") | ||
plt.legend(loc="lower left") | ||
plt.suptitle("Algorithm error vs. n_components\n" | ||
"LFW, size %i x %i" % data.shape) | ||
plt.xlabel("Number of components (out of max %i)" % data.shape[1]) | ||
plt.ylabel("Mean absolute error") | ||
|
||
|
||
def plot_batch_times(all_times, n_features, all_batch_sizes, data): | ||
plt.figure() | ||
plot_results(all_batch_sizes, all_times['pca'], label="PCA") | ||
plot_results(all_batch_sizes, all_times['rpca'], label="RandomizedPCA") | ||
plot_results(all_batch_sizes, all_times['ipca'], label="IncrementalPCA") | ||
plt.legend(loc="lower left") | ||
plt.suptitle("Algorithm runtime vs. batch_size for n_components %i\n \ | ||
LFW, size %i x %i" % ( | ||
n_features, data.shape[0], data.shape[1])) | ||
plt.xlabel("Batch size") | ||
plt.ylabel("Time (seconds)") | ||
|
||
|
||
def plot_batch_errors(all_errors, n_features, all_batch_sizes, data): | ||
plt.figure() | ||
plot_results(all_batch_sizes, all_errors['pca'], label="PCA") | ||
plot_results(all_batch_sizes, all_errors['ipca'], label="IncrementalPCA") | ||
plt.legend(loc="lower left") | ||
plt.suptitle("Algorithm error vs. batch_size for n_components %i\n \ | ||
LFW, size %i x %i" % ( | ||
n_features, data.shape[0], data.shape[1])) | ||
plt.xlabel("Batch size") | ||
plt.ylabel("Mean absolute error") | ||
|
||
|
||
def fixed_batch_size_comparison(data): | ||
all_features = [i.astype(int) for i in np.linspace(data.shape[1] // 10, | ||
data.shape[1], num=5)] | ||
batch_size = 1000 | ||
# Compare runtimes and error for fixed batch size | ||
all_times = defaultdict(list) | ||
all_errors = defaultdict(list) | ||
for n_components in all_features: | ||
pca = PCA(n_components=n_components) | ||
rpca = RandomizedPCA(n_components=n_components, random_state=1999) | ||
ipca = IncrementalPCA(n_components=n_components, batch_size=batch_size) | ||
results_dict = {k: benchmark(est, data) for k, est in [('pca', pca), | ||
('ipca', ipca), | ||
('rpca', rpca)]} | ||
|
||
for k in sorted(results_dict.keys()): | ||
all_times[k].append(results_dict[k]['time']) | ||
all_errors[k].append(results_dict[k]['error']) | ||
|
||
plot_feature_times(all_times, batch_size, all_features, data) | ||
plot_feature_errors(all_errors, batch_size, all_features, data) | ||
|
||
|
||
def variable_batch_size_comparison(data): | ||
batch_sizes = [i.astype(int) for i in np.linspace(data.shape[0] // 10, | ||
data.shape[0], num=10)] | ||
|
||
for n_components in [i.astype(int) for i in | ||
np.linspace(data.shape[1] // 10, | ||
data.shape[1], num=4)]: | ||
all_times = defaultdict(list) | ||
all_errors = defaultdict(list) | ||
pca = PCA(n_components=n_components) | ||
rpca = RandomizedPCA(n_components=n_components, random_state=1999) | ||
results_dict = {k: benchmark(est, data) for k, est in [('pca', pca), | ||
('rpca', rpca)]} | ||
|
||
# Create flat baselines to compare the variation over batch size | ||
all_times['pca'].extend([results_dict['pca']['time']] * | ||
len(batch_sizes)) | ||
all_errors['pca'].extend([results_dict['pca']['error']] * | ||
len(batch_sizes)) | ||
all_times['rpca'].extend([results_dict['rpca']['time']] * | ||
len(batch_sizes)) | ||
all_errors['rpca'].extend([results_dict['rpca']['error']] * | ||
len(batch_sizes)) | ||
for batch_size in batch_sizes: | ||
ipca = IncrementalPCA(n_components=n_components, | ||
batch_size=batch_size) | ||
results_dict = {k: benchmark(est, data) for k, est in [('ipca', | ||
ipca)]} | ||
all_times['ipca'].append(results_dict['ipca']['time']) | ||
all_errors['ipca'].append(results_dict['ipca']['error']) | ||
|
||
plot_batch_times(all_times, n_components, batch_sizes, data) | ||
# RandomizedPCA error is always worse (approx 100x) than other PCA | ||
# tests | ||
plot_batch_errors(all_errors, n_components, batch_sizes, data) | ||
|
||
faces = fetch_lfw_people(resize=.2, min_faces_per_person=5) | ||
# limit dataset to 5000 people (don't care who they are!) | ||
X = faces.data[:5000] | ||
n_samples, h, w = faces.images.shape | ||
n_features = X.shape[1] | ||
|
||
X -= X.mean(axis=0) | ||
X /= X.std(axis=0) | ||
|
||
fixed_batch_size_comparison(X) | ||
variable_batch_size_comparison(X) | ||
plt.show() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
""" | ||
|
||
=============== | ||
Incremental PCA | ||
=============== | ||
|
||
Incremental principal component analysis (IPCA) is typically used as a | ||
replacement for principal component analysis (PCA) when the dataset to be | ||
decomposed is too large to fit in memory. IPCA builds a low-rank approximation | ||
for the input data using an amount of memory which is independent of the | ||
number of input data samples. It is still dependent on the input data features, | ||
but changing the batch size allows for control of memory usage. | ||
|
||
This example serves as a visual check that IPCA is able to find a similar | ||
projection of the data to PCA (to a sign flip), while only processing a | ||
few samples at a time. This can be considered a "toy example", as IPCA is | ||
intended for large datasets which do not fit in main memory, requiring | ||
incremental approaches. | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would add that the purpose of this example is to only serve as a visual sanity check as IPCA is only interesting on datasets with large number of samples. |
||
""" | ||
print(__doc__) | ||
|
||
# Authors: Kyle Kastner | ||
# License: BSD 3 clause | ||
|
||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
|
||
from sklearn.datasets import load_iris | ||
from sklearn.decomposition import PCA, IncrementalPCA | ||
|
||
iris = load_iris() | ||
X = iris.data | ||
y = iris.target | ||
|
||
n_components = 2 | ||
ipca = IncrementalPCA(n_components=n_components, batch_size=10) | ||
X_ipca = ipca.fit_transform(X) | ||
|
||
pca = PCA(n_components=n_components) | ||
X_pca = pca.fit_transform(X) | ||
|
||
for X_transformed, title in [(X_ipca, "Incremental PCA"), (X_pca, "PCA")]: | ||
plt.figure(figsize=(8, 8)) | ||
for c, i, target_name in zip("rgb", [0, 1, 2], iris.target_names): | ||
plt.scatter(X_transformed[y == i, 0], X_transformed[y == i, 1], | ||
c=c, label=target_name) | ||
|
||
if "Incremental" in title: | ||
err = np.abs(np.abs(X_pca) - np.abs(X_ipca)).mean() | ||
plt.title(title + " of iris dataset\nMean absolute unsigned error " | ||
"%.6f" % err) | ||
else: | ||
plt.title(title + " of iris dataset") | ||
plt.legend(loc="best") | ||
plt.axis([-4, 4, -1.5, 1.5]) | ||
|
||
plt.show() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please reorder imports (numpy first and sklearn last)