# Code source: Gaël Varoquaux # License: BSD 3 clause # This code is a MOD with Gradio Demo import numpy as np import matplotlib.pyplot as plt import matplotlib from sklearn import decomposition from sklearn import datasets # unused but required import for doing 3d projections with matplotlib < 3.2 import mpl_toolkits.mplot3d # noqa: F401 matplotlib.use('agg') import gradio as gr np.random.seed(5) ## PCA def PCA_Pred(x1, x2, x3, x4): #Load Data from iris dataset: iris = datasets.load_iris() X = iris.data y = iris.target fig, ax = plt.subplots(1, subplot_kw={'projection': '3d', 'elev': 48, 'azim': 134}) ax.set_position([0, 0, 0.95, 1]) plt.cla() #Create the model with 3 principal components: pca = decomposition.PCA(n_components=3) #Fit model and transform (decrease dimensions) iris dataset: pca.fit(X) X = pca.transform(X) #Set labels to data clusters for name, label in [("Setosa", 0), ("Versicolour", 1), ("Virginica", 2)]: ax.text3D( X[y == label, 0].mean(), X[y == label, 1].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment="center", bbox=dict(alpha=0.5, edgecolor="w", facecolor="w"), ) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(float) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.nipy_spectral, edgecolor="k") user_iris_data = np.array([[x1, x2, x3, x4]], ndmin=2) #Perform reduction to user data pc_output = pca.transform(user_iris_data) ax.scatter(pc_output[0, 0], pc_output[0, 1], pc_output[0, 2], c='r', marker='*') ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) ax.zaxis.set_ticklabels([]) return [pc_output, fig] title = "🌺 PCA example with Iris Data-set" with gr.Blocks(title=title) as demo: gr.Markdown(f"## {title}") gr.Markdown( """ ## The following app is a demo for PCA decomposition. It takes 4 dimensions as input, in reference \ to the Iris flower image (left), and returns the transformed first 3 principal components (feature \ reduction) taken from a pre-trained model with Iris dataset (Right). """) with gr.Row(): with gr.Column(): html1 = ( "
" "image One" + "
" ) gr.HTML(html1) inp1 = gr.Slider(0, 5, value=1, step=0.1, label="Sepal Length (cm)") inp2 = gr.Slider(0, 5, value=1, step=0.1, label="Sepal Width (cm)") inp3 = gr.Slider(0, 5, value=1, step=0.1, label="Petal Length (cm)") inp4 = gr.Slider(0, 5, value=1, step=0.1, label="Petal Width (cm)") output = gr.Textbox(label="PCA Axes") with gr.Column(): html2 = ( "
" "image two" + "
" ) gr.HTML(html2) plot = gr.Plot(label="PCA 3D Space") Reduction = gr.Button("PCA Transform") Reduction.click(fn=PCA_Pred, inputs=[inp1, inp2, inp3, inp4], outputs=[output, plot]) demo.load(fn=PCA_Pred, inputs=[inp1, inp2, inp3, inp4], outputs=[output, plot]) demo.launch()