Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,469 +1,251 @@
|
|
1 |
import marimo
|
2 |
|
3 |
-
__generated_with = "0.
|
4 |
app = marimo.App()
|
5 |
|
6 |
|
7 |
-
@app.cell
|
8 |
-
def __():
|
9 |
-
import marimo as mo
|
10 |
-
|
11 |
-
mo.md("# Welcome to marimo! ππ")
|
12 |
-
return (mo,)
|
13 |
-
|
14 |
-
|
15 |
-
@app.cell
|
16 |
-
def __(mo):
|
17 |
-
slider = mo.ui.slider(1, 22)
|
18 |
-
return (slider,)
|
19 |
-
|
20 |
-
|
21 |
-
@app.cell
|
22 |
-
def __(mo, slider):
|
23 |
-
mo.md(
|
24 |
-
f"""
|
25 |
-
marimo is a **reactive** Python notebook.
|
26 |
-
|
27 |
-
This means that unlike traditional notebooks, marimo notebooks **run
|
28 |
-
automatically** when you modify them or
|
29 |
-
interact with UI elements, like this slider: {slider}.
|
30 |
-
|
31 |
-
{"##" + "π" * slider.value}
|
32 |
-
"""
|
33 |
-
)
|
34 |
-
return
|
35 |
-
|
36 |
-
|
37 |
-
@app.cell(hide_code=True)
|
38 |
-
def __(mo):
|
39 |
-
mo.accordion(
|
40 |
-
{
|
41 |
-
"Tip: disabling automatic execution": mo.md(
|
42 |
-
rf"""
|
43 |
-
marimo lets you disable automatic execution: just go into the
|
44 |
-
notebook settings and set
|
45 |
-
|
46 |
-
"Runtime > On Cell Change" to "lazy".
|
47 |
-
|
48 |
-
When the runtime is lazy, after running a cell, marimo marks its
|
49 |
-
descendants as stale instead of automatically running them. The
|
50 |
-
lazy runtime puts you in control over when cells are run, while
|
51 |
-
still giving guarantees about the notebook state.
|
52 |
-
"""
|
53 |
-
)
|
54 |
-
}
|
55 |
-
)
|
56 |
-
return
|
57 |
-
|
58 |
-
|
59 |
@app.cell(hide_code=True)
|
60 |
-
def
|
61 |
mo.md(
|
62 |
-
"""
|
63 |
-
|
64 |
-
by entering `marimo edit` at the command line.
|
65 |
-
"""
|
66 |
-
).callout()
|
67 |
-
return
|
68 |
-
|
69 |
-
|
70 |
-
@app.cell(hide_code=True)
|
71 |
-
def __(mo):
|
72 |
-
mo.md(
|
73 |
-
"""
|
74 |
-
## 1. Reactive execution
|
75 |
|
76 |
-
|
77 |
-
cells.
|
78 |
|
79 |
-
|
80 |
-
a cell that defines a global variable is run, marimo
|
81 |
-
**automatically runs** all cells that reference that variable.
|
82 |
|
83 |
-
|
84 |
-
making for a dynamic programming environment that prevents bugs before they
|
85 |
-
happen.
|
86 |
"""
|
87 |
)
|
88 |
return
|
89 |
|
90 |
|
91 |
-
@app.cell(hide_code=True)
|
92 |
-
def __(changed, mo):
|
93 |
-
(
|
94 |
-
mo.md(
|
95 |
-
f"""
|
96 |
-
**β¨ Nice!** The value of `changed` is now {changed}.
|
97 |
-
|
98 |
-
When you updated the value of the variable `changed`, marimo
|
99 |
-
**reacted** by running this cell automatically, because this cell
|
100 |
-
references the global variable `changed`.
|
101 |
-
|
102 |
-
Reactivity ensures that your notebook state is always
|
103 |
-
consistent, which is crucial for doing good science; it's also what
|
104 |
-
enables marimo notebooks to double as tools and apps.
|
105 |
-
"""
|
106 |
-
)
|
107 |
-
if changed
|
108 |
-
else mo.md(
|
109 |
-
"""
|
110 |
-
**π See it in action.** In the next cell, change the value of the
|
111 |
-
variable `changed` to `True`, then click the run button.
|
112 |
-
"""
|
113 |
-
)
|
114 |
-
)
|
115 |
-
return
|
116 |
-
|
117 |
-
|
118 |
@app.cell
|
119 |
-
def
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
138 |
)
|
139 |
-
return
|
140 |
|
141 |
|
142 |
@app.cell(hide_code=True)
|
143 |
-
def
|
144 |
-
mo.md(
|
145 |
-
"""
|
146 |
-
**Global names must be unique.** To enable reactivity, marimo imposes a
|
147 |
-
constraint on how names appear in cells: no two cells may define the same
|
148 |
-
variable.
|
149 |
-
"""
|
150 |
-
)
|
151 |
return
|
152 |
|
153 |
|
154 |
-
@app.cell
|
155 |
-
def
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
)
|
166 |
-
return
|
167 |
|
168 |
|
169 |
@app.cell(hide_code=True)
|
170 |
-
def
|
171 |
-
mo.
|
172 |
-
{
|
173 |
-
"Tip: private variables": (
|
174 |
-
"""
|
175 |
-
Variables prefixed with an underscore are "private" to a cell, so
|
176 |
-
they can be defined by multiple cells.
|
177 |
-
"""
|
178 |
-
)
|
179 |
-
}
|
180 |
-
)
|
181 |
return
|
182 |
|
183 |
|
184 |
-
@app.cell
|
185 |
-
def
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
198 |
)
|
199 |
-
return
|
200 |
|
201 |
|
202 |
@app.cell
|
203 |
-
def
|
204 |
-
mo.md("""
|
205 |
return
|
206 |
|
207 |
|
208 |
@app.cell
|
209 |
-
def
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
return (repetitions,)
|
218 |
|
219 |
|
220 |
@app.cell
|
221 |
-
def
|
222 |
-
|
223 |
return
|
224 |
|
225 |
|
226 |
@app.cell
|
227 |
-
def
|
228 |
-
|
229 |
-
return
|
230 |
-
|
231 |
-
|
232 |
-
@app.cell(hide_code=True)
|
233 |
-
def __(mo):
|
234 |
-
mo.md(
|
235 |
-
"""
|
236 |
-
## 3. marimo is just Python
|
237 |
|
238 |
-
|
239 |
-
|
240 |
-
|
|
|
|
|
|
|
|
|
241 |
|
242 |
-
The Python files generated by marimo are:
|
243 |
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
|
|
|
|
|
|
253 |
|
254 |
|
255 |
@app.cell(hide_code=True)
|
256 |
-
def
|
257 |
-
mo.md(
|
258 |
-
"""
|
259 |
-
## 4. Running notebooks as apps
|
260 |
-
|
261 |
-
marimo notebooks can double as apps. Click the app window icon in the
|
262 |
-
bottom-right to see this notebook in "app view."
|
263 |
-
|
264 |
-
Serve a notebook as an app with `marimo run` at the command-line.
|
265 |
-
Of course, you can use marimo just to level-up your
|
266 |
-
notebooking, without ever making apps.
|
267 |
-
"""
|
268 |
-
)
|
269 |
return
|
270 |
|
271 |
|
272 |
-
@app.cell
|
273 |
-
def
|
274 |
-
mo
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
**Creating and editing notebooks.** Use
|
279 |
-
|
280 |
-
```
|
281 |
-
marimo edit
|
282 |
-
```
|
283 |
-
|
284 |
-
in a terminal to start the marimo notebook server. From here
|
285 |
-
you can create a new notebook or edit existing ones.
|
286 |
-
|
287 |
-
|
288 |
-
**Running as apps.** Use
|
289 |
-
|
290 |
-
```
|
291 |
-
marimo run notebook.py
|
292 |
-
```
|
293 |
-
|
294 |
-
to start a webserver that serves your notebook as an app in read-only mode,
|
295 |
-
with code cells hidden.
|
296 |
-
|
297 |
-
**Convert a Jupyter notebook.** Convert a Jupyter notebook to a marimo
|
298 |
-
notebook using `marimo convert`:
|
299 |
-
|
300 |
-
```
|
301 |
-
marimo convert your_notebook.ipynb > your_app.py
|
302 |
-
```
|
303 |
-
|
304 |
-
**Tutorials.** marimo comes packaged with tutorials:
|
305 |
-
|
306 |
-
- `dataflow`: more on marimo's automatic execution
|
307 |
-
- `ui`: how to use UI elements
|
308 |
-
- `markdown`: how to write markdown, with interpolated values and
|
309 |
-
LaTeX
|
310 |
-
- `plots`: how plotting works in marimo
|
311 |
-
- `sql`: how to use SQL
|
312 |
-
- `layout`: layout elements in marimo
|
313 |
-
- `fileformat`: how marimo's file format works
|
314 |
-
- `markdown-format`: for using `.md` files in marimo
|
315 |
-
- `for-jupyter-users`: if you are coming from Jupyter
|
316 |
-
|
317 |
-
Start a tutorial with `marimo tutorial`; for example,
|
318 |
-
|
319 |
-
```
|
320 |
-
marimo tutorial dataflow
|
321 |
-
```
|
322 |
-
|
323 |
-
In addition to tutorials, we have examples in our
|
324 |
-
[our GitHub repo](https://www.github.com/marimo-team/marimo/tree/main/examples).
|
325 |
-
"""
|
326 |
-
)
|
327 |
-
return
|
328 |
|
329 |
|
330 |
@app.cell(hide_code=True)
|
331 |
-
def
|
332 |
-
mo.md(
|
333 |
-
"""
|
334 |
-
## 6. The marimo editor
|
335 |
-
|
336 |
-
Here are some tips to help you get started with the marimo editor.
|
337 |
-
"""
|
338 |
-
)
|
339 |
return
|
340 |
|
341 |
|
342 |
@app.cell
|
343 |
-
def
|
344 |
-
mo.
|
345 |
-
return
|
346 |
|
347 |
|
348 |
-
@app.cell
|
349 |
-
def
|
350 |
-
|
351 |
-
|
352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
353 |
|
354 |
-
|
355 |
-
|
356 |
-
mo.md(
|
357 |
-
"""
|
358 |
-
The name "marimo" is a reference to a type of algae that, under
|
359 |
-
the right conditions, clumps together to form a small sphere
|
360 |
-
called a "marimo moss ball". Made of just strands of algae, these
|
361 |
-
beloved assemblages are greater than the sum of their parts.
|
362 |
-
"""
|
363 |
-
)
|
364 |
-
return
|
365 |
|
366 |
|
367 |
-
@app.cell
|
368 |
-
def
|
369 |
-
|
370 |
-
"Saving": (
|
371 |
-
"""
|
372 |
-
**Saving**
|
373 |
-
|
374 |
-
- _Name_ your app using the box at the top of the screen, or
|
375 |
-
with `Ctrl/Cmd+s`. You can also create a named app at the
|
376 |
-
command line, e.g., `marimo edit app_name.py`.
|
377 |
-
|
378 |
-
- _Save_ by clicking the save icon on the bottom right, or by
|
379 |
-
inputting `Ctrl/Cmd+s`. By default marimo is configured
|
380 |
-
to autosave.
|
381 |
-
"""
|
382 |
-
),
|
383 |
-
"Running": (
|
384 |
-
"""
|
385 |
-
1. _Run a cell_ by clicking the play ( β· ) button on the top
|
386 |
-
right of a cell, or by inputting `Ctrl/Cmd+Enter`.
|
387 |
-
|
388 |
-
2. _Run a stale cell_ by clicking the yellow run button on the
|
389 |
-
right of the cell, or by inputting `Ctrl/Cmd+Enter`. A cell is
|
390 |
-
stale when its code has been modified but not run.
|
391 |
-
|
392 |
-
3. _Run all stale cells_ by clicking the play ( β· ) button on
|
393 |
-
the bottom right of the screen, or input `Ctrl/Cmd+Shift+r`.
|
394 |
-
"""
|
395 |
-
),
|
396 |
-
"Console Output": (
|
397 |
-
"""
|
398 |
-
Console output (e.g., `print()` statements) is shown below a
|
399 |
-
cell.
|
400 |
-
"""
|
401 |
-
),
|
402 |
-
"Creating, Moving, and Deleting Cells": (
|
403 |
-
"""
|
404 |
-
1. _Create_ a new cell above or below a given one by clicking
|
405 |
-
the plus button to the left of the cell, which appears on
|
406 |
-
mouse hover.
|
407 |
-
|
408 |
-
2. _Move_ a cell up or down by dragging on the handle to the
|
409 |
-
right of the cell, which appears on mouse hover.
|
410 |
-
|
411 |
-
3. _Delete_ a cell by clicking the trash bin icon. Bring it
|
412 |
-
back by clicking the undo button on the bottom right of the
|
413 |
-
screen, or with `Ctrl/Cmd+Shift+z`.
|
414 |
-
"""
|
415 |
-
),
|
416 |
-
"Disabling Automatic Execution": (
|
417 |
-
"""
|
418 |
-
Via the notebook settings (gear icon) or footer panel, you
|
419 |
-
can disable automatic execution. This is helpful when
|
420 |
-
working with expensive notebooks or notebooks that have
|
421 |
-
side-effects like database transactions.
|
422 |
-
"""
|
423 |
-
),
|
424 |
-
"Disabling Cells": (
|
425 |
-
"""
|
426 |
-
You can disable a cell via the cell context menu.
|
427 |
-
marimo will never run a disabled cell or any cells that depend on it.
|
428 |
-
This can help prevent accidental execution of expensive computations
|
429 |
-
when editing a notebook.
|
430 |
-
"""
|
431 |
-
),
|
432 |
-
"Code Folding": (
|
433 |
-
"""
|
434 |
-
You can collapse or fold the code in a cell by clicking the arrow
|
435 |
-
icons in the line number column to the left, or by using keyboard
|
436 |
-
shortcuts.
|
437 |
-
|
438 |
-
Use the command palette (`Ctrl/Cmd+k`) or a keyboard shortcut to
|
439 |
-
quickly fold or unfold all cells.
|
440 |
-
"""
|
441 |
-
),
|
442 |
-
"Code Formatting": (
|
443 |
-
"""
|
444 |
-
If you have [ruff](https://github.com/astral-sh/ruff) installed,
|
445 |
-
you can format a cell with the keyboard shortcut `Ctrl/Cmd+b`.
|
446 |
-
"""
|
447 |
-
),
|
448 |
-
"Command Palette": (
|
449 |
-
"""
|
450 |
-
Use `Ctrl/Cmd+k` to open the command palette.
|
451 |
-
"""
|
452 |
-
),
|
453 |
-
"Keyboard Shortcuts": (
|
454 |
-
"""
|
455 |
-
Open the notebook menu (top-right) or input `Ctrl/Cmd+Shift+h` to
|
456 |
-
view a list of all keyboard shortcuts.
|
457 |
-
"""
|
458 |
-
),
|
459 |
-
"Configuration": (
|
460 |
-
"""
|
461 |
-
Configure the editor by clicking the gears icon near the top-right
|
462 |
-
of the screen.
|
463 |
-
"""
|
464 |
-
),
|
465 |
-
}
|
466 |
-
return (tips,)
|
467 |
|
468 |
|
469 |
if __name__ == "__main__":
|
|
|
1 |
import marimo
|
2 |
|
3 |
+
__generated_with = "0.12.8"
|
4 |
app = marimo.App()
|
5 |
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
@app.cell(hide_code=True)
|
8 |
+
def _(mo):
|
9 |
mo.md(
|
10 |
+
r"""
|
11 |
+
## Face Embeddings of World Leaders
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
This notebook explores face embeddings using a subset of the **Labeled Faces in the Wild** dataset, focused on public figures. We'll use standard Python and scikit-learn libraries to load the data, embed images, reduce dimensionality, and visualize clustering behavior.
|
|
|
14 |
|
15 |
+
This example builds on a demo from the Marimo gallery using the MNIST dataset. Here, we adapt it to work with a facial recognition dataset of public figures. While facial recognition has limited responsible use cases, this curated subset includes only world leaders β a group I feel comfortable experimenting with in a technical context.
|
|
|
|
|
16 |
|
17 |
+
We'll start with our imports:
|
|
|
|
|
18 |
"""
|
19 |
)
|
20 |
return
|
21 |
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
@app.cell
|
24 |
+
def _():
|
25 |
+
from time import time
|
26 |
+
|
27 |
+
import matplotlib.pyplot as plt
|
28 |
+
from scipy.stats import loguniform
|
29 |
+
|
30 |
+
from sklearn.datasets import fetch_lfw_people
|
31 |
+
from sklearn.decomposition import PCA
|
32 |
+
from sklearn.metrics import ConfusionMatrixDisplay, classification_report
|
33 |
+
from sklearn.model_selection import RandomizedSearchCV, train_test_split
|
34 |
+
from sklearn.preprocessing import StandardScaler
|
35 |
+
from sklearn.svm import SVC
|
36 |
+
return (
|
37 |
+
ConfusionMatrixDisplay,
|
38 |
+
PCA,
|
39 |
+
RandomizedSearchCV,
|
40 |
+
SVC,
|
41 |
+
StandardScaler,
|
42 |
+
classification_report,
|
43 |
+
fetch_lfw_people,
|
44 |
+
loguniform,
|
45 |
+
plt,
|
46 |
+
time,
|
47 |
+
train_test_split,
|
48 |
)
|
|
|
49 |
|
50 |
|
51 |
@app.cell(hide_code=True)
|
52 |
+
def _(mo):
|
53 |
+
mo.md(r"""We're using `fetch_lfw_people` from `sklearn.datasets` to load a curated subset of the LFW dataset β restricted to individuals with at least 70 images, resulting in 7 distinct people and just over 1,200 samples. These happen to be mostly world leaders, which makes the demo both manageable and fun to explore.""")
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
return
|
55 |
|
56 |
|
57 |
+
@app.cell
|
58 |
+
def _(fetch_lfw_people):
|
59 |
+
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
|
60 |
+
|
61 |
+
# introspect the images arrays to find the shapes (for plotting)
|
62 |
+
n_samples, h, w = lfw_people.images.shape
|
63 |
+
|
64 |
+
# for machine learning we use the 2 data directly (as relative pixel
|
65 |
+
# positions info is ignored by this model)
|
66 |
+
X = lfw_people.data
|
67 |
+
n_features = X.shape[1]
|
68 |
+
|
69 |
+
# the label to predict is the id of the person
|
70 |
+
Y = lfw_people.target
|
71 |
+
target_names = lfw_people.target_names
|
72 |
+
n_classes = target_names.shape[0]
|
73 |
+
|
74 |
+
print("Total dataset size:")
|
75 |
+
print("n_samples: %d" % n_samples)
|
76 |
+
print("n_features: %d" % n_features)
|
77 |
+
print("n_classes: %d" % n_classes)
|
78 |
+
return (
|
79 |
+
X,
|
80 |
+
Y,
|
81 |
+
h,
|
82 |
+
lfw_people,
|
83 |
+
n_classes,
|
84 |
+
n_features,
|
85 |
+
n_samples,
|
86 |
+
target_names,
|
87 |
+
w,
|
88 |
)
|
|
|
89 |
|
90 |
|
91 |
@app.cell(hide_code=True)
|
92 |
+
def _(mo):
|
93 |
+
mo.md(r"""Next, we embed each face image using a pre-trained FaceNet model (`InceptionResnetV1` trained on `vggface2`). This converts each image into a 512-dimensional vector. Since the original data is grayscale and flattened, we reshape, normalize, and convert it to RGB before feeding it through the model.""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
return
|
95 |
|
96 |
|
97 |
+
@app.cell
|
98 |
+
def _(X, h, w):
|
99 |
+
from facenet_pytorch import InceptionResnetV1
|
100 |
+
from torchvision import transforms
|
101 |
+
from PIL import Image
|
102 |
+
import torch
|
103 |
+
import numpy as np
|
104 |
+
|
105 |
+
# Load FaceNet model
|
106 |
+
model = InceptionResnetV1(pretrained='vggface2').eval()
|
107 |
+
|
108 |
+
# Transform pipeline: grayscale β RGB β resize β normalize
|
109 |
+
transform = transforms.Compose([
|
110 |
+
transforms.Resize((160, 160)),
|
111 |
+
transforms.ToTensor(),
|
112 |
+
transforms.Lambda(lambda x: x.repeat(3, 1, 1) if x.shape[0] == 1 else x),
|
113 |
+
transforms.Normalize([0.5], [0.5])
|
114 |
+
])
|
115 |
+
|
116 |
+
# Embed a single flattened row from X
|
117 |
+
def embed_flat_row(flat):
|
118 |
+
img = flat.reshape(h, w)
|
119 |
+
img = (img * 255).astype(np.uint8)
|
120 |
+
pil = Image.fromarray(img).convert("L") # grayscale
|
121 |
+
tensor = transform(pil).unsqueeze(0)
|
122 |
+
with torch.no_grad():
|
123 |
+
return model(tensor).squeeze().numpy() # 512-dim
|
124 |
+
|
125 |
+
# Generate embeddings for all samples
|
126 |
+
embeddings = np.array([embed_flat_row(row) for row in X])
|
127 |
+
return (
|
128 |
+
Image,
|
129 |
+
InceptionResnetV1,
|
130 |
+
embed_flat_row,
|
131 |
+
embeddings,
|
132 |
+
model,
|
133 |
+
np,
|
134 |
+
torch,
|
135 |
+
transform,
|
136 |
+
transforms,
|
137 |
)
|
|
|
138 |
|
139 |
|
140 |
@app.cell
|
141 |
+
def _(mo):
|
142 |
+
mo.md(r"""Now that we have 512-dimensional embeddings, we reduce them to 2D for visualization. Both t-SNE and UMAP are available here β UMAP is active by default, but you can switch to t-SNE by uncommenting the alternate line. This step lets us inspect the structure of the embedding space:""")
|
143 |
return
|
144 |
|
145 |
|
146 |
@app.cell
|
147 |
+
def _(embeddings):
|
148 |
+
from sklearn.manifold import TSNE
|
149 |
+
import umap.umap_ as umap
|
|
|
150 |
|
151 |
+
# X_embedded = TSNE(n_components=2, perplexity=30, random_state=42).fit_transform(embeddings)
|
152 |
+
X_embedded = umap.UMAP(n_components=2, random_state=42).fit_transform(embeddings)
|
153 |
+
return TSNE, X_embedded, umap
|
|
|
154 |
|
155 |
|
156 |
@app.cell
|
157 |
+
def _(mo):
|
158 |
+
mo.md(r"""We wrap the 2D embeddings into a Pandas DataFrame for easier manipulation and plotting. Each row includes x/y coordinates and the associated person ID, which we map to names. We then define a simple Altair scatterplot function to visualize the clustered embeddings by identity.""")
|
159 |
return
|
160 |
|
161 |
|
162 |
@app.cell
|
163 |
+
def _(X_embedded, Y, target_names):
|
164 |
+
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
|
166 |
+
embedding_df = pd.DataFrame({
|
167 |
+
"x": X_embedded[:, 0],
|
168 |
+
"y": X_embedded[:, 1],
|
169 |
+
"person": Y
|
170 |
+
}).reset_index()
|
171 |
+
embedding_df["name"] = embedding_df["person"].map(lambda i: target_names[i])
|
172 |
+
return embedding_df, pd
|
173 |
|
|
|
174 |
|
175 |
+
@app.cell
|
176 |
+
def _():
|
177 |
+
import altair as alt
|
178 |
+
def scatter(df):
|
179 |
+
return (alt.Chart(df)
|
180 |
+
.mark_circle()
|
181 |
+
.encode(
|
182 |
+
x=alt.X("x:Q"),
|
183 |
+
y=alt.Y("y:Q"),
|
184 |
+
color=alt.Color("name:N"),
|
185 |
+
).properties(width=500, height=300))
|
186 |
+
return alt, scatter
|
187 |
|
188 |
|
189 |
@app.cell(hide_code=True)
|
190 |
+
def _(mo):
|
191 |
+
mo.md(r"""Here's our 2D embedding space of world leader faces! Each point is a facial embedding projected with UMAP and colored by identity. Try selecting a cluster β the notebook will automatically reveal the associated images so you can explore what the model βthinksβ belongs together.""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
return
|
193 |
|
194 |
|
195 |
+
@app.cell
|
196 |
+
def _(embedding_df, scatter):
|
197 |
+
import marimo as mo
|
198 |
+
chart = mo.ui.altair_chart(scatter(embedding_df))
|
199 |
+
return chart, mo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
201 |
|
202 |
@app.cell(hide_code=True)
|
203 |
+
def _(mo):
|
204 |
+
mo.md(r"""When you select points in the scatterplot, Marimo automatically passes those indices into this cell. Here, we render a preview of the corresponding face images using `matplotlib`, along with a table of all selected metadata β making it easy to inspect clustering quality or outliers at a glance.""")
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
return
|
206 |
|
207 |
|
208 |
@app.cell
|
209 |
+
def _(chart, mo):
|
210 |
+
table = mo.ui.table(chart.value)
|
211 |
+
return (table,)
|
212 |
|
213 |
|
214 |
+
@app.cell
|
215 |
+
def _(X, chart, h, mo, table, w):
|
216 |
+
def show_images(indices, max_images=6):
|
217 |
+
import matplotlib.pyplot as plt
|
218 |
+
|
219 |
+
indices = indices[:max_images]
|
220 |
+
images = X.reshape((-1, h, w))[indices]
|
221 |
+
fig, axes = plt.subplots(1, len(indices))
|
222 |
+
fig.set_size_inches(12.5, 1.5)
|
223 |
+
if len(indices) > 1:
|
224 |
+
for im, ax in zip(images, axes.flat):
|
225 |
+
ax.imshow(im, cmap="gray")
|
226 |
+
ax.set_yticks([])
|
227 |
+
ax.set_xticks([])
|
228 |
+
else:
|
229 |
+
axes.imshow(images[0], cmap="gray")
|
230 |
+
axes.set_yticks([])
|
231 |
+
axes.set_xticks([])
|
232 |
+
plt.tight_layout()
|
233 |
+
return fig
|
234 |
+
|
235 |
+
def show_selected():
|
236 |
+
return (
|
237 |
+
show_images(list(chart.value["index"]))
|
238 |
+
if not len(table.value)
|
239 |
+
else show_images(list(table.value["index"]))
|
240 |
+
)
|
241 |
|
242 |
+
mo.hstack([chart, show_selected() if len(chart.value) else ""])
|
243 |
+
return show_images, show_selected
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
244 |
|
245 |
|
246 |
+
@app.cell
|
247 |
+
def _():
|
248 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
|
250 |
|
251 |
if __name__ == "__main__":
|