Text and clustering · About 40 minutes
Group notes by topic
You have a set of short notes about sport, cooking and computing, with no labels. You will make a model sort them into groups without telling it the topics.
- The data
- Nine short notes, three on each topic, written into the notebook.
- Before you start
- You need basic Python: strings, lists and loops. The bike demand project helps but you can skip it.
Open the notebook
The notebook has the data and an empty cell for each step. Keep it open next to this page.
Your own computer
Download the notebook, then open it with Jupyter.
Download notebook ↓uvx --with scikit-learn --with pandas --with matplotlib --from jupyter jupyter lab group-documents.ipynbStep 1
Turn text into numbers
Practice firstWrite TF-IDF yourselfMediumModels work with numbers, so each note must become a vector.
TF-IDF gives each word a score in each note. A word scores high when it appears often in that note but rarely in the others. Words such as "the" appear everywhere, so they score low and stop dominating.
Need more background? Read the lesson →In the notebook
Convert the notes to TF-IDF vectors. Print the vocabulary and the top-scoring words for one note.
Step 2
Group similar notes
Practice firstWrite K-Means Clustering yourselfMediumk-means splits the data into k groups. It starts with k random centers, puts each note in the group of its nearest center, moves each center to the middle of its group, and repeats until nothing changes.
You choose k. You know there are three topics, so use k = 3. Fix the random seed so you get the same groups on each run.
Need more background? Read the lesson →In the notebook
Fit k-means with 3 clusters and a fixed seed. Print each note next to its cluster number.
Step 3
Find what each group means
Practice firstWrite Cosine Similarity yourselfEasyThe model gives each group a number, not a name. To find out what a group is about, look at the words with the highest weight in its center.
Cosine similarity compares two notes by the angle between their vectors, so long and short notes compare fairly. Use it to see where a new, unclear note fits.
Need more background? Read the lesson →In the notebook
Print the top words for each cluster. Add a note that mixes two topics and find the cluster it is closest to.
Check your work
Answer these in the last cell of the notebook.
- Do the groups match the topics you see when you read the notes?
- Why do the cluster numbers change when you change the seed?
- Why do nine notes not prove that this works on a large archive?