Skip to content

Notebooks

Jupyter notebooks as documentation pages

This page is a Jupyter notebook (notebooks.ipynb), rendered as Markdown. Thus, Markdown cells support the same extensions as other pages, e.g., citations [Fang et al., 2004].

Code and Text Outputs

Code cells look like other code blocks, with prompts like in Jupyter. Printed text and the cell's result are outputs:

In [1]:
axioms = ["TFC1", "TFC3", "LNC1"]
print(f"{len(axioms)} axioms: {', '.join(axioms)}")
3 axioms: TFC1, TFC3, LNC1
In [2]:
{axiom: len(axiom) for axiom in axioms}
Out[2]:
{'TFC1': 4, 'TFC3': 4, 'LNC1': 4}

A cell can print text and return a result:

In [3]:
print("Counting characters...")
sum(len(axiom) for axiom in axioms)
Counting characters...
Out[3]:
12

Logs and warnings (stderr) are not shown:

In [4]:
import warnings

warnings.warn("This warning is not shown.")
print("But this text is.")
But this text is.

Errors show the traceback:

In [5]:
axioms.index("TFC2")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 axioms.index("TFC2")

ValueError: 'TFC2' is not in list

Magics and Shell Commands

In [6]:
%%time
sorted(axioms, key=len)
CPU times: user 5 μs, sys: 1 μs, total: 6 μs
Wall time: 7.87 μs
Out[6]:
['TFC1', 'TFC3', 'LNC1']
In [7]:
!echo TFC1 TFC3 LNC1 | wc -w
3

Data Frames

Data frames look like other tables:

In [8]:
from pandas import DataFrame

df = DataFrame(
    {
        "axiom": axioms,
        "consistency": [0.62, 0.55, 0.58],
    }
)
df
Out[8]:
axiom consistency
0 TFC1 0.62
1 TFC3 0.55
2 LNC1 0.58

Also with a named index:

In [9]:
df.set_index("axiom")
Out[9]:
consistency
axiom
TFC1 0.62
TFC3 0.55
LNC1 0.58

And with multiple index levels:

In [10]:
DataFrame(
    {
        "group": ["term frequency", "term frequency", "length"],
        "axiom": axioms,
        "consistency": [0.62, 0.55, 0.58],
        "coverage": [0.31, 0.12, 0.44],
    }
).set_index(["group", "axiom"])
Out[10]:
consistency coverage
group axiom
term frequency TFC1 0.62 0.31
TFC3 0.55 0.12
length LNC1 0.58 0.44

Plots

In [11]:
%matplotlib inline
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3))
ax.bar(df["axiom"], df["consistency"])
ax.set_ylabel("Consistency")
plt.show()

png

Vector graphics:

In [12]:
%config InlineBackend.figure_formats = ['svg']

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(df["axiom"], df["consistency"], marker="o")
ax.set_ylabel("Consistency")
plt.show()

svg

Maths

Markdown cells can contain maths, inline, like \(tf(t, d)\), or as blocks:

\[ \mathrm{TFC1}: \quad tf(t, d_1) > tf(t, d_2) \Rightarrow s(q, d_1) > s(q, d_2) \]

Rich Outputs

In [13]:
from IPython.display import HTML, Markdown, Math, display

display(Markdown("Markdown output with **bold** text and a [link](https://webis.de/)."))
display(HTML('<p>HTML output with a <span class="badge">badge</span>.</p>'))
display(
    Math(
        r"\mathrm{TFC1}: \quad tf(t, d_1) > tf(t, d_2) \Rightarrow s(q, d_1) > s(q, d_2)"
    )
)

Markdown output with bold text and a link.

HTML output with a badge.

\(\displaystyle \mathrm{TFC1}: \quad tf(t, d_1) > tf(t, d_2) \Rightarrow s(q, d_1) > s(q, d_2)\)

Widgets

Progress bars:

In [14]:
from tqdm.auto import tqdm

for axiom in tqdm(axioms):
    pass
100% 3/3 [00:00<00:00, 760.48it/s]

Interactive widgets are shown as they were saved, but disabled:

In [15]:
from ipywidgets import IntSlider

IntSlider(value=3, min=1, max=10, description="Top k:")
Out[15]:
Top k:3
In [16]:
from ipywidgets import Button, Checkbox, Dropdown, HBox, Text, ToggleButtons, VBox

VBox(
    [
        Dropdown(options=["BM25", "TF-IDF", "QL"], value="BM25", description="Model:"),
        ToggleButtons(options=["Title", "Body", "Both"], value="Both"),
        Text(value="formal axioms", description="Query:"),
        HBox(
            [Checkbox(value=True, description="Stemming"), Button(description="Search")]
        ),
    ]
)
Out[16]:
Model:Query:
In [17]:
from ipywidgets import interact


@interact(k=(1, 3))
def top(k=2):
    return df.nlargest(k, "consistency")
k2
axiom consistency
0 TFC1 0.62
2 LNC1 0.58

References

Hui Fang, Tao Tao, and ChengXiang Zhai. A formal study of information retrieval heuristics. In SIGIR 2004: Proceedings of the 27th Annual International ACM SIGIR Conference on Research and Development in Information Retrieval, Sheffield, UK, July 25-29, 2004, pages 49–56, 2004. ACM. [] [doi]
@inproceedings{fang2004formal,
  author       = {Hui Fang and
                  Tao Tao and
                  ChengXiang Zhai},
  title        = {A formal study of information retrieval heuristics},
  booktitle    = {{SIGIR} 2004: Proceedings of the 27th Annual International {ACM} {SIGIR}
                  Conference on Research and Development in Information Retrieval,
                  Sheffield, UK, July 25-29, 2004},
  pages        = {49--56},
  publisher    = {{ACM}},
  year         = {2004},
  url          = {https://doi.org/10.1145/1008992.1009004},
  doi          = {10.1145/1008992.1009004}
}