Spaces:
Sleeping
Sleeping
File size: 2,264 Bytes
4aefecb bb227d7 4aefecb 0adaeaa bb227d7 74eb73a bb227d7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA, KernelPCA
import gradio as gr
X, y = make_circles(n_samples=1_000, factor=0.3, noise=0.05, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
def fit_plot(n_comp, gamma, alpha):
pca = PCA(n_components=n_comp)
kernel_pca = KernelPCA(
n_components=None, kernel="rbf", gamma=gamma, fit_inverse_transform=True, alpha=alpha
)
X_test_pca = pca.fit(X_train).transform(X_test)
X_test_kernel_pca = kernel_pca.fit(X_train).transform(X_test)
fig1, (orig_data_ax, pca_proj_ax, kernel_pca_proj_ax) = plt.subplots(
ncols=3, figsize=(14, 4)
)
orig_data_ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test)
orig_data_ax.set_ylabel("Feature #1")
orig_data_ax.set_xlabel("Feature #0")
orig_data_ax.set_title("Testing data")
pca_proj_ax.scatter(X_test_pca[:, 0], X_test_pca[:, 1], c=y_test)
pca_proj_ax.set_ylabel("Principal component #1")
pca_proj_ax.set_xlabel("Principal component #0")
pca_proj_ax.set_title("Projection of testing data\n using PCA")
kernel_pca_proj_ax.scatter(X_test_kernel_pca[:, 0], X_test_kernel_pca[:, 1], c=y_test)
kernel_pca_proj_ax.set_ylabel("Principal component #1")
kernel_pca_proj_ax.set_xlabel("Principal component #0")
_ = kernel_pca_proj_ax.set_title("Projection of testing data\n using KernelPCA")
return fig1
with gr.Blocks() as demo:
gr.Markdown("## PCA vs Kernel PCA")
gr.Markdown("Demo is based on the [Kernel PCA](https://scikit-learn.org/stable/auto_examples/decomposition/plot_kernel_pca.html#sphx-glr-auto-examples-decomposition-plot-kernel-pca-py")
with gr.Row():
p1 = gr.Slider(0, 10, label="Number of PCs", value=2, step=1)
p2 = gr.Slider(0, 10, label="Kernel coefficient", value=2, step=1e-3)
p3 = gr.Slider(0, 1, label="Hyperparameter for ridge regression", value=0.1, step=1e-3)
btn = gr.Button(value="Submit")
btn.click(fit_plot, inputs= [p1,p2,p3], outputs= gr.Plot(label='Projecting data with PCA and Kernel PCA') )
demo.launch() |