Raaniel commited on
Commit
cb6037b
1 Parent(s): ec2f390

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +184 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Jaques Grobler <[email protected]>
2
+ # License: BSD 3 clause
3
+
4
+ from time import time
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ from matplotlib.ticker import NullFormatter
8
+ from sklearn import manifold
9
+ from sklearn.utils import check_random_state
10
+ import plotly.graph_objects as go
11
+ import gradio as gr
12
+ from matplotlib import style
13
+ plt.switch_backend("agg")
14
+ style.use('ggplot')
15
+
16
+ n_neighbors = 10
17
+ n_samples = 1000
18
+
19
+ font1 = {'family':'DejaVu Sans','size':10, 'color':'white'}
20
+
21
+ def sphere(n_neighbors, n_samples):
22
+
23
+ # Create our sphere.
24
+ random_state = check_random_state(0)
25
+ p = random_state.rand(n_samples) * (2 * np.pi - 0.55)
26
+ t = random_state.rand(n_samples) * np.pi
27
+
28
+ # Sever the poles from the sphere.
29
+ indices = (t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))
30
+ colors = p[indices]
31
+ x, y, z = (
32
+ np.sin(t[indices]) * np.cos(p[indices]),
33
+ np.sin(t[indices]) * np.sin(p[indices]),
34
+ np.cos(t[indices]),
35
+ )
36
+
37
+ sphere_data = np.array([x, y, z]).T
38
+
39
+ return x, y, z, colors, sphere_data
40
+
41
+ x, y, z, colors, sphere_data = sphere(n_neighbors, n_samples)
42
+
43
+ def create_3D_plot(n_neighbors = n_neighbors, n_samples = n_samples):
44
+
45
+ x, y, z, colors = sphere(n_neighbors, n_samples)[:4]
46
+
47
+ # Create the trace for the scatter plot
48
+ scatter_trace = go.Scatter3d(
49
+ x=x,
50
+ y=y,
51
+ z=z,
52
+ mode='markers',
53
+ marker=dict(
54
+ size=5,
55
+ color=colors,
56
+ colorscale='rainbow',
57
+ showscale=False
58
+ )
59
+ )
60
+
61
+ # Create the figure and add the trace
62
+ fig = go.Figure()
63
+ fig.add_trace(scatter_trace)
64
+
65
+ return fig
66
+
67
+ # Perform Locally Linear Embedding Manifold learning
68
+ methods = {"LLE":"standard", "LTSA":"ltsa" ,
69
+ 'Hessian LLE':'hessian', "Modified LLE":"modified"}
70
+
71
+ available = ["LLE", "LTSA",'Hessian LLE',"Modified LLE",
72
+ "Isomap","MDS","Spectral Embedding", "t-SNE"]
73
+
74
+ def make_plot(method, methods = methods):
75
+
76
+ # Plot our dataset.
77
+ fig1 = plt.figure(figsize=(10, 6), facecolor = 'none', dpi = 200)
78
+ plt.title(
79
+ "Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors),
80
+ pad = 20, bbox=dict(boxstyle="round,pad=0.3",color = "#6366F1"),
81
+ fontdict = font1, size = 16
82
+ )
83
+
84
+ if method in methods.keys():
85
+ t0 = time()
86
+ trans_data = (
87
+ manifold.LocallyLinearEmbedding(
88
+ n_neighbors=n_neighbors, n_components=2, method=methods[method]
89
+ )
90
+ .fit_transform(sphere_data)
91
+ .T
92
+ )
93
+ t1 = time()
94
+ title = "%s: %.2g sec" % (method, t1 - t0)
95
+
96
+ elif method == "Isomap":
97
+ # Perform Isomap Manifold learning.
98
+ t0 = time()
99
+ trans_data = (
100
+ manifold.Isomap(n_neighbors=n_neighbors, n_components=2)
101
+ .fit_transform(sphere_data)
102
+ .T
103
+ )
104
+ t1 = time()
105
+ title = "%s: %.2g sec" % ("ISO", t1 - t0)
106
+
107
+ elif method == "MDS":
108
+ # Perform Multi-dimensional scaling.
109
+ t0 = time()
110
+ mds = manifold.MDS(2, max_iter=100, n_init=1, normalized_stress="auto")
111
+ trans_data = mds.fit_transform(sphere_data).T
112
+ t1 = time()
113
+ title = "MDS: %.2g sec" % (t1 - t0)
114
+
115
+ elif method == "Spectral Embedding":
116
+ # Perform Spectral Embedding.
117
+ t0 = time()
118
+ se = manifold.SpectralEmbedding(n_components=2, n_neighbors=n_neighbors)
119
+ trans_data = se.fit_transform(sphere_data).T
120
+ t1 = time()
121
+ title = "Spectral Embedding: %.2g sec" % (t1 - t0)
122
+
123
+ elif method == "t-SNE":
124
+ # Perform t-distributed stochastic neighbor embedding.
125
+ t0 = time()
126
+ tsne = manifold.TSNE(n_components=2, random_state=0)
127
+ trans_data = tsne.fit_transform(sphere_data).T
128
+ t1 = time()
129
+ title = "t-SNE: %.2g sec" % (t1 - t0)
130
+
131
+ ax = fig1.add_subplot()
132
+ ax.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
133
+
134
+ ax.tick_params(axis='x', which='both', bottom=False, labelbottom=False) # Hide x-axis tick labels
135
+ ax.tick_params(axis='y', which='both', left=False, labelleft=False) # Hide y-axis tick labels
136
+
137
+ return fig1, title
138
+
139
+ made ="""<div style="text-align: center;">
140
+ <p>Made with ❤</p>"""
141
+
142
+ link = """<div style="text-align: center;">
143
+ <a href="https://scikit-learn.org/stable/auto_examples/manifold/plot_manifold_sphere.html#sphx-glr-auto-examples-manifold-plot-manifold-sphere-py">
144
+ Demo is based on this script from scikit-learn documentation</a>"""
145
+
146
+ intro = """<h1 style="text-align: center;">🤗 Manifold Learning methods on a severed sphere 🤗</h1>
147
+ """
148
+ desc = """<h3 style="text-align: left;"> An application of the different <a href="https://scikit-learn.org/stable/modules/manifold.html#manifold">
149
+ Manifold Learning</a> techniques on a spherical data-set. Here one can see the use of dimensionality reduction in order to gain some intuition regarding the manifold learning methods. Regarding the dataset, the poles are cut from the sphere, as well as a thin slice down its side. This enables the manifold learning techniques to ‘spread it open’ whilst projecting it onto two dimensions.
150
+ <br><br>
151
+ For a similar example, where the methods are applied to the S-curve dataset, see <a href="https://scikit-learn.org/stable/auto_examples/manifold/plot_manifold_sphere.html#sphx-glr-auto-examples-manifold-plot-manifold-sphere-py">
152
+ Comparison of Manifold Learning methods</a>.
153
+ <br><br>
154
+ Note that the purpose of the <a href="https://scikit-learn.org/stable/modules/manifold.html#multidimensional-scaling">
155
+ MDS</a> is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. Here the manifold problem matches fairly that of representing a flat map of the Earth, as with <a href="https://en.wikipedia.org/wiki/Map_projection">
156
+ map projection</a>.
157
+ </h3>
158
+ """
159
+
160
+ with gr.Blocks(theme = gr.themes.Soft(
161
+ primary_hue="amber",
162
+ secondary_hue="orange",
163
+ neutral_hue="teal",
164
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui', 'sans-serif'],), title = "Manifold Learning methods on a severed sphere") as demo:
165
+ with gr.Column():
166
+ gr.HTML(intro)
167
+ with gr.Accordion(label = "Description", open = True):
168
+ gr.HTML(desc)
169
+ with gr.Column():
170
+ method = gr.Radio(available, label="Select method:", value= "LLE")
171
+ title = gr.Textbox(label = 'Time for the method to perform:')
172
+ with gr.Row():
173
+ plot_3D = gr.Plot(label="3D projection of the sphere")
174
+ plot = gr.Plot(label="Plot")
175
+
176
+ method.change(fn=make_plot, inputs = method, outputs=[plot, title])
177
+
178
+ demo.load(fn=make_plot, inputs = method, outputs=[plot, title])
179
+ demo.load(fn=create_3D_plot, inputs = [], outputs=plot_3D)
180
+ gr.HTML(made)
181
+ gr.HTML(link)
182
+
183
+ demo.launch()
184
+
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ matplotlib
2
+ numpy
3
+ scikit-learn
4
+ plotly
5
+ gradio