A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add example notebook on embedding google scholar (#488)
Akshay Agrawal6e7d3204e5ad
diff --git a/examples/embeddings/debugging_embeddings.py b/examples/embeddings/debugging_embeddings.pyindex 15c8b816f6..f9f42a46a9 100644--- a/examples/embeddings/debugging_embeddings.py+++ b/examples/embeddings/debugging_embeddings.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.1.0"+__generated_with = "0.1.68"app = marimo.App()@@ -10,8 +10,8 @@ def __(mo):"""# Sanity-Checking Embeddings- This app shows you the basics of sanity-checking an embedding made with- the `PyMDE` library. We'll use MNIST as a case study.+ This notebook shows you the basics of sanity-checking an embedding made+ with the `PyMDE` library. We'll use MNIST as a case study.""")return@@ -21,9 +21,9 @@ def __(mo):def __(mo):mo.md("""- We'll start by making a simple neighborhood-preserving embedding. This+ We'll start by making a simple neighborhood-preserving embedding. Thismeans that we'll try to identify pairs of images that are similar, using- a heuristic, and we'll tell PyMDE to place these pairs near each other in+ a heuristic, and we'll tell PyMDE to place these pairs near each other inthe embedding.""")@@ -128,8 +128,8 @@ def __(mo, ready):## Pairs with highest and lowest distortionLet's visualize a few pairs of images with low distortion (meaning they- were similar and placed near each other by the embedding) and with high- distortion (meaning they were similar but the embedding failed to place+ were similar and placed near each other by the embedding) and with high+ distortion (meaning they were similar but the embedding failed to placethem near each other).""") if ready else None@@ -170,8 +170,8 @@ def __(mo, ready):Notice that some of these pairs of images are actually not the same digit;we told our embedding to put them close together, but the embedding refusedto do so (in some cases, rightly so!). In other cases, the images in a pair- do depict the same digit, but are very strangely drawn. In a very real- sense, these pairs can be considered to be **outliers** in our original+ do depict the same digit, but are very strangely drawn. In a very real+ sense, these pairs can be considered to be **outliers** in our originaldata.""") if ready else Nonediff --git a/examples/embeddings/google_scholar.py b/examples/embeddings/google_scholar.pynew file mode 100644index 0000000000..1f6ba07c88--- /dev/null+++ b/examples/embeddings/google_scholar.py@@ -0,0 +1,159 @@+import marimo++__generated_with = "0.1.68"+app = marimo.App()+++def _(mo):+ mo.md(+ r"""+ # Embedding Google Scholar++ This notebook shows how to use the function `pymde.preserve_distances` to+ produce embeddings of networks, in which the goal is to preserve the+ shortest-path distances in the network.++ It uses an academic co-authorship network collected from Google Scholar as+ a case study.+ """+ )+ return+++def _():+ import pymde++ import matplotlib.pyplot as plt+ import numpy as np+ import torch+ return np, plt, pymde, torch+++def _(pymde):+ gscholar = pymde.datasets.google_scholar()+ return gscholar,+++def _(gscholar):+ scholars_df = gscholar.other_data['dataframe']+ scholars_df+ return scholars_df,+++def _(gscholar):+ coauthorship_graph = gscholar.data+ return coauthorship_graph,+++def _(coauthorship_graph):+ f'{coauthorship_graph.n_items:,} authors'+ return+++def _(coauthorship_graph):+ f'{coauthorship_graph.n_edges:,} edges'+ return+++def _(coauthorship_graph):+ print(f'edge density: {100*(coauthorship_graph.n_edges / (coauthorship_graph.n_all_edges)):.2f} percent')+ return+++def _(DEVICE, coauthorship_graph, pymde):+ mde = pymde.preserve_distances(+ data=coauthorship_graph,+ loss=pymde.losses.Absolute,+ max_distances=1e8,+ device=DEVICE,+ verbose=True)++ mde.embed(verbose=True)+ return mde,+++def _(mde, np, plt):+ plt.figure(figsize=(12, 3))+ original_distances = np.sort(mde.distortion_function.deviations.cpu().numpy())+ ax = plt.gca()+ plt.hist(original_distances, histtype='step', bins=np.arange(1, 11), density=True, cumulative=True)+ plt.xlim(1, 10)+ plt.xticks(np.arange(1, 11))+ plt.xlabel('graph distances')+ plt.show()+ return ax, original_distances+++def _(mde):+ mde.distortions_cdf()+ return+++def _(gscholar, mde):+ mde.plot(color_by=gscholar.attributes['coauthors'], color_map='viridis',+ figsize_inches=(12., 12.), background_color='k')+ return+++def _(coauthorship_graph, gscholar, mde, plt, torch):+ edges = coauthorship_graph.edges+ indices = torch.randperm(edges.shape[0])[:1000]+ edges = edges[indices].cpu().numpy()++ _ax = mde.plot(edges=edges, color_by=gscholar.attributes['coauthors'], color_map='viridis', figsize_inches=(12, 12))+ plt.tight_layout()+ _ax+ return edges, indices+++def _(gscholar):+ from matplotlib import colors+++ legend = {+ 'bio': colors.to_rgba('tab:purple'),+ 'ai': colors.to_rgba('tab:red'),+ 'cs': colors.to_rgba('tab:cyan'),+ 'ee': colors.to_rgba('tab:green'),+ 'physics': colors.to_rgba('tab:orange')+ }+ scholar_disciplines_df = gscholar.other_data['disciplines']+ topic_colors = [legend[code] for code in scholar_disciplines_df['topic']]+ return colors, legend, scholar_disciplines_df, topic_colors+++def _(mde, pymde, scholar_disciplines_df, topic_colors):+ pymde.plot(mde.X[scholar_disciplines_df['node_id'].values], colors=topic_colors,+ figsize_inches=(12, 12), background_color='black')+ return+++def __(torch):+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'+ return DEVICE,+++def _():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()