-
Notifications
You must be signed in to change notification settings - Fork 22
Adding Principal Covariates Classification (PCovC) Code #248
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
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
1c3fab9
Adding PCovC code along with base class, modifying PCovR to inherit f…
rvasav26 513241b
Merge pull request #246 from rvasav26/adding-pcovc-new
cajchristian 7f24a7d
Finalizing/touching up docs
cajchristian 0c841dd
Fixing linting
cajchristian f807237
Minor changes to examples, formatting
rvasav26 c651e23
Fixing docstrings to address docs build errors
rvasav26 c0a16aa
Fixing whitespace for linter
rosecers f66aa9d
Adding pcovc to docs
rosecers df8fa2e
Making PCovC accessible via API reference on docs for now.
rvasav26 f56ea06
Implementing Rosy's suggestions to code
rvasav26 78e7051
Adding PCovC to docs examples
rvasav26 12a2c39
Updating CHANGELOG, changing PCovC fit() note
rvasav26 861eb07
Modifying examples, docstrings
rvasav26 234f668
Addressing docs suggestions for inclusion of PCovC
rvasav26 9d8ea28
Adding side-by-side to PCovC comparison example
rvasav26 2c77b00
Touching up pcovc vs pca example
cajchristian 061d7ad
Linting
cajchristian f524ab2
Linting (again)
cajchristian 9505742
Touching up docs
cajchristian 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
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,122 @@ | ||
#!/usr/bin/env python | ||
# coding: utf-8 | ||
|
||
""" | ||
PCovC with the Breast Cancer Dataset | ||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
==================================== | ||
""" | ||
# %% | ||
# | ||
|
||
import matplotlib.pyplot as plt | ||
import numpy as np | ||
from sklearn.datasets import load_breast_cancer | ||
from sklearn.decomposition import PCA | ||
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis | ||
from sklearn.linear_model import LogisticRegressionCV | ||
from sklearn.preprocessing import StandardScaler | ||
|
||
from skmatter.decomposition import PCovC | ||
|
||
|
||
plt.rcParams["image.cmap"] = "tab10" | ||
plt.rcParams["scatter.edgecolors"] = "k" | ||
|
||
random_state = 0 | ||
|
||
# %% | ||
# | ||
# For this, we will use the :func:`sklearn.datasets.load_breast_cancer` dataset from | ||
# ``sklearn``. | ||
|
||
X, y = load_breast_cancer(return_X_y=True) | ||
print(load_breast_cancer().DESCR) | ||
|
||
# %% | ||
# | ||
# Scale Feature Data | ||
# ------------------ | ||
# | ||
# Below, we transform the Breast Cancer feature data to have a mean of zero | ||
# and standard deviation of one, while preserving relative relationships | ||
# between feature values. | ||
|
||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
scaler = StandardScaler() | ||
X_scaled = scaler.fit_transform(X) | ||
|
||
# %% | ||
# | ||
# PCA | ||
# --- | ||
# | ||
# We use Principal Component Analysis to reduce the Breast Cancer feature | ||
# data to two features that retain as much information as possible | ||
# about the original dataset. | ||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
pca = PCA(n_components=2) | ||
|
||
pca.fit(X_scaled, y) | ||
T_pca = pca.transform(X_scaled) | ||
|
||
fig, axis = plt.subplots() | ||
scatter = axis.scatter(T_pca[:, 0], T_pca[:, 1], c=y) | ||
axis.set(xlabel="PC$_1$", ylabel="PC$_2$") | ||
axis.legend( | ||
scatter.legend_elements()[0][::-1], | ||
load_breast_cancer().target_names[::-1], | ||
loc="upper right", | ||
title="Classes", | ||
) | ||
|
||
# %% | ||
# | ||
# LDA | ||
# --- | ||
# | ||
# Here, we use Linear Discriminant Analysis to find a projection | ||
# of the feature data that maximizes separability between | ||
# the benign/malignant classes. | ||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
lda = LinearDiscriminantAnalysis(n_components=1) | ||
lda.fit(X_scaled, y) | ||
|
||
T_lda = lda.transform(X_scaled) | ||
|
||
fig, axis = plt.subplots() | ||
axis.scatter(-T_lda[:], np.zeros(len(T_lda[:])), c=y) | ||
|
||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
# %% | ||
# | ||
# PCA, PCovC, and LDA | ||
# ------------------- | ||
# | ||
# Below, we see a side-by-side comparison of PCA, PCovC (Logistic | ||
# Regression classifier, :math:`\alpha` = 0.5), and LDA maps of the data. | ||
|
||
mixing = 0.5 | ||
n_models = 3 | ||
fig, axes = plt.subplots(1, n_models, figsize=(6 * n_models, 5)) | ||
|
||
models = { | ||
PCA(n_components=2): "PCA", | ||
PCovC( | ||
mixing=mixing, | ||
n_components=2, | ||
random_state=random_state, | ||
classifier=LogisticRegressionCV(), | ||
): "PCovC", | ||
LinearDiscriminantAnalysis(n_components=1): "LDA", | ||
} | ||
|
||
for id in range(0, n_models): | ||
model = list(models)[id] | ||
|
||
model.fit(X_scaled, y) | ||
T = model.transform(X_scaled) | ||
|
||
if isinstance(model, LinearDiscriminantAnalysis): | ||
axes[id].scatter(-T_lda[:], np.zeros(len(T_lda[:])), c=y) | ||
else: | ||
axes[id].scatter(T[:, 0], T[:, 1], c=y) | ||
|
||
axes[id].set_title(models[model]) |
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,178 @@ | ||
#!/usr/bin/env python | ||
# coding: utf-8 | ||
|
||
""" | ||
PCovC with the Iris Dataset | ||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
=========================== | ||
""" | ||
# %% | ||
# | ||
|
||
import matplotlib.pyplot as plt | ||
from matplotlib.colors import LinearSegmentedColormap | ||
from sklearn.datasets import load_iris | ||
from sklearn.decomposition import PCA | ||
from sklearn.inspection import DecisionBoundaryDisplay | ||
from sklearn.linear_model import LogisticRegressionCV, Perceptron, RidgeClassifierCV | ||
from sklearn.preprocessing import StandardScaler | ||
from sklearn.svm import LinearSVC | ||
|
||
from skmatter.decomposition import PCovC | ||
|
||
|
||
plt.rcParams["image.cmap"] = "tab10" | ||
plt.rcParams["scatter.edgecolors"] = "k" | ||
|
||
random_state = 10 | ||
n_components = 2 | ||
|
||
# %% | ||
# | ||
# For this, we will use the :func:`sklearn.datasets.load_iris` dataset from | ||
# ``sklearn``. | ||
|
||
X, y = load_iris(return_X_y=True) | ||
print(load_iris().DESCR) | ||
|
||
# %% | ||
# | ||
# Scale Feature Data | ||
# ------------------ | ||
# | ||
# Below, we transform the Iris feature data to have a mean of zero and | ||
# standard deviation of one, while preserving relative relationships | ||
# between feature values. | ||
|
||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
scaler = StandardScaler() | ||
X_scaled = scaler.fit_transform(X) | ||
|
||
# %% | ||
# | ||
# PCA | ||
# --- | ||
# | ||
# We use Principal Component Analysis to reduce the Iris feature | ||
# data to two features that retain as much information as possible | ||
# about the original dataset. | ||
cajchristian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
pca = PCA(n_components=n_components) | ||
|
||
pca.fit(X_scaled, y) | ||
T_pca = pca.transform(X_scaled) | ||
|
||
fig, axis = plt.subplots() | ||
scatter = axis.scatter(T_pca[:, 0], T_pca[:, 1], c=y) | ||
axis.set(xlabel="PC$_1$", ylabel="PC$_2$") | ||
axis.legend( | ||
scatter.legend_elements()[0], | ||
load_iris().target_names, | ||
loc="lower right", | ||
title="Classes", | ||
) | ||
|
||
# %% | ||
# | ||
# Effect of Mixing Parameter :math:`\alpha` on PCovC Map | ||
# ------------------------------------------------------ | ||
# | ||
# Below, we see how different :math:`\alpha` values for our PCovC model | ||
# result in varying class distinctions between setosa, versicolor, | ||
# and virginica on the PCovC map. | ||
|
||
n_mixing = 5 | ||
mixing_params = [0, 0.25, 0.50, 0.75, 1] | ||
|
||
fig, axes = plt.subplots(1, n_mixing, figsize=(4 * n_mixing, 4), sharey="row") | ||
|
||
for id in range(0, n_mixing): | ||
mixing = mixing_params[id] | ||
|
||
pcovc = PCovC( | ||
mixing=mixing, | ||
n_components=n_components, | ||
random_state=random_state, | ||
classifier=LogisticRegressionCV(), | ||
) | ||
|
||
pcovc.fit(X_scaled, y) | ||
T = pcovc.transform(X_scaled) | ||
|
||
axes[id].set_xticks([]) | ||
axes[id].set_yticks([]) | ||
|
||
axes[id].set_title(r"$\alpha=$" + str(mixing)) | ||
axes[id].set_xlabel("PCov$_1$") | ||
axes[id].scatter(T[:, 0], T[:, 1], c=y) | ||
|
||
axes[0].set_ylabel("PCov$_2$") | ||
|
||
fig.subplots_adjust(wspace=0) | ||
|
||
# %% | ||
# | ||
# Effect of PCovC Classifier on PCovC Map and Decision Boundaries | ||
# --------------------------------------------------------------- | ||
# | ||
# Here, we see how a PCovC model (:math:`\alpha` = 0.5) fitted with | ||
# different classifiers produces varying PCovC maps. In addition, | ||
# we see the varying decision boundaries produced by the | ||
# respective PCovC classifiers. | ||
|
||
soft_dots = ["#ff3333", "#339933", "#3333ff"] | ||
soft_fill = ["#f5bcbc", "#b7d4b7", "#bcbcf5"] | ||
|
||
cmap_dots = LinearSegmentedColormap.from_list("SoftDots", soft_dots) | ||
cmap_fill = LinearSegmentedColormap.from_list("SoftFill", soft_fill) | ||
|
||
mixing = 0.5 | ||
n_models = 4 | ||
fig, axes = plt.subplots(1, n_models, figsize=(4 * n_models, 4)) | ||
|
||
models = { | ||
RidgeClassifierCV(): "Ridge Classification", | ||
LogisticRegressionCV(random_state=random_state): "Logistic Regression", | ||
LinearSVC(random_state=random_state): "Support Vector Classification", | ||
Perceptron(random_state=random_state): "Single-Layer Perceptron", | ||
} | ||
|
||
for id in range(0, n_models): | ||
model = list(models)[id] | ||
|
||
pcovc = PCovC( | ||
mixing=mixing, | ||
n_components=n_components, | ||
random_state=random_state, | ||
classifier=model, | ||
) | ||
|
||
pcovc.fit(X_scaled, y) | ||
T = pcovc.transform(X_scaled) | ||
|
||
graph = axes[id] | ||
graph.set_title(models[model]) | ||
|
||
DecisionBoundaryDisplay.from_estimator( | ||
estimator=pcovc.classifier_, | ||
X=T, | ||
ax=graph, | ||
response_method="predict", | ||
grid_resolution=1000, | ||
cmap=cmap_fill, | ||
) | ||
|
||
scatter = graph.scatter(T[:, 0], T[:, 1], c=y, cmap=cmap_dots) | ||
|
||
graph.set_xlabel("PCov$_1$") | ||
graph.set_xticks([]) | ||
graph.set_yticks([]) | ||
|
||
axes[0].set_ylabel("PCov$_2$") | ||
axes[0].legend( | ||
scatter.legend_elements()[0], | ||
load_iris().target_names, | ||
loc="lower right", | ||
title="Classes", | ||
fontsize=8, | ||
) | ||
|
||
fig.subplots_adjust(wspace=0.04) |
cajchristian marked this conversation as resolved.
Show resolved
Hide resolved
|
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,2 @@ | ||
PCovC | ||
===== |
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.
Uh oh!
There was an error while loading. Please reload this page.