AI voor iedereen

Zoeken

Zoek in hoofdstukken en demo's

🌌 Embeddings in Python

Zinnen worden getallen, en deze cursus wordt data: een kaart van al zijn secties, onderwerpen die k-gemiddelden en hiërarchisch clusteren zelf vinden, een zoekmachine die op betekenis zoekt, en als extra een studieassistent die eerst in de cursus opzoekt en dan antwoordt, met links.

Uitvoeren in Google Colab

Colab vereist een Google-account, maar je kan de notebook ook .

Hoofdstuk nog niet online. Deze notebook is af, maar het hoofdstuk waar ze bij hoort staat nog niet online. Links naar dat hoofdstuk werken dus misschien nog niet, en voorlopig is ze geen examenleerstof.

Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.

An embedding turns a text into a list of numbers, in such a way that texts with a similar meaning get similar numbers (see the chapter Embeddings). In this notebook you put that to work on a text you know well: this course. You draw a map of all its sections, you let the computer find its topics without telling it what the chapters are, and you build a search engine that searches on meaning instead of on words.

You will:

  1. 🔢 turn sentences into numbers, and see which ones lie close together;
  2. 📚 collect the text of the course and cut it into pieces;
  3. 🗺️ draw a map of the course, and let 🫧 k-means and 🌲 hierarchical clustering find its topics;
  4. 🔍 search the course on meaning;
  5. 🤖 as an extra, build a study assistant that looks things up in the course before it answers.

Prior knowledge: the chapter Embeddings, and k-means and hierarchical clustering from the chapter Clustering. The extra part at the end builds on tool calling from the chapter Large language models.

Estimated time: about 40 minutes. Everything runs on Colab's free computer; only the extra part needs a free key from OpenRouter.

This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/embeddings, and you can open it directly in Google Colab (externe link).

🚀 First time in a notebook?

Then the short introductory notebook explains everything step by step. The most important things:

  1. Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
  2. Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
  3. Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.

Prefer not to use Google? Download the notebook file and open it in Jupyter (externe link) or Visual Studio Code (externe link). For the extra part at the end, put your OpenRouter key in an environment variable OPENROUTER_API_KEY, or type it in when the notebook asks for it.

🐍 Python in this notebook

New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:

CodeMeaning
model.encode(texts)Turns a list of texts into a table of numbers: one row, a vector, per text.
vectors @ vectors.TA matrix product: the dot product of every vector with every other vector, all at once.
np.argsort(-scores)[:5]The positions of the five highest scores.
requests.get(url).textDownloads a web page, as text in HTML.
BeautifulSoup(page, "html.parser")Reads that HTML, so that you can ask for parts of the page, such as .find("article") or .find_all("h2").
re.findall(r"...", text)Finds every piece of a text that matches a pattern (a regular expression).
pd.DataFrame(rows)A table made from a list of dictionaries, one row per dictionary. table[table.chapter == name] keeps the rows you want.
px.scatter(table, x="x", y="y", color="chapter")An interactive plot (plotly): hover over a dot to see what it is.
question = "..." # @param {type:"string"}In Colab, a text field next to the code, as in the introductory notebook.

🔢 Sentences as numbers

An embedding model reads a text and returns a vector: a fixed list of numbers. This notebook uses granite-embedding-107m-multilingual (externe link), a small model from IBM (107 million weights) that knows twelve languages, among them English and Dutch, and that runs fine on Colab's computer without a graphics card. The first time, Colab downloads it: about 230 MB.

# Colab already has these packages; elsewhere, this installs them
%pip install --quiet sentence-transformers plotly beautifulsoup4 openai markdown
import getpass
import html
import json
import os
import re
import textwrap

import markdown
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import requests
from bs4 import BeautifulSoup
from IPython.display import HTML, display
from openai import OpenAI
from scipy.cluster.hierarchy import dendrogram, linkage
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE
model = SentenceTransformer("ibm-granite/granite-embedding-107m-multilingual")
model.float()   # ordinary floats: the model is stored in a shorter number format that many processors compute slowly

vector = model.encode("The train to Leuven is late again.")
print(vector.round(3))
print("Size of the vector:", vector.shape)
Uitvoer
[ 0.074  0.063 -0.003  0.029  0.032 -0.004  0.022 -0.008  0.057 -0.025
 -0.085  0.049  0.061  0.015  0.029  0.034 -0.003 -0.011  0.003 -0.01
  0.002  0.033  0.021  0.051 -0.205  0.035  0.059  0.02   0.033  0.066
  0.043  0.057  0.04  -0.049  0.094  0.04   0.022 -0.007  0.022  0.051
  0.02   0.06   0.026  0.009  0.033 -0.048 -0.047  0.063  0.015 -0.043
  0.014 -0.012  0.048 -0.027  0.055 -0.025  0.024  0.04   0.009  0.024
  0.025 -0.015  0.09   0.036  0.04  -0.029  0.11   0.039  0.013  0.028
  0.052  0.006  0.035 -0.006  0.062  0.031 -0.024  0.011  0.013  0.043
  0.061  0.034  0.052  0.094  0.001  0.089 -0.039  0.044 -0.018 -0.003
  0.008  0.017  0.068  0.002  0.046  0.041 -0.191 -0.056 -0.     0.021
  0.013 -0.018  0.111  0.028  0.031  0.061  0.046  0.022  0.059  0.022
  0.112 -0.029  0.016  0.01   0.014  0.04   0.008  0.026  0.108 -0.048
  0.074  0.038  0.071  0.012  0.024 -0.015  0.032 -0.011 -0.013  0.08
  0.036  0.025  0.037  0.001  0.016 -0.031  0.042 -0.006 -0.088  0.068
  0.093 -0.043  0.039  0.031 -0.07  -0.    -0.042  0.036  0.021  0.038
  0.01   0.043  0.016 -0.019 -0.038  0.01   0.043  0.055  0.026  0.042
 -0.009  0.087  0.064  0.048  0.064  0.013  0.07  -0.025  0.097  0.017
 -0.025 -0.015  0.036  0.039  0.07  -0.025  0.054  0.033 -0.011 -0.039
 -0.056  0.028 -0.034  0.062  0.068  0.009  0.094 -0.121  0.017  0.028
  0.035  0.072  0.063  0.088 -0.142  0.009 -0.04   0.058  0.015  0.013
  0.004  0.073 -0.078 -0.018  0.03   0.048  0.076  0.053  0.079  0.021
  0.062 -0.024  0.037  0.05  -0.07   0.029  0.047  0.053  0.067  0.014
  0.116  0.052  0.008 -0.001  0.035  0.041  0.023 -0.086  0.007 -0.081
  0.025  0.019 -0.     0.025 -0.006 -0.046  0.015  0.012  0.01   0.03
  0.047 -0.089  0.003  0.003  0.014 -0.017  0.096  0.054  0.08   0.008
  0.091  0.019  0.122 -0.004 -0.002 -0.044  0.027  0.022 -0.017  0.046
 -0.05   0.053  0.006  0.124  0.016 -0.018 -0.074 -0.08   0.023  0.005
  0.005  0.004 -0.164  0.001  0.03   0.005  0.063 -0.011  0.006  0.049
  0.05  -0.059  0.046 -0.005 -0.047 -0.016 -0.03   0.013 -0.021 -0.068
  0.011 -0.002  0.025 -0.015  0.034  0.049  0.025  0.053  0.047 -0.013
  0.046 -0.034  0.022  0.129  0.146  0.02  -0.055  0.031  0.061  0.032
 -0.035  0.028 -0.022  0.07   0.059  0.01  -0.097  0.071  0.05   0.038
 -0.023 -0.028  0.105 -0.001  0.007  0.004  0.053  0.049  0.022  0.022
 -0.037 -0.002  0.013 -0.017  0.039  0.042 -0.049  0.044 -0.021  0.005
  0.022  0.128  0.05   0.024 -0.035  0.031  0.015  0.068  0.006  0.118
 -0.022  0.068 -0.015 -0.129  0.017  0.024  0.008 -0.008  0.057  0.041
 -0.057  0.033 -0.005 -0.045  0.018  0.008  0.086 -0.03   0.097  0.042
  0.075 -0.039  0.028  0.093  0.006 -0.013  0.004  0.025 -0.01   0.009
  0.107 -0.065 -0.064  0.02 ]
Size of the vector: (384,)

One sentence, 384 numbers. On their own they mean nothing to you, and that's fine: what matters is which vectors lie close to each other. As a measure, this notebook uses the cosine similarity: 1 when two vectors point in the same direction, around 0 when they have nothing to do with each other. With normalize_embeddings=True, every vector gets length 1, and then the cosine similarity is simply the dot product a @ b. For a whole list of vectors, vectors @ vectors.T gives every pair at once:

sentences = [
    "The train to Leuven is late again.",
    "My bus never shows up on time.",
    "It will rain all day tomorrow.",
    "Take an umbrella, a storm is coming.",
    "The exam was much harder than I expected.",
    "I failed my statistics test.",
    "De trein naar Leuven heeft weer vertraging.",
]
vectors = model.encode(sentences, normalize_embeddings=True)
similarity = vectors @ vectors.T

figure, axes = plt.subplots(figsize=(8, 4.5))
axes.imshow(similarity, cmap="Blues", vmin=0.4, vmax=1)
for row in range(len(sentences)):
    for column in range(len(sentences)):
        value = similarity[row, column]
        axes.text(column, row, f"{value:.2f}", ha="center", va="center", fontsize=9, color="white" if value > 0.8 else "black")
axes.set_xticks(range(len(sentences)), [str(number) for number in range(1, len(sentences) + 1)])
axes.set_yticks(range(len(sentences)), [f"{number}. {sentence}" for number, sentence in enumerate(sentences, 1)])
plt.show()
Uitvoer

Every sentence is most similar to the other one on the same topic, also when they share hardly any words, like late again and never shows up on time. That's what a search on keywords can't do. The Dutch sentence lands right on top of its English translation (0.91): the model learned both languages in one space. And notice that no score comes near 0. Even sentences about different topics score around 0.5 here: only the order counts, and every model has a scale of its own.

Now one word with two meanings, and one sentence turned around:

def similarity_of(a, b):
    # How close two texts lie: the cosine similarity of their vectors
    vector_a, vector_b = model.encode([a, b], normalize_embeddings=True)
    return float(vector_a @ vector_b)


pairs = [
    ("She sat on the bank of the river.", "She sat by the water."),
    ("She sat on the bank of the river.", "She took money out of the bank."),
    ("I really like this course.", "This course is great fun."),
    ("I really like this course.", "I don't like this course at all."),
]
for a, b in pairs:
    print(f"{similarity_of(a, b):.2f}   {a}  |  {b}")
Uitvoer
0.85   She sat on the bank of the river.  |  She sat by the water.
0.74   She sat on the bank of the river.  |  She took money out of the bank.
0.88   I really like this course.  |  This course is great fun.
0.91   I really like this course.  |  I don't like this course at all.

The bank of a river lands closer to the water than to the bank where you take out money: the model reads the whole sentence, not only the word. But in the last two lines it goes wrong: I don't like this course at all scores higher than This course is great fun. Both sentences are about liking this course, and the don't hardly counts. An embedding captures what a text is about much better than what it claims. Keep that in mind for the search engine later: it finds the sections on the right topic, but you (or a language model) still have to read what they say.

📚 The course as data

Now a real text: the course itself. Every chapter is a web page, and every heading on it has an address of its own, such as …/en/history#the-first-ai-winter. Which chapters are there? Most websites list their pages for search engines in a file sitemap.xml (externe link). This cell keeps the English chapters from it:

SITE = "https://ai.kuleuven.be/aivooriedereen"
# Tells the website who is asking. Reusing this code for another website? Then describe yourself instead.
HEADERS = {"User-Agent": "Student running the AI voor Iedereen embeddings notebook "
                         "(https://ai.kuleuven.be/aivooriedereen/en/notebook/embeddings)"}

sitemap = requests.get(f"{SITE}/sitemap.xml", headers=HEADERS).text
chapters = [path for path in re.findall(r"aivooriedereen(/en/[a-z-]+)</loc>", sitemap)
            if path not in ("/en/demo", "/en/notebook", "/en/about")]
print(len(chapters), "chapters:", " ".join(chapters))
Uitvoer
15 chapters: /en/history /en/dimensions /en/search /en/heuristic-search /en/game-trees /en/logic /en/probability /en/bayesian-networks /en/naive-bayes /en/nearest-neighbors /en/support-vector-machines /en/decision-trees /en/regression /en/clustering /en/model-evaluation

A web page is written in HTML: text between tags, such as <h2> for a heading and <p> for a paragraph. read_chapter takes the <article> out of a chapter page (the text, without menus and buttons), turns every formula back into the LaTeX it was written in, and cuts the text at every heading. Every section keeps its link: the address of the page, with the id of its heading after the #.

def read_chapter(path):
    # The sections of one chapter: the text under every heading, with its chapter, heading and link
    page = BeautifulSoup(requests.get(SITE + path, headers=HEADERS).content, "html.parser")  # the bytes: the page says how to read them
    article = page.find("article")                                     # the chapter itself, without menus
    for tag in article.find_all(["script", "style", "svg", "button"]) + article.find_all(class_="sr-only"):
        tag.decompose()                                                  # no code, drawings, buttons or text for screen readers
    for formula in article.find_all(class_="katex"):                    # a formula: keep the LaTeX
        latex = formula.find("annotation")
        formula.replace_with(f"${latex.get_text()}$" if latex else "")
    for cell in article.find_all(["td", "th"]):
        cell.append(" | ")                                               # a table: keep its cells apart
    for block in article.find_all(["p", "div", "li", "tr", "figcaption", "blockquote"]):
        block.append("\n")                                               # a new line after every paragraph
    chapter = article.find("h1").get_text(" ", strip=True)
    for heading in article.find_all(["h2", "h3", "h4", "h5"]):          # mark every heading in the text
        heading.replace_with(f"\n@@{heading.get('id')}@@{heading.get_text(' ', strip=True)}\n")
    parts = re.split(r"\n@@(.*?)@@(.*)\n", article.get_text())           # and cut the text at those marks
    sections = []
    for anchor, heading, text in zip(parts[1::3], parts[2::3], parts[3::3]):
        text = re.sub(r"[ \t]+", " ", text)
        text = re.sub(r"\s*\n\s*", "\n", text).strip()                  # no empty lines
        sections.append({"chapter": chapter, "heading": heading, "url": f"{SITE}{path}#{anchor}", "text": text})
    return sections


sections = pd.DataFrame([section for path in chapters for section in read_chapter(path)])
print(len(sections), "sections,", sections.text.str.split().str.len().sum(), "words")
examples = sections[sections.text != ""].head(3)
HTML(examples.assign(text=examples.text.str[:150].str.replace("\n", " ") + " …").to_html(index=False))
Uitvoer
398 sections, 78956 words
chapter heading url text
📜 History of AI 🏠 AI in everyday life https://ai.kuleuven.be/aivooriedereen/en/history#ai-in-everyday-life How many different AI systems have you used yourself today? None at all? One? A couple? More than five? The real number is probably much higher than y …
📜 History of AI 🎯 The shifting boundary of intelligence https://ai.kuleuven.be/aivooriedereen/en/history#the-shifting-boundary-of-intelligence There is something peculiar about the way we think about AI. As soon as a computer can do something we used to consider "intelligent", we stop calling …
📜 History of AI 📖 Definitions https://ai.kuleuven.be/aivooriedereen/en/history#definitions What sets AI apart from "ordinary" software? The difference lies in the kind of problem you are solving. 💻 Standard programming: an "ordinary" compute …

Most sections are a few paragraphs long, but some run to more than 800 words. That's a problem for two reasons. The model only reads the first 512 tokens of a text (roughly 400 words), and silently ignores the rest. And one vector for a long section about three things is a blur of all three. So the long sections are cut into chunks of at most 200 words, between two paragraphs. Every chunk also gets its heading in front, so that a chunk that starts with That's why … still says what it's about. Not the name of its chapter, though: you'll see why in the part about k-means.

Libraries such as LangChain (RecursiveCharacterTextSplitter) and chonkie do the same: they cut at the largest boundary that still fits, a paragraph, then a sentence, then a word. Some can also cut on meaning, wherever two sentences in a row lie far apart. On the English chapters of this course, such a semantic chunker found only 14% of the places where the authors put a heading; cutting at random found 8%. For a text with headings, the headings are the better cut. Semantic chunking is for text without any structure, such as the transcript of a lecture.

def cut(text, max_words=200):
    # A long text in pieces of at most max_words words, cut between two paragraphs
    pieces, current = [], []
    for paragraph in text.split("\n"):
        if current and len(" ".join(current + [paragraph]).split()) > max_words:
            pieces.append("\n".join(current))
            current = []
        current.append(paragraph)
    return pieces + ["\n".join(current)]


chunks = []
for section in sections.itertuples():
    if len(section.text.split()) < 15:                                  # only a heading, the text sits below the next one
        continue
    for piece in cut(section.text):
        chunks.append({"chapter": section.chapter, "heading": section.heading, "url": section.url,
                       "text": f"{section.heading}\n{piece}"})
chunks = pd.DataFrame(chunks)
words = chunks.text.str.split().str.len()
print(len(chunks), "chunks, median", int(words.median()), "words, the longest", words.max())
Uitvoer
575 chunks, median 155 words, the longest 208

Now every chunk becomes a vector. That's the slowest step of the notebook: about a minute on Colab's computer.

vectors = model.encode(chunks.text.tolist(), normalize_embeddings=True, batch_size=16)
print(vectors.shape)
Uitvoer
(575, 384)

🗺️ A map of the course

Every chunk is now a point in a space of 384 dimensions. To see them, t-SNE (externe link) squashes those 384 numbers into 2, and tries to keep points that were neighbors close together on the map. It's a picture for your eyes, not something to compute with: the size of an island and the distance between two islands mean little. draw_map draws one dot per chunk, with the name of every chapter in the middle of its dots. Hover over a dot to see its heading and its first words.

xy = TSNE(n_components=2, metric="cosine", random_state=0).fit_transform(vectors)
chunks["x"], chunks["y"] = xy[:, 0], xy[:, 1]
chunks["preview"] = [html.escape(textwrap.fill(text.split("\n")[1][:150], 60)).replace("\n", "<br>") + " …" for text in chunks.text]


def draw_map(color):
    # The map of the course: a dot per chunk, colored by the column `color`, with every chapter's name in the middle of its dots
    figure = px.scatter(chunks, x="x", y="y", color=color, hover_name="heading", height=390, template="plotly_white",
                        hover_data={"chapter": True, "preview": True, "x": False, "y": False},
                        color_discrete_sequence=px.colors.qualitative.Dark24)
    for name, middle in chunks.groupby("chapter")[["x", "y"]].mean().iterrows():
        figure.add_annotation(x=middle.x, y=middle.y, text=name, showarrow=False, font_size=11, bgcolor="rgba(255,255,255,0.7)")
    figure.update_layout(showlegend=False, xaxis_visible=False, yaxis_visible=False, margin=dict(l=0, r=0, t=0, b=0))
    figure.show()


draw_map("chapter")
Uitvoer

Most chapters form an island of their own, and nobody told the model which chunk belongs to which chapter: it only read the text. Where two islands touch, the chapters share a topic.

Not every chapter forms an island. The soft pink dots of Dimensions of AI are spread all over the map: that chapter gives an overview of the whole field, and many of its parts land next to the chapter that goes deeper into their topic. Hover over them: the Analogizers lie next to Nearest Neighbors, the Bayesians next to Probability, and reinforcement learning next to Game Trees.

One spot looks odd: a tight knot of dots in many colors. Hover over it: it's the feedback form at the end of every chapter, every time the same text, so every time the same vector. A map like this is a quick way to find such duplicates in your data. They don't belong in a search engine, so out they go:

feedback = chunks.heading.str.endswith("Feedback").to_numpy()
print(feedback.sum(), "chunks are the feedback form")
vectors, chunks = vectors[~feedback], chunks[~feedback].reset_index(drop=True)
Uitvoer
15 chunks are the feedback form

🫧 Topics with k-means

Now the computer looks for groups itself, with k-means from the chapter Clustering. It works on all 384 numbers of every chunk, not on the squashed map. For k, take the number of chapters: then you can check whether k-means finds the chapters again. To see what a cluster is about, it gets the heading of the chunk closest to its center as its name.

k = chunks.chapter.nunique()
kmeans = KMeans(n_clusters=k, n_init=10, random_state=0).fit(vectors)

topics = {}
for cluster in range(k):
    members = np.flatnonzero(kmeans.labels_ == cluster)
    closest = members[np.argmax(vectors[members] @ kmeans.cluster_centers_[cluster])]
    name = chunks.heading[closest]
    topics[cluster] = name if name not in topics.values() else f"{name} ({cluster})"   # two clusters, one name
chunks["topic"] = [topics[cluster] for cluster in kmeans.labels_]

rows = []
for topic, group in chunks.groupby("topic"):
    counts = group.chapter.value_counts()
    rows.append({"topic": topic, "chunks": len(group), "mostly from": counts.index[0], "own": counts.iloc[0]})
overview = pd.DataFrame(rows)
overview["share"] = overview.own / overview.chunks
print(f"{overview.own.sum() / len(chunks):.0%} of the chunks are in a cluster that mostly holds their own chapter")
overview = overview.sort_values("share", ascending=False).drop(columns="own")
HTML(overview.to_html(index=False, formatters={"share": "{:.0%}".format}))
Uitvoer
67% of the chunks are in a cluster that mostly holds their own chapter
topic chunks mostly from share
🌿 What is a decision tree? 30 🌳 Decision Trees 97%
🔭 Looking further ahead in Connect Four 37 ♟️ Game Trees 92%
🕊️ Euclidean heuristic 37 🧭 Heuristic Search 92%
🎉 A party for picky guests 25 🧩 Logic 88%
🦍 The brute force of basic search algorithms 40 🔍 Search Algorithms 80%
💭 Symbolic AI: the first wave 41 📜 History of AI 76%
🤔 Where do the arrows and probabilities come from? 43 🕸️ Bayesian Networks 74%
🔢 How many clusters? 29 🫧 Clustering 69%
🔍 Conditional probability 39 🎲 Probability 64%
⚙️ How does the model learn its weights? 49 📈 Regression 57%
🔄 The learning process 36 🗺️ Dimensions of AI 53%
📐 🔍 How a SAT solver searches 29 🧩 Logic 52%
🎚️ Choosing the number of neighbors 27 🏘️ Nearest Neighbors 48%
🔍 What the line tells you 37 🛡️ Support Vector Machines 46%
🎚️ From probability to decision 61 🏅 Model Evaluation 38%

In this run, 67% of the chunks land in a cluster that mostly holds their own chapter. Some chapters come out almost untouched, as a cluster of their own. The clusters at the bottom of the table are more interesting: there, k-means put chunks from several chapters together, because they're about the same thing. Look inside the cluster that mixes the most:

mixed = overview.topic.iloc[-1]                                              # the cluster with the most mixed chapters
print(mixed)
inside = chunks[chunks.topic == mixed].groupby("chapter").heading.agg(lambda headings: " · ".join(sorted(set(headings))))
HTML(inside.to_frame().to_html())
Uitvoer
🎚️ From probability to decision
heading
chapter
🌳 Decision Trees 🌡️ Entropy · 📐 🎲 The Gini index: an alternative to entropy · 📐 🎲 The entropy formula · 🤔 What makes a question good?
🎲 Probability ⚠️ Pitfalls: when probabilities mislead · 🎯 Calibration · 🔁 Turning the arrow around · 🪤 Simpson's paradox: combining groups can reverse a trend
🏅 Model Evaluation ✂️ Data splits · 🎚️ Threshold · 🎯 Evaluation metrics · 🎲 How reliable is your score? · 👥 Human evaluation · 💯 Accuracy · 📂 Training, validation, test · 📐 ↔️ Calculating the mean and the standard deviation · 📐 📈 ROC curves and AUC · 🔬 The complete evaluation workflow · 🕸️ Overfitting: too complex · 🕹️ Demos · 🗂️ Confusion matrix · 🚦 False positive vs false negative · 🚰 Data leakage
🏘️ Nearest Neighbors ✂️ Data splits · 📋 Confusion matrix · 📝 Do not test on your training data · 🧐 Choosing k
👶 Naive Bayes 🎚️ From probability to decision · 🎲 Why "naive"? · 🏋️ Practice · 🏷️ Classification · 💪 Strengths · 🕹️ Demos · 🚨 Limitations · 🧭 When to use it? · 🩹 Smoothing
📈 Regression 🎯 Lowest error is not always highest accuracy · 🏷️ From numbers to label probabilities · 📐 🌀 Binary cross-entropy · 📐 🔢 Calculating the probability: step by step · 📐 🗂️ Multiple classes · 🧾 The calculation step by step · 🪛 When to use them?
🗺️ Dimensions of AI 🔢 Classification versus regression
🫧 Clustering 🔖 Labels are expensive

This one is hard to name. In this run, it puts the scores and thresholds of Model Evaluation together with entropy from Decision Trees, the label probabilities of Regression and much of Naive Bayes. Perhaps the model sees one topic in them, predicting a label and how sure you can be of it; perhaps k-means simply had a cluster left over. The clusters are always mathematically sound, but whether they're useful is up to you: interpreting them is the real work.

On the map, colored by cluster this time, you see where k-means cut across the chapters: an island in two colors, or one color spread over several islands.

draw_map("topic")
Uitvoer

Try it. Put the name of the chapter in front of every chunk as well: in the cell with cut, make it f"{section.chapter} > {section.heading}\n{piece}", and run the cells again from there. K-means then finds the chapters much better (about 90% instead of 70%), but not because it understands the course any better: every chunk now carries the answer. That's the mistake of a data leak, where the answer sneaks into the data, and it's why the chunks in this notebook only get their heading.

Here, the number of chapters was an obvious choice for k. For text without such a natural number, there's rarely one right k: it depends on how many topics you want to see (see k remains a choice).

🌲 A family tree of the chapters

K-means needs k in advance. Hierarchical clustering builds every grouping at once, from fine to coarse, and draws them as a dendrogram. On hundreds of chunks that tree gets unreadable, but on one average vector per chapter it becomes a family tree of the course:

names = list(chunks.chapter.unique())                                     # in the order of the course
averages = np.array([vectors[(chunks.chapter == name).to_numpy()].mean(axis=0) for name in names])
tree = linkage(averages, method="average", metric="cosine")

plt.figure(figsize=(8, 6))
dendrogram(tree, labels=[name.split(" ", 1)[1] for name in names], orientation="right")   # without the emoji
plt.xlabel("distance between the clusters (1 − cosine similarity)")
plt.show()
Uitvoer

Compare the tree with the menu on the left of the site. Many branches match: Search Algorithms, Heuristic Search and Game Trees (Reasoning), History and Dimensions (Introduction), and most of Machine Learning hangs together. Where the tree differs, it often has a point. Naive Bayes joins Probability and Bayesian Networks, because it's built on probabilities. Model Evaluation, at the very end of the menu, lands in the middle of Machine Learning: that's what it evaluates. Clustering stays apart from the rest of Machine Learning: it's the only chapter there that works without labels. Logic hangs on a long branch of its own: in this course, no other chapter looks much like it. And the search chapters join the rest only at the very top.

Which chapter would you have put elsewhere?

🔍 Searching on meaning

A search engine on meaning takes only a few lines: turn the question into a vector, and take the chunks with the highest dot product. The best hit shows its whole chunk; click the others to read theirs. Type another question in the field and run the cell again; in Colab it runs by itself when you change the question.

def search(question, k=5):
    # The k chunks that lie closest to the question, the best one first
    scores = vectors @ model.encode(question, normalize_embeddings=True)
    best = np.argsort(-scores)[:k]
    return chunks.iloc[best].assign(score=scores[best])


def show_results(results):
    # The results with a link to every section: the best one open, a click opens the whole chunk of the others
    rows = []
    for rank, row in enumerate(results.itertuples()):
        rows.append(f'<details{" open" if rank == 0 else ""}><summary style="cursor:pointer">{row.score:.2f} '
                    f'<a href="{row.url}" target="_blank">{html.escape(row.chapter)} › {html.escape(row.heading)}</a></summary>'
                    f'<div style="white-space:pre-wrap;max-width:50em;margin:4px 0 8px 1.2em;font-size:smaller">{html.escape(row.text)}</div></details>')
    display(HTML("".join(rows)))
question = "Why did AI research run out of money in the 1970s?"  # @param {type:"string"}
show_results(search(question))
Uitvoer
0.81 📜 History of AI › ❄️ The first AI winter
❄️ The first AI winter By the mid-1970s it had become clear that the early promises were too optimistic. Computers were too slow, memory too limited, and many problems turned out to be exponentially harder than expected. A damning report for the British government criticized the lack of progress, and governments in the UK and the US cut their funding drastically. This led to the first "AI winter", which lasted for the rest of the decade: a period in which funding dried up and the research field stagnated.
0.79 📜 History of AI › 🏷️ Artificial intelligence as a term
🏷️ Artificial intelligence as a term The term "artificial intelligence" is more than seventy years old. It was used for the first time in the proposal for a summer project at Dartmouth College in the United States. The project was organized by a handful of researchers who really did lay the foundations of many AI techniques. In their proposal they set out the following ambitious hypothesis: Every aspect of learning or any other feature of intelligence can in principle be so precisely described that a machine can be made to simulate it. They identified a number of areas of AI research that are still current today, among them neural networks, self-improvement (what we now call machine learning), the use of language, abstraction and even creativity.
0.76 📜 History of AI › 📜 History
📜 History The field of AI is more than 70 years old. In that time, one family after another from the 🗂️ overview above took the spotlight, in three big waves: first symbolic AI, then statistical models and today neural networks. Meanwhile, periods of high expectations, the AI summers, alternated with periods of disappointment, the AI winters. The timeline below sums it up. The background color shows which family dominated at the time, the curve how high expectations were (a rough estimate, not a measurement), and each pin is an event from this section. Try it out: Hover over a pin to see what happened then, and click it to read more. Look at the colors of the pins too: some ideas turned up decades before their own wave. 💭 Symbolic AI 📊 Statistical models 🧠 Neural networks expectations (rough estimate) ❄️AI winter
0.75 📜 History of AI › 🩺 Expert systems and the second AI winter
🩺 Expert systems and the second AI winter The 1980s saw the rise of expert systems: AI tools that use knowledge within a specific domain (medical diagnosis, say, or configuring computer systems) to carry out tasks at the level of a human expert. Although they were successful at first, they eventually proved too expensive to maintain and too rigid, which contributed to a second AI winter in the late 1980s.
0.74 📜 History of AI › 🎢 AI summers, AI winters and the hype cycle
🎢 AI summers, AI winters and the hype cycle As the 📜 timeline shows, the history of AI moves in cycles: a big breakthrough raises inflated expectations (an AI summer), and when those are not met, funding dries up and the field stagnates (an AI winter). That pattern is not unique to AI. The Gartner hype cycle describes how expectations around many new technologies develop: after a breakthrough they rise to a peak of inflated expectations, then they sink into a trough of disillusionment, and only then do they slowly climb to a realistic level, at which the technology delivers real value. An AI summer is such a peak, an AI winter such a trough. Careful: the curve describes society's expectations, not the actual value of the technology. Even in a trough, a technology can be useful. Our own rendering of the Gartner Hype Cycle model We are currently in the biggest AI summer ever: first around generative AI and by now mostly around the agentic AI above. If history teaches us anything, such a peak is indeed often followed by a correction.

The question says run out of money; the course says that governments cut their funding and that the funding dried up. Different words, the same meaning, and so the first hit is the section about the first AI winter. A few more to try: "Who first asked whether machines can think?", "How do I group my customers when nobody labeled them?" or "My model is perfect on the training data but bad on new data. Why?".

And in another language:

show_results(search("Hoe kies ik hoeveel clusters ik nodig heb?"))
Uitvoer
0.83 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? In data without clear groups there is no bend to see, and then the choice of $k$ is a decision you have to make: how many stations can the company afford, how many playlists do you want, how many customer segments can a marketing team handle?
0.79 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? The algorithm asks beforehand how many clusters there should be, and that choice of $k$ determines the result. Drag the $k$ slider below. With $k = 2$ two neighborhoods are lumped together, with $k = 3$ you get the three neighborhoods you saw yourself, and with $k = 4$ or more a real neighborhood is chopped into pieces. The chart next to the map helps with that choice. For every $k$ it shows how far a student lives from their station on average, each time after the algorithm has run to the end. More stations are always better for the average distance (with a station per room, everyone lives at distance zero), but the gain quickly gets smaller. From one to two and from two to three stations the distance drops sharply; a fourth station only gains a little. The bend in the curve looks like an elbow, and that is usually where a good $k$ lies: the elbow method. Click a point in the chart to choose that $k$. The elbow is an aid, not a law.
0.79 🫧 Clustering › 🌲 Hierarchical clustering
🌲 Hierarchical clustering K-means wants to know beforehand how many clusters there are. Hierarchical clustering turns that question around: it first builds up all the groupings, from very fine to very coarse, and you choose afterwards. The recipe is simple. You start with every point as its own cluster: eight rooms are then eight clusters of one. Then you repeatedly look for the two clusters that lie closest to each other and merge them into one cluster. You repeat that until everything is in one big cluster. You can measure how far apart two clusters lie as, for example, the average distance between their points. You draw the result as a dendrogram, a kind of family tree of your data. At the bottom every data point stands on its own, and every horizontal connection is a merge. The height of such a connection is the distance between the two clusters that come together there: low means they were very similar, high means you are gluing two different groups together. Eight rooms on the map, colored by cluster, and the dendrogram with all the merges. The dashed line cuts at 2.9 km and leaves three clusters.
0.78 🫧 Clustering › 🤔 k remains a choice
🤔 k remains a choice You have to say beforehand how many clusters there are, and in practice you rarely know that. Too few clusters lump real groups together, too many chop them into pieces. The 🔢 elbow method helps, but gives no answer if the data shows no clear bend. Then you decide.
0.76 🫧 Clustering › ✅ Strengths of clustering
✅ Strengths of clustering 🏷️ No labels needed: you save the 🔖 time and cost of labeling by hand and can get started right away with raw data. 🔍 Unexpected structure: the algorithm can 🗂️ find groups you had not thought of yourself, which makes clustering ideal for exploring a new dataset. 🧩 A stepping stone to labels: if you have a pile of unlabeled data, you cluster it first, label a few examples per cluster and then train a supervised model on those labels. That way you only have to look at a fraction of the data yourself. ⚡ Fast and scalable: k-means is simple and 🏁 converges quickly, even on millions of data points.

The question is in Dutch and the course in English, and still the search lands in the section about how many clusters to choose. The model puts a Dutch question and an English answer close together, as it did with the train sentences at the start.

Two warnings, though. The scores lie close together, so a high score doesn't mean that a chunk answers the question: it only lies closer than the rest. And for names, numbers and exact terms, ordinary search on words often does better, so large search engines combine both.

🤖 Extra: a study assistant for this course

A search engine plus a language model: those are the ingredients of retrieval-augmented generation (RAG). First look things up, then answer, with the sources. Here the language model gets the search engine as a tool: it decides itself what to search for, and how often, before it answers. The notebook about large language models explains tool calls step by step; here you only plug in your search engine.

This part needs a free key from OpenRouter (externe link), stored in Colab's 🔑 Secrets as OPENROUTER_API_KEY. Did you make one for that notebook? Then only switch on Notebook access for this one. If not, its section about the key explains how to get one. As there: never put a key in the code, and send nothing private to a free model.

try:
    from google.colab import userdata                     # in Colab: the key from the 🔑 Secrets
    api_key = userdata.get("OPENROUTER_API_KEY")
except ImportError:                                         # elsewhere: an environment variable, or type it in
    api_key = os.environ.get("OPENROUTER_API_KEY") or getpass.getpass("Your OpenRouter key: ")

client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)

# The free model we use, followed by the free models that OpenRouter tries when it's busy
MODEL = "nvidia/nemotron-3.5-super-vl:free"
MODELS = [MODEL, "google/gemma-4-31b-it:free", "openrouter/free"]

The model sees the tool as a description in JSON: its name, what it does, and what it needs (a query). ask_course sends the question with that description. As long as the model asks for searches, it runs them with search and sends the chunks back; as soon as the model answers without searching, that's the answer. Under every search you see its results, as in your search engine above. The model gets the whole text of those five chunks, not only their headings, so click them open to read what it read.

SEARCH_TOOL = {"type": "function", "function": {
    "name": "search_course",
    "description": "Searches the course AI voor Iedereen on meaning, and returns the 5 chunks that match best, with their links.",
    "parameters": {"type": "object", "required": ["query"], "properties": {
        "query": {"type": "string", "description": "What to look for: a few words or a question."}}},
}}
SYSTEM = """You are a study assistant for the course AI voor Iedereen of KU Leuven.
Before you answer, look up what the course says with search_course, as often as you need.
Answer only with what the course says, in at most 150 words, and link every section you use as [heading](url), without its emoji.
Write formulas and symbols as plain text, without LaTeX.
If the course doesn't cover the question, say so.
Answer in the language of the question: a question in English gets an answer in English."""


def ask_course(question):
    # Lets the model search the course until it can answer; shows every search and the answer, returns the conversation
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
    for step in range(6):
        response = client.chat.completions.create(model=MODEL, messages=messages, tools=[SEARCH_TOOL],
                                                  extra_body={"models": MODELS})
        message = response.choices[0].message
        messages.append(message.model_dump(exclude_none=True))
        if not message.tool_calls:                                   # no search: this is the answer
            print("Answered by", response.model)
            display(HTML(markdown.markdown(message.content or "", extensions=["tables"])))
            return messages
        for call in message.tool_calls:
            query = json.loads(call.function.arguments).get("query", question)
            found = search(query)
            print("🔍", query)
            show_results(found)
            results = found[["chapter", "heading", "url", "text"]].to_dict("records")
            # ensure_ascii=False: 🔢 and ï stay as they are, instead of codes such as 🔢 that the model has to decode
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(results, ensure_ascii=False)})
    return messages
conversation = ask_course("How do I choose the number of clusters in k-means?")
Uitvoer
🔍 k-means number of clusters choose
0.79 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? In data without clear groups there is no bend to see, and then the choice of $k$ is a decision you have to make: how many stations can the company afford, how many playlists do you want, how many customer segments can a marketing team handle?
0.78 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? The algorithm asks beforehand how many clusters there should be, and that choice of $k$ determines the result. Drag the $k$ slider below. With $k = 2$ two neighborhoods are lumped together, with $k = 3$ you get the three neighborhoods you saw yourself, and with $k = 4$ or more a real neighborhood is chopped into pieces. The chart next to the map helps with that choice. For every $k$ it shows how far a student lives from their station on average, each time after the algorithm has run to the end. More stations are always better for the average distance (with a station per room, everyone lives at distance zero), but the gain quickly gets smaller. From one to two and from two to three stations the distance drops sharply; a fourth station only gains a little. The bend in the curve looks like an elbow, and that is usually where a good $k$ lies: the elbow method. Click a point in the chart to choose that $k$. The elbow is an aid, not a law.
0.77 🫧 Clustering › 🤔 k remains a choice
🤔 k remains a choice You have to say beforehand how many clusters there are, and in practice you rarely know that. Too few clusters lump real groups together, too many chop them into pieces. The 🔢 elbow method helps, but gives no answer if the data shows no clear bend. Then you decide.
0.75 🫧 Clustering › 🌲 Hierarchical clustering
🌲 Hierarchical clustering K-means wants to know beforehand how many clusters there are. Hierarchical clustering turns that question around: it first builds up all the groupings, from very fine to very coarse, and you choose afterwards. The recipe is simple. You start with every point as its own cluster: eight rooms are then eight clusters of one. Then you repeatedly look for the two clusters that lie closest to each other and merge them into one cluster. You repeat that until everything is in one big cluster. You can measure how far apart two clusters lie as, for example, the average distance between their points. You draw the result as a dendrogram, a kind of family tree of your data. At the bottom every data point stands on its own, and every horizontal connection is a merge. The height of such a connection is the distance between the two clusters that come together there: low means they were very similar, high means you are gluing two different groups together. Eight rooms on the map, colored by cluster, and the dendrogram with all the merges. The dashed line cuts at 2.9 km and leaves three clusters.
0.72 🏘️ Nearest Neighbors › 🎚️ Choosing the number of neighbors
🎚️ Choosing the number of neighbors The choice of $k$ has a big influence on how the algorithm behaves. With a low $k$ (such as 1 or 3), the model follows the data very closely, as if it "memorizes" every individual point. That makes it sensitive to noise: a single mislabeled point changes the prediction in its whole surroundings. The model then follows not only the real patterns, but also the chance exceptions in the training data. That is called overfitting. With a high $k$ (for example $k = 10$), the algorithm looks at the "average" of a larger neighborhood. The decision boundaries become smoother and more robust against noise, but you lose nuance: small groups and local patterns are missed. In the extreme case, when $k$ equals the total number of data points, the algorithm always predicts the most common class, wherever the new point lies. That is called underfitting: the model is too simple to see anything anymore. Try to find the balance in the demo below. Watch how the decision regions (the background colors) change, and with them the predictions in those regions. The drop-down list at the top switches to another dataset.
Answered by nvidia/nemotron-3.5-super-vl:free

In k-means you must pick k before running the algorithm, and that choice determines the result How many clusters?. A common aid is the elbow method: plot the average distance to the cluster center for each k. The distance always drops as k grows, but the improvement gets smaller after a good k, creating a bend or elbow in the curve How many clusters?. The elbow is only a guide, not a rule. If the curve shows no clear bend, you must decide based on the situation, such as how many segments are useful or affordable k remains a choice. Too few clusters merge real groups; too many split them apart.

The model wrote its own search query, read the chunks that came back, and answered with links to the sections it used. Those chunks are all it saw of the course, so open them and compare: does the text really say what the answer claims? Which model answered depends on how busy the free models are, and the answer differs a little every time.

A question about two chapters at once:

conversation = ask_course("What's the difference between the k in k-means and the k in k-nearest neighbors?")
Uitvoer
🔍 k-means k nearest neighbors difference k value
0.75 🏘️ Nearest Neighbors › 🔄 How the algorithm works
🔄 How the algorithm works The k-nearest neighbors algorithm classifies a new data point in four steps: 📏 Calculate the distance from the new point to every point in the training data. 📊 Sort all distances from small to large. 🔝 Select the $k$ nearest neighbors (the $k$ points with the smallest distance). 🗳️ Vote: take the label that occurs most often among those $k$ neighbors (majority vote).
0.73 🏘️ Nearest Neighbors › 🎚️ Choosing the number of neighbors
🎚️ Choosing the number of neighbors The choice of $k$ has a big influence on how the algorithm behaves. With a low $k$ (such as 1 or 3), the model follows the data very closely, as if it "memorizes" every individual point. That makes it sensitive to noise: a single mislabeled point changes the prediction in its whole surroundings. The model then follows not only the real patterns, but also the chance exceptions in the training data. That is called overfitting. With a high $k$ (for example $k = 10$), the algorithm looks at the "average" of a larger neighborhood. The decision boundaries become smoother and more robust against noise, but you lose nuance: small groups and local patterns are missed. In the extreme case, when $k$ equals the total number of data points, the algorithm always predicts the most common class, wherever the new point lies. That is called underfitting: the model is too simple to see anything anymore. Try to find the balance in the demo below. Watch how the decision regions (the background colors) change, and with them the predictions in those regions. The drop-down list at the top switches to another dataset.
0.72 🏅 Model Evaluation › 🔧 Choosing hyperparameters with cross-validation
🔧 Choosing hyperparameters with cross-validation The k in k-fold cross-validation is not the same as the k in k-nearest neighbors: one is the number of folds you split the data into, the other the number of neighbors that vote on the label. It is pure coincidence that both techniques use the same letter.
0.72 🏘️ Nearest Neighbors › 👥 More neighbors
👥 More neighbors So far you only looked at the nearest neighbor: the one point in the training data that lies closest to the new point. That is the simplest version of the algorithm, but it has a big drawback: a single mislabeled point or a single exception can completely upset the predictions around it. An apple that happens to lie among the oranges turns all the new fruit around it into "apples". That is why we extend the algorithm to k-nearest neighbors (k-NN): it looks at the $k$ nearest points instead of just one. With $k = 3$, for example, you look at the three nearest neighbors and take the label that occurs most often among those three. That one stray apple is then outvoted by the oranges around it. In the demo below you see that with $k = 1$, some individual pieces of fruit create whole "islands" in the decision regions. Set $k$ to 3: the little island at the bottom left disappears, because the apple that cut it off is now outvoted by the oranges around it.
0.71 🫧 Clustering › 📐 📉 What k-means minimizes exactly
📐 📉 What k-means minimizes exactly In this chapter we keep track of the average distance to the centroid as a measure of the quality of a clustering. The algorithm actually minimizes the sum of the squared distances, the WCSS, also called the inertia of the clustering: $J = \sum_{i=1}^{k} \sum_{x \in C_i} \|x - \mu_i\|^2$where $C_i$ is the set of points in cluster $i$ and $\mu_i$ its centroid. Both steps of the recipe lower $J$ or keep it the same. The assignment step chooses for every point the centroid that makes its contribution the smallest. The update step puts every centroid at the mean of its points, and the mean is exactly the point that minimizes the sum of the squared distances to those points. Because $J \geq 0$ cannot go down forever and there are only finitely many assignments, the algorithm has to converge. It does end in a local minimum of $J$, though: finding the best possible clustering is NP-hard, and k-means is a fast heuristic that usually finds a good solution, but not necessarily the best one. In practice the elbow method from above therefore works with $J$ instead of the average distance; the shape of the curve is similar.
🔍 k-means k number of clusters
0.78 🫧 Clustering › 🌲 Hierarchical clustering
🌲 Hierarchical clustering K-means wants to know beforehand how many clusters there are. Hierarchical clustering turns that question around: it first builds up all the groupings, from very fine to very coarse, and you choose afterwards. The recipe is simple. You start with every point as its own cluster: eight rooms are then eight clusters of one. Then you repeatedly look for the two clusters that lie closest to each other and merge them into one cluster. You repeat that until everything is in one big cluster. You can measure how far apart two clusters lie as, for example, the average distance between their points. You draw the result as a dendrogram, a kind of family tree of your data. At the bottom every data point stands on its own, and every horizontal connection is a merge. The height of such a connection is the distance between the two clusters that come together there: low means they were very similar, high means you are gluing two different groups together. Eight rooms on the map, colored by cluster, and the dendrogram with all the merges. The dashed line cuts at 2.9 km and leaves three clusters.
0.77 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? In data without clear groups there is no bend to see, and then the choice of $k$ is a decision you have to make: how many stations can the company afford, how many playlists do you want, how many customer segments can a marketing team handle?
0.75 🫧 Clustering › 🔢 How many clusters?
🔢 How many clusters? The algorithm asks beforehand how many clusters there should be, and that choice of $k$ determines the result. Drag the $k$ slider below. With $k = 2$ two neighborhoods are lumped together, with $k = 3$ you get the three neighborhoods you saw yourself, and with $k = 4$ or more a real neighborhood is chopped into pieces. The chart next to the map helps with that choice. For every $k$ it shows how far a student lives from their station on average, each time after the algorithm has run to the end. More stations are always better for the average distance (with a station per room, everyone lives at distance zero), but the gain quickly gets smaller. From one to two and from two to three stations the distance drops sharply; a fourth station only gains a little. The bend in the curve looks like an elbow, and that is usually where a good $k$ lies: the elbow method. Click a point in the chart to choose that $k$. The elbow is an aid, not a law.
0.74 🫧 Clustering › 🤔 k remains a choice
🤔 k remains a choice You have to say beforehand how many clusters there are, and in practice you rarely know that. Too few clusters lump real groups together, too many chop them into pieces. The 🔢 elbow method helps, but gives no answer if the data shows no clear bend. Then you decide.
0.72 🫧 Clustering › 📐 📉 What k-means minimizes exactly
📐 📉 What k-means minimizes exactly WCSS (Within-Cluster Sum of Squares)📖 Definition The objective function of k-means is: $\begin{align*} J &= \sum_{i=1}^{k} \sum_{x \in C_i} \|x - \mu_i\|^2 \\ &= \underbrace{\sum_{x \in C_1} \|x - \mu_1\|^2}_{\text{cluster 1}} + \underbrace{\sum_{x \in C_2} \|x - \mu_2\|^2}_{\text{cluster 2}} + \ldots + \underbrace{\sum_{x \in C_k} \|x - \mu_k\|^2}_{\text{cluster } k} \end{align*}$where: $k$ is the number of clusters $C_i$ is the set of points in cluster $i$ $\mu_i$ is the centroid (the mean) of cluster $i$ $\|x - \mu_i\|^2$ is the squared Euclidean distance between point $x$ and the centroid $\mu_i$ K-means tries to make $J$ as small as possible: every point should lie as close as possible to the center of its cluster.
Answered by nvidia/nemotron-3.5-super-vl:free

In k-means, k is the number of clusters you must choose before running the algorithm; it determines how many groups the data is split into, and each group gets a centroid How many clusters? k remains a choice. In k-nearest neighbors, k is the number of nearest training points that vote on the label of a new data point How the algorithm works. A low k makes the model follow the data closely and risk overfitting; a high k smooths the decision boundaries but can miss local patterns Choosing the number of neighbors. The course notes that both techniques using the letter k is pure coincidence Choosing hyperparameters with cross-validation.

Count the searches: plain RAG searches once, with the question itself. Here the model decides what it still needs to know, so for a question about two chapters it can search more than once, for instance once per chapter. You've just built a small version of Gemini Notebook from the chapter, on the course you're taking.

Your turn: ask about anything in the course, in English or in Dutch. And keep comparing: an answer with sources is more trustworthy, but it isn't guaranteed to be right (see hallucinations). When we ran this cell, the answer ended with "The course notes that both techniques using the letter k is pure coincidence". The chunk it links to does say that, but about the k of k-fold cross-validation and the k of nearest neighbors, not about k-means.

🧰 Embeddings for your own documents

The recipe for your own texts:

  1. Collect the text with its structure: headings, page numbers, one message or review per row. For PDF, Word and PowerPoint files, MarkItDown (externe link) turns them into text with their headings.
  2. Cut at that structure: one chunk per section or paragraph, well below what the model reads (512 tokens here), with its heading in front.
  3. Choose a model for your language. This granite model is small and fast; multilingual-e5-small (externe link) knows a hundred languages, but needs "query: " in front of questions and "passage: " in front of the texts. Bigger models find a bit more, but without a graphics card they take minutes instead of seconds.
  4. Embed once, and save: np.save("vectors.npy", vectors), and np.load the next time. Up to a hundred thousand chunks, vectors @ question is fast enough; beyond that, a vector database such as FAISS or Chroma searches faster.
  5. Test the search with ten questions whose answer you know, before you trust it.
  6. For clusters: choose k yourself, read the chunks closest to every center to name the clusters, and look for odd clusters: those are often duplicates or junk in your data.

By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/embeddings.