Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Code source: Gaël Varoquaux
|
2 |
+
# License: BSD 3 clause
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from sklearn import svm
|
7 |
+
import gradio as gr
|
8 |
+
from matplotlib.colors import ListedColormap
|
9 |
+
plt.switch_backend("agg")
|
10 |
+
|
11 |
+
font1 = {'family':'DejaVu Sans','size':20}
|
12 |
+
|
13 |
+
def create_data(random, size_num, x_min, x_max, y_min, y_max):
|
14 |
+
#emulate some random data
|
15 |
+
if random:
|
16 |
+
size_num = int(size_num)
|
17 |
+
x = np.random.uniform(x_min, x_max, size=(size_num, 1))
|
18 |
+
y = np.random.uniform(y_min, y_max, size=(size_num, 1))
|
19 |
+
|
20 |
+
X = np.hstack((x, y))
|
21 |
+
Y = [0] * int(size_num/2) + [1] * int(size_num/2)
|
22 |
+
else:
|
23 |
+
X = np.c_[
|
24 |
+
(0.4, -0.7),
|
25 |
+
(-1.5, -1),
|
26 |
+
(-1.4, -0.9),
|
27 |
+
(-1.3, -1.2),
|
28 |
+
(-1.5, 0.2),
|
29 |
+
(-1.2, -0.4),
|
30 |
+
(-0.5, 1.2),
|
31 |
+
(-1.5, 2.1),
|
32 |
+
(1, 1),
|
33 |
+
# --
|
34 |
+
(1.3, 0.8),
|
35 |
+
(1.5, 0.5),
|
36 |
+
(0.2, -2),
|
37 |
+
(0.5, -2.4),
|
38 |
+
(0.2, -2.3),
|
39 |
+
(0, -2.7),
|
40 |
+
(1.3, 2.8),
|
41 |
+
].T
|
42 |
+
|
43 |
+
Y = [0] * 8 + [1] * 8
|
44 |
+
return X, Y
|
45 |
+
|
46 |
+
# fit the model
|
47 |
+
def clf_kernel(color1, color2, dpi, size_num = None, x_min = None,
|
48 |
+
x_max = None, y_min = None,
|
49 |
+
y_max = None, random = False):
|
50 |
+
|
51 |
+
if size_num is not None or x_min is not None or x_max is not None or y_min is not None or y_max is not None:
|
52 |
+
random = True
|
53 |
+
|
54 |
+
X, Y = create_data(random, size_num, x_min, x_max, y_min, y_max)
|
55 |
+
|
56 |
+
kernels = ["linear", "poly", "rbf"]
|
57 |
+
|
58 |
+
# plot the line, the points, and the nearest vectors to the plane
|
59 |
+
fig, axs = plt.subplots(1,3, figsize = (16,8), facecolor='none', dpi = res[dpi])
|
60 |
+
|
61 |
+
cmap = ListedColormap([color1, color2], N=2, name = 'braincell')
|
62 |
+
for i, kernel in enumerate(kernels):
|
63 |
+
clf = svm.SVC(kernel=kernel, gamma=2)
|
64 |
+
clf.fit(X, Y)
|
65 |
+
axs[i].scatter(
|
66 |
+
clf.support_vectors_[:, 0],
|
67 |
+
clf.support_vectors_[:, 1],
|
68 |
+
s=80,
|
69 |
+
facecolors="none",
|
70 |
+
zorder=10,
|
71 |
+
edgecolors="k",
|
72 |
+
)
|
73 |
+
axs[i].scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=cmap, edgecolors="k")
|
74 |
+
|
75 |
+
axs[i].axis("tight")
|
76 |
+
x_min = -3
|
77 |
+
x_max = 3
|
78 |
+
y_min = -3
|
79 |
+
y_max = 3
|
80 |
+
|
81 |
+
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
|
82 |
+
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
|
83 |
+
|
84 |
+
# Put the result into a color plot
|
85 |
+
Z = Z.reshape(XX.shape)
|
86 |
+
axs[i].pcolormesh(XX, YY, Z > 0, cmap=cmap)
|
87 |
+
axs[i].contour(
|
88 |
+
XX,
|
89 |
+
YY,
|
90 |
+
Z,
|
91 |
+
colors=["k", "k", "k"],
|
92 |
+
linestyles=["--", "-", "--"],
|
93 |
+
levels=[-0.5, 0, 0.5],
|
94 |
+
)
|
95 |
+
|
96 |
+
axs[i].set_xlim(x_min, x_max)
|
97 |
+
axs[i].set_ylim(y_min, y_max)
|
98 |
+
|
99 |
+
axs[i].set_xticks(())
|
100 |
+
axs[i].set_yticks(())
|
101 |
+
axs[i].set_title('Type of kernel: ' + kernel,
|
102 |
+
color = "white", fontdict = font1, pad=20,
|
103 |
+
bbox=dict(boxstyle="round,pad=0.3",
|
104 |
+
color = "#6366F1"))
|
105 |
+
|
106 |
+
plt.close()
|
107 |
+
return fig, np.round(X, decimals=2)
|
108 |
+
|
109 |
+
intro = """<h1 style="text-align: center;">🤗 Introducing SVM-Kernels 🤗</h1>
|
110 |
+
"""
|
111 |
+
desc = """<h3 style="text-align: center;">Three different types of SVM-Kernels are displayed below.
|
112 |
+
The polynomial and RBF are especially useful when the data-points are not linearly separable. </h3>
|
113 |
+
"""
|
114 |
+
notice = """<br><div style = "text-align: left;"> <em>Notice: Run the model on example data or use <strong>Randomize data</strong>
|
115 |
+
button below to check out the model on randomized data-points. Any changes to visual parameters will reset the data!</em></div>"""
|
116 |
+
|
117 |
+
notice2 = """<br><div style = "text-align: left;"> <em>Notice: The data points are categorized into two distinct classes, and they are evenly distributed on the plots to visually represent these classes.</em></div>"""
|
118 |
+
|
119 |
+
made ="""<div style="text-align: center;">
|
120 |
+
<p>Made with ❤</p>"""
|
121 |
+
|
122 |
+
link = """<div style="text-align: center;">
|
123 |
+
<a href="https://scikit-learn.org/stable/auto_examples/svm/plot_svm_kernels.html#sphx-glr-auto-examples-svm-plot-svm-kernels-py" target="_blank" rel="noopener noreferrer">
|
124 |
+
Demo is based on this script from scikit-learn documentation</a>"""
|
125 |
+
|
126 |
+
res = {'Small': 50, 'Medium': 75, 'Large': 100}
|
127 |
+
|
128 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo",
|
129 |
+
secondary_hue="violet",
|
130 |
+
neutral_hue="slate",
|
131 |
+
font = gr.themes.GoogleFont("Inter")),
|
132 |
+
title="SVM-Kernels") as demo:
|
133 |
+
|
134 |
+
gr.HTML(intro)
|
135 |
+
gr.HTML(desc)
|
136 |
+
|
137 |
+
with gr.Tab("Plotted results"):
|
138 |
+
plot = gr.Plot(label="Kernel comparison:")
|
139 |
+
with gr.Tab("Data coordinates"):
|
140 |
+
gr.HTML(notice2)
|
141 |
+
X = gr.Numpy(headers = ['x','y'], interactive=False)
|
142 |
+
|
143 |
+
with gr.Column():
|
144 |
+
|
145 |
+
with gr.Accordion(label = 'Randomize data'):
|
146 |
+
gr.HTML(notice)
|
147 |
+
samples = gr.Slider(4, 16, value = 8, step = 2, label = "Number of samples:")
|
148 |
+
x_min = gr.Slider(-3, 0, value=-2, step=0.1, label="X Min:")
|
149 |
+
x_max = gr.Slider(0, 3, value=2, step=0.1, label="X Max:")
|
150 |
+
y_min = gr.Slider(-3, 0, value=-2, step=0.1, label="Y Min:")
|
151 |
+
y_max = gr.Slider(0, 3, value=2, step=0.1, label="Y Max:")
|
152 |
+
random = gr.Button("Randomize data")
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
with gr.Accordion(label = "Visual parameters"):
|
158 |
+
with gr.Row():
|
159 |
+
color1 = gr.ColorPicker(label = 'Pick color one:', value = '#9abfd8')
|
160 |
+
color2 = gr.ColorPicker(label = 'Pick color two:', value = '#371c4b')
|
161 |
+
#dpi = gr.Slider(50, 100, value = 75, step = 1, label = "Set the resolution: ")
|
162 |
+
dpi = gr.Radio(list(res.keys()), value = 'Medium', label = "Select the plot size:")
|
163 |
+
|
164 |
+
params2 = [color1, color2, dpi]
|
165 |
+
|
166 |
+
random.click(fn=clf_kernel, inputs=[color1, color2, dpi,samples, x_min, x_max, y_min, y_max], outputs=[plot,X])
|
167 |
+
|
168 |
+
for i in params2:
|
169 |
+
i.change(fn=clf_kernel, inputs=[color1, color2,dpi], outputs=[plot, X])
|
170 |
+
|
171 |
+
demo.load(fn=clf_kernel, inputs=[color1, color2, dpi], outputs=[plot,X])
|
172 |
+
gr.HTML(made)
|
173 |
+
gr.HTML(link)
|
174 |
+
|
175 |
+
demo.launch()
|