Joe Chi commited on
Commit
697a68e
1 Parent(s): 8270912

Add gradio app

Browse files
Files changed (1) hide show
  1. app.py +90 -0
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.decomposition import PCA
2
+ import matplotlib
3
+ matplotlib.use("Agg")
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ from scipy import stats
7
+ import gradio as gr
8
+
9
+ e = np.exp(1)
10
+ np.random.seed(4)
11
+
12
+
13
+ def pdf(x):
14
+ return 0.5 * (stats.norm(scale=0.25 / e).pdf(x) + stats.norm(scale=4 / e).pdf(x))
15
+
16
+
17
+ y = np.random.normal(scale=0.5, size=(30000))
18
+ x = np.random.normal(scale=0.5, size=(30000))
19
+ z = np.random.normal(scale=0.1, size=len(x))
20
+
21
+ density = pdf(x) * pdf(y)
22
+ pdf_z = pdf(5 * z)
23
+
24
+ density *= pdf_z
25
+
26
+ a = x + y
27
+ b = 2 * y
28
+ c = a - b + z
29
+
30
+ norm = np.sqrt(a.var() + b.var())
31
+ a /= norm
32
+ b /= norm
33
+
34
+ def plot_figs(fig_num, elev, azim):
35
+ fig = plt.figure()
36
+ plt.clf()
37
+ ax = fig.add_subplot(111, projection="3d", elev=elev, azim=azim)
38
+ ax.set_position([0, 0, 0.95, 1])
39
+
40
+ ax.scatter(a[::10], b[::10], c[::10], c=density[::10], marker="+", alpha=0.4)
41
+ Y = np.c_[a, b, c]
42
+
43
+ # Using SciPy's SVD, this would be:
44
+ # _, pca_score, Vt = scipy.linalg.svd(Y, full_matrices=False)
45
+
46
+ pca = PCA(n_components=3)
47
+ pca.fit(Y)
48
+ V = pca.components_.T
49
+
50
+ x_pca_axis, y_pca_axis, z_pca_axis = 3 * V
51
+ x_pca_plane = np.r_[x_pca_axis[:2], -x_pca_axis[1::-1]]
52
+ y_pca_plane = np.r_[y_pca_axis[:2], -y_pca_axis[1::-1]]
53
+ z_pca_plane = np.r_[z_pca_axis[:2], -z_pca_axis[1::-1]]
54
+ x_pca_plane.shape = (2, 2)
55
+ y_pca_plane.shape = (2, 2)
56
+ z_pca_plane.shape = (2, 2)
57
+ ax.plot_surface(x_pca_plane, y_pca_plane, z_pca_plane)
58
+ ax.xaxis.set_ticklabels([])
59
+ ax.yaxis.set_ticklabels([])
60
+ ax.zaxis.set_ticklabels([])
61
+
62
+ plt.savefig(f"{fig_num}.png")
63
+
64
+ return fig
65
+
66
+ def make_plot(plot_type):
67
+ if plot_type == "Very flat direction":
68
+ elev = -40
69
+ azim = -80
70
+ fig_num = 1
71
+ else:
72
+ elev = 30
73
+ azim = 20
74
+ fig_num = 2
75
+ plot_figs(fig_num, elev, azim)
76
+
77
+ title = "Principal components analysis (PCA)"
78
+ with gr.Blocks(title=title) as demo:
79
+ gr.Markdown(f"## {title}")
80
+ gr.Markdown("These figures aid in illustrating how a point cloud can be \
81
+ very flat in one direction–which is where PCA comes in to choose a direction that is not flat.")
82
+
83
+
84
+ button = gr.Radio(label="Plot type",
85
+ choices=['Very flat direction', 'Not flat direction'], value='Very flat direction')
86
+ plot = gr.Plot(label="Plot")
87
+ button.change(make_plot, inputs=button, outputs=[plot])
88
+ demo.load(make_plot, inputs=[button], outputs=[plot])
89
+
90
+ demo.launch()