English:Clustering and unsupervised learning - AI Year 9
Introduction

Can a computer find groups without being told the correct categories? Work through two exact k-means rounds, compare different numbers of centres and test a new point. Separate numerical groupings from their real-world meaning. All points represent fictional counters, and the executed program fits an unsupervised toy grouping rather than a verified classification of people.
Group examples without target labels
Clustering groups examples using selected features and a similarity rule without supplied target-category labels. The output group numbers identify the groups produced by the method. They are not automatically species, abilities, personality types or any other naturally true category. A useful interpretation requires a purpose and independent evidence about what the features represent.
Our original six cards use two features: red-counter count on the horizontal axis and blue-counter count on the vertical axis. The points are A at one, one; B one, two; C two, one; D five, five; E five, six; and F six, five. None has a target label. Plot them and identify what has been measured, what has not, and why changing a feature definition would change the problem.
| Point | Red count | Blue count |
|---|---|---|
| A | 1 | 1 |
| B | 1 | 2 |
| C | 2 | 1 |
| D | 5 | 5 |
| E | 5 | 6 |
| F | 6 | 5 |
For k-means, choose k, the number of centres. A centre, also called a centroid, is represented by feature-coordinate means and need not coincide with an observed card. Our supplied starting centres for k=2 are one, one and five, five. An assignment step chooses the nearer centre using squared Euclidean distance. An update step replaces each centre by the coordinate-wise mean of the points assigned to it. Repeating assignment and update is the small Lloyd procedure implemented here.
For example, B at one, two has squared distance one to the first starting centre and 25 to the second. A goes with the first centre at distance zero; D with the second at zero. The initial assignment puts A, B and C in group 0 and D, E and F in group 1. We declare that an exact distance tie goes to the first listed centre. This is a reproducible policy, not evidence that the first group is more important.
StatQuest explains k-means clustering. Use the recording to connect the alternating assignment and mean-update steps with the paper calculation. The actual title, creator, playability, embedding and preview were checked; that does not imply a complete independent review of every spoken claim. The written lesson contains the full required method and can be completed without playback.
Try before checking: calculate C's two starting squared distances and decide its first group. Hint: subtract coordinate by coordinate before squaring. Partial step: C is one unit horizontally from the first centre. After attempting, check that its distances are one and 25, so it joins group 0. No target label was needed for this calculation, and no correct real-world category has been established.
Carry out two complete rounds and compare k
In round one, group 0 contains A, B and C. Their horizontal values one, one and two sum to four, and their vertical values one, two and one also sum to four. The new centre is four thirds, four thirds. Group 1 contains D, E and F; each coordinate sums to 16, so its new centre is 16 thirds, 16 thirds. Fractional coordinates are valid means even though each original counter count was an integer.
Round two must still perform a new assignment using these updated centres. It is not enough to assume nothing changes. For A the squared distances are two ninths and 338 ninths. For B they are five ninths and 269 ninths; C has the same pair. D is much nearer the second centre, and E and F also remain there. The groups therefore stay A B C and D E F. Recomputing their means gives the same centres, so this fixture has a fixed point after the second round.
| Round | Group 0 | Group 1 | Centres after update | Sum of squared distances after update |
|---|---|---|---|---|
| 1 | A B C | D E F | 4/3 4/3 and 16/3 16/3 | 8/3 |
| 2 | A B C | D E F | Unchanged | 8/3 |
The within-cluster sum of squared distances is often called inertia. For group 0, distances to the updated centre are two ninths, five ninths and five ninths, totalling four thirds. Group 1 contributes another four thirds. Total is eight thirds. The first starting assignment had total four around its old centres, so updating the means reduces that declared objective. This is an internal geometry measure, not a classification-accuracy score.
Compare a simple one-centre baseline. All six points share centre ten thirds, ten thirds, and its objective is 152 thirds. With the three initial centres one, one; five, five; and six, five, two rounds give groups A B C, D E, and F, with objective 11 sixths. A lower within-sample objective for three groups does not prove that there are three meaningful kinds of counter cards. Extra centres offer more flexibility, and usefulness depends on a separate purpose and evidence.
The complete exact-arithmetic program below was actually executed for k=1, k=2 and k=3. It deliberately runs a requested one to ten rounds, with two in the main examples, rather than claiming a general stopping controller or a globally optimal solution. It rejects empty clusters and asks for initial-centre review rather than silently inventing a replacement centre. Equal starting centres can send every point to the same tie-winning group and trigger that case.
"""Two exact Lloyd rounds on original unlabelled points, with bounded settings."""
from fractions import Fraction as F
import json
POINTS = [(1, 1), (1, 2), (2, 1), (5, 5), (5, 6), (6, 5)]
def checked_point(point):
if (not isinstance(point, tuple) or len(point) != 2
or any(type(x) not in (int, F) for x in point)):
raise ValueError("Expected two exact numeric coordinates")
def distance2(a, b):
checked_point(a)
checked_point(b)
return sum((x - y) * (x - y) for x, y in zip(a, b))
def assign(point, centres):
checked_point(point)
if not isinstance(centres, list) or not centres:
raise ValueError("Expected a nonempty centre list")
for centre in centres:
checked_point(centre)
# A distance tie is assigned to the first listed centre, by declared policy.
return min(range(len(centres)), key=lambda i: distance2(point, centres[i]))
def lloyd(points, initial, rounds=2):
if (not isinstance(points, list) or not points
or type(rounds) is not int or rounds not in range(1, 11)):
raise ValueError("Expected nonempty points and one to ten rounds")
for point in points:
checked_point(point)
if not isinstance(initial, list) or not initial or len(initial) > len(points):
raise ValueError("Expected one to n initial centres")
for point in initial:
checked_point(point)
centres, history = list(initial), []
for step in range(rounds):
assignments = [assign(p, centres) for p in points]
groups = [[p for p, label in zip(points, assignments) if label == i]
for i in range(len(centres))]
if any(not group for group in groups):
raise ValueError("Empty cluster: review the initial centres")
updated = [tuple(F(sum(p[j] for p in group), len(group)) for j in range(2))
for group in groups]
old_sse = sum(distance2(p, centres[i]) for p, i in zip(points, assignments))
new_sse = sum(distance2(p, updated[i]) for p, i in zip(points, assignments))
history.append(dict(round=step + 1, assignments=assignments,
centres_before=centres, centres_after=updated,
sse_before=old_sse, sse_after=new_sse,
centres_unchanged=updated == centres))
centres = updated
return dict(centres=centres, history=history)
def demonstrate():
fitted = lloyd(POINTS, [(1, 1), (5, 5)])
centres = fitted["centres"]
tie = (F(10, 3), F(10, 3))
held_out, remote = (4, 2), (100, 100)
return dict(points=POINTS, two_cluster=fitted,
one_cluster=lloyd(POINTS, [(0, 0)]),
three_cluster=lloyd(POINTS, [(1, 1), (5, 5), (6, 5)]),
held_out=dict(point=held_out, distances=[distance2(held_out, c)
for c in centres], assignment=assign(held_out, centres)),
tie=dict(point=tie, distances=[distance2(tie, c) for c in centres],
assignment=assign(tie, centres)),
remote=dict(point=remote, assignment=assign(remote, centres)),
target_labels_used=False, real_world_categories_verified=False)
if __name__ == "__main__":
print(json.dumps(demonstrate(), default=str, indent=2))Attempt the update: compute the mean of D and E in the k=3 example and its contribution to the objective. Hint: their first coordinates are both five and the second coordinates five and six. Check after attempting that the centre is five, five and a half, with squared distances one quarter each. Adding one half to the first group's four thirds gives 11 sixths. A different initialisation or data geometry may produce another result; stability on these six cards does not prove universal optimality.
Test interpretation boundaries and a new context
Freeze the fitted two-centre result before examining a new card. H at four, two was not used to calculate either centre. Its squared distances are 68 ninths to group 0's centre and 116 ninths to group 1's centre, so the declared nearest-centre rule assigns it to group 0. That may surprise someone looking only at the red count four. Assignment uses both coordinates, and the output number is not a true label with which to calculate supervised accuracy.
At the midpoint ten thirds, ten thirds, the squared distances are eight and eight. The tie policy chooses group 0, so a group number here reflects the declared centre order. Reversing centre numbering does not by itself change the mathematical partition. Report a tie or its policy instead of describing the selected group as intrinsically correct.
A remote point at 100,100 is assigned to group 1 because that centre is closer. The code has no novelty detector or maximum-distance rejection. Receiving a group number therefore does not mean that a new example resembles the fitted data closely or is within an appropriate use context. This remote input is a deliberate challenge case, not a normal delivery of a confidently recognised category.
Changing scales can also change distance-based groups. The red and blue counts use comparable numerical units in our fixture, but a new context might mix minutes and metres. Define feature meaning and a justified representation before comparing distances. If transformations are fitted from data, estimate them on the fitting subset and freeze them for later examples. Do not tune a representation using reserved evaluation cases and still call those cases untouched evidence.
CodeAI discusses training data and bias. Ask which situations are missing from a selected feature representation. Six invented cards cannot support decisions about real pupils, their abilities or their future opportunities. An unexplained cluster label is particularly weak justification for treating a person differently. Human review should examine the purpose, features, affected people, error consequences and evidence beyond an internal geometry score.
The optional Commons animation by Chire shows a different k-means example with three moving centres and 15 frames. In its frame convention, the means and black boundaries have been updated while point colours still reflect the previous assignment. That temporary mismatch is part of the illustrated intermediate stage, not our six-card output. Its external source is provided below because this portal's native parser did not resolve the GIF during the media check. The functioning coordinate image and verified videos remain embedded; the lesson does not pretend the optional GIF is playing inline.
Transfer workshop: propose grouping fictional museum displays by two named numerical features. Choose and justify a purpose, compare k=1 with another k, and reserve new displays for inspection. Keep a log of source definitions, units, initial centres, tie and empty-cluster policies, each assignment and mean, expected versus actual results and limits. Explain what evidence would make the grouping useful to a curator or visitor; a smaller objective alone is insufficient. Use invented displays rather than collecting private visitor or pupil profiles.
The supplied KS3 algorithm objective is a broad source anchor. The Year 9 placement, k-means example and success criteria are editorial applications. They are not a claim that k-means is a mandatory named KS3 algorithm or that a two-round exercise establishes practical competence in a real AI service.
Interactive Tasks
Quiz: Test Your Knowledge
What distinguishes this clustering task from supervised classification? (No target-category labels are supplied) (!The correct labels are hidden in the group numbers) (!Every group is a natural species) (!The method cannot use numbers)
What does k specify here? (The number of centres) (!The guaranteed accuracy percentage) (!The number of labelled outcomes) (!The number of real people tested)
Which points join the first group in round one? (A B and C) (!A D and F) (!B E and F) (!Only H)
What is the first updated centre for group zero? (Four thirds in both coordinates) (!One in both coordinates) (!Four in both coordinates) (!Sixteen thirds in both coordinates)
What happens in the second main round? (Assignments and updated centres stay the same) (!All points swap groups) (!The model gains verified target labels) (!The objective becomes a success probability)
What does eight thirds measure in the main result? (Within-cluster sum of squared distances) (!The fraction of correct real-world categories) (!The number of learners who passed) (!A guaranteed future error rate)
Why does a lower objective for three groups not prove three true categories? (It measures fit to selected numerical features rather than real-world meaning) (!All lower objectives are arithmetic errors) (!Three groups always have higher inertia) (!The centres must be actual observed cards)
How is the exact midpoint tie resolved? (Choose the first listed centre by declared policy) (!Infer the naturally correct category) (!Train on a private visitor profile) (!Remove the point without recording it)
What does the remote point test expose? (The code assigns a group without a novelty-rejection rule) (!Every remote point is certified familiar) (!Group one is a probability of one) (!The training data contain all future examples)
What happens if an initialisation leaves a cluster empty? (The program stops with a review error) (!It silently invents a new centre) (!It publishes a real service automatically) (!It calls every target label correct)
Memory Game
| Cluster | A grouping produced under selected features and settings |
| Centroid | A coordinate-wise mean representing a group |
| Assignment | Choosing a group using current centres |
| Update | Recomputing a centre from assigned points |
| Inertia | The within-cluster sum of squared distances |
| Initialisation | The chosen starting centres |
Drag and Drop
| Compare a point with the current centres | Assignment step |
| Average each coordinate within an assigned group | Centre update |
| Keep a new card out of fitting the centres | Held-out inspection |
| Record how equal distances are handled | Tie policy |
| Stop when no points reach one centre in this implementation | Empty-cluster review |
Crossword Puzzle
| CLUSTER | A computed grouping |
| CENTROID | A mean representing a group |
| ASSIGN | Choose a current nearest centre |
| UPDATE | Recompute a group mean |
| INERTIA | Within-group sum of squared distances |
| FEATURE | A measured input characteristic |
LearningApps
Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.
Cloze Text
Open Tasks
Easy
- Plot and name the features: Draw all six points with red and blue count axes. Hint: no point has a target category. Explain what a vector contains and what it leaves unknown.
- Compute a first assignment: Calculate the two starting squared distances for B and C. Hint: square each coordinate difference then add. Compare with A and D before naming the first groups.
- Update the two centres: Find the coordinate-wise means of A B C and D E F. Hint: both first-group coordinate sums are four and both second-group sums sixteen. Keep exact thirds.
- Explain the group numbers: Describe what zero and one mean here. Hint: they identify outputs of a method. Avoid calling either group a true species skill level or personal category.
Standard
- Complete round two: Reassign all six points using the updated centres then recompute both means. Hint: do not simply assume the first assignment remains valid. Keep a trace with expected and actual values.
- Calculate the objective: Add the six squared distances to the updated centres. Hint: each three-point group contributes four thirds. Explain why this internal value is not classification accuracy.
- Compare one two and three groups: Use the executed results for the declared initial centres. Hint: objectives are one hundred fifty two thirds eight thirds and eleven sixths. State a criterion beyond lower within-sample distance.
- Inspect new and tied points: Calculate H distances and the exact midpoint case using frozen centres. Hint: distinguish a nearest-centre output from an independently known correct category. State the tie policy explicitly.
Advanced
- Test a problematic start: Use two identical initial centres and explain the empty-cluster result. Hint: the declared tie rule sends every point to the first centre. Document the error rather than silently claiming a successful fit.
- Assess the remote point: Explain why assigning the 100 100 point does not establish familiarity or valid use. Hint: no distance-rejection mechanism is implemented. Propose further review without inventing an existing detector.
- Review representation and evaluation: Plan a feature-scale and unseen-case audit for a new numerical dataset. Hint: keep fitted transformations separate from reserved evaluation cases and distinguish geometric fit from usefulness.
- Transfer to museum displays: Design a fictional curator task with two named numerical features purpose initial centres baseline and inspection cases. Hint: report limitations user needs and human review rather than inferring categories of actual visitors or pupils.
Learning Check
- Distinguish unsupervised output: What are the inputs and what do the group numbers mean?
- Complete the main two rounds: Give assignments centres and the fixed-point check.
- Calculate and compare objectives: What are the one two and three group results?
- Handle held-out ties and remoteness: What do the three challenge cases show?
- Handle initialisation honestly: What happens with an empty cluster and what remains uncertain?
- Evaluate a new context: What should a museum-display project report?
Worked checks and assessment guidance
- The six original cards supply two numerical counts and no target-category labels. K-means groups them under chosen centres distance and settings. Output group numbers identify those computed groups rather than naturally true kinds or verified personal characteristics.
- Starting at one one and five five round one assigns A B C to zero and D E F to one. Coordinate means become four thirds four thirds and sixteen thirds sixteen thirds. Round two repeats the distance comparison keeps the assignments and returns the same means. That is a fixed point for this fixture not proof of global optimality everywhere.
- After the declared rounds one centre has objective one hundred fifty two thirds two centres eight thirds and three centres eleven sixths. Each main three-point group contributes four thirds. Lower within-sample squared distance does not measure true-category accuracy and more flexible groups need separate purpose-based justification.
- H four two has squared distances sixty eight ninths and one hundred sixteen ninths so joins group zero. The midpoint ten thirds in both coordinates has distance eight to each and follows the first-centre tie policy. The remote 100 100 point joins group one but no novelty detector validates it. None has a supplied true label for supervised accuracy.
- The bounded implementation raises a review error if any centre receives no points. Two identical starting centres can create that condition under first-centre ties. It does not silently reseed claim a globally optimal result or turn a fixed number of rounds into a general convergence guarantee.
- State purpose feature definitions units selection initial centres k baseline tie and empty-cluster policies assignment and mean traces unseen-case evidence and remaining limits. Fit any data-dependent transformation on the fitting subset and freeze it for inspection. Meaningfulness requires curator or visitor evidence beyond geometry and the editorial Year9 exercise does not justify personal classification.
Learning evidence
Retain a labelled six-point plot, full two-round distance and mean trace, exact objective calculations and k=1 and k=3 comparisons. Add the held-out midpoint remote and empty-cluster checks, expected and actual program outputs and a new museum-display plan. Separate unsupervised fitting geometric coherence and real-world usefulness; do not invent target labels classification accuracy or observed practical competence.
OER and Wikipedia
scikit-learn: Clustering, k-means section supplies the technical assignment/mean-update method and the interpretation limits of inertia and initialisation. Relevant primary sections inspected 15 November 2026. The six-point fixture exact Fraction implementation and one/two/three-centre calculations are original teaching constructions, not the library's full implementation or a guarantee of a globally optimal result.
DfE: Computing programmes of study supplies the broad KS3 algorithm anchor. K-means and the Year 9 decomposition are editorial applications; the source does not mandate this named algorithm or certify real-world AI competence.
2D Cartesian Coordinates.svg, H Padleckas, public domain. Generic coordinate image embedded unchanged. Optional external animation: K-means convergence.gif, Chire, CC BY-SA 4.0. The 15-frame original was retrieved and frames 0 7 and 14 visually inspected without changing the source file. Its updated boundaries and previous-assignment point colours represent different stages of each round. The native portal parser did not resolve this GIF, so it is an optional external source rather than a falsely claimed inline animation or the six-card fixture.
https://www.youtube.com/watch?v=4b5d3muPQmA — StatQuest with Josh Starmer: StatQuest: K-means clustering. https://www.youtube.com/watch?v=x2mRoFNm22g — CodeAI: AI: Training Data & Bias. Actual metadata playability embedding and preview bytes verified; previews visually inspected. Videos embedded unchanged without transcript copying endorsement redistribution or relicensing implied. The complete written method and paper calculations work without playback.
All six cards challenge points target-free grouping comparisons and museum scenarios are original fictional exercises. The complete bounded exact-arithmetic program was actually executed. It performs unsupervised toy fitting but no supervised classifier real person profiling service deployment local generative LLM or paid API. Author checks are not an independent subject-specialist certification.
Linked learning areas
aiMOOC Projects
Schulfach+


aiMOOCs


aiMOOC Projekte


MOOCwiki · Deutsch
Nach dem Lernen ist vor dem Lernen
Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.
Zur MOOCwiki-HauptseiteMediathek
Mediathek wird aus dem Wiki geladen ...
Keine passenden Inhalte gefunden. Bitte ändere Suche oder Filter.
NEWSLernweltNOAH fragen