Your First Machine Learning Program in Python
You can write a real machine learning program in plain Python, with no extra libraries, in about 50 lines. This one sorts fruit into apples and oranges using a method called k-nearest neighbors (k-NN). It trains on some examples, tests itself on examples it has never seen, and counts its own mistakes honestly.
Examples use Python 3.10 or later and only the standard library. If you are new to Python, the guide from block coding to Python covers lists, loops and if statements first.
The idea: ask the neighbors
To classify a new fruit, k-NN finds the k training fruits that are most similar to it (its "nearest neighbors") and lets them vote. If k is 3 and two of the three nearest fruits are apples, the guess is "apple". That is the whole method. There is no complicated training step: the model simply remembers the training examples and compares new ones against them.
"Similar" needs a number. Each fruit here has two features, its weight in grams and a smoothness score from 1 (bumpy) to 10 (smooth), so we can treat each fruit as a point on a graph and measure the straight-line distance between points.
The program
Save this as knn.py and run it with python3 knn.py (on some computers the command is python).
import math
import random
from collections import Counter
# Made-up fruit: (weight in grams, smoothness from 1 to 10, label)
fruit = [
(150, 9, "apple"), (170, 8, "apple"), (140, 9, "apple"), (160, 7, "apple"),
(180, 8, "apple"), (130, 9, "apple"), (155, 6, "apple"), (165, 8, "apple"),
(185, 5, "apple"),
(200, 3, "orange"), (220, 2, "orange"), (190, 4, "orange"), (210, 3, "orange"),
(230, 2, "orange"), (175, 6, "orange"), (205, 4, "orange"),
]
random.seed(2)
random.shuffle(fruit)
train = fruit[:10]
test = fruit[10:]
def predict(weight, smooth, k=3):
# Distance from the new fruit to every training fruit
distances = []
for w, s, label in train:
d = math.dist((weight / 10, smooth), (w / 10, s))
distances.append((d, label))
distances.sort()
nearest = [label for d, label in distances[:k]]
return Counter(nearest).most_common(1)[0][0]
confusion = Counter()
correct = 0
for w, s, actual in test:
guess = predict(w, s)
confusion[(actual, guess)] += 1
if guess == actual:
correct += 1
print(f"{w} g, smoothness {s}: actual {actual}, guess {guess}")
print("Confusion matrix (actual, guess): count")
for actual in ("apple", "orange"):
for guess in ("apple", "orange"):
print(f" {actual:6} -> {guess:6}: {confusion[(actual, guess)]}")
print(f"k-NN accuracy: {correct}/{len(test)}")
commonest = Counter(label for w, s, label in train).most_common(1)[0][0]
baseline = sum(1 for w, s, label in test if label == commonest)
print(f"Baseline (always '{commonest}'): {baseline}/{len(test)}")
What it printed
Running it with Python 3.12 printed:
220 g, smoothness 2: actual orange, guess orange
140 g, smoothness 9: actual apple, guess apple
130 g, smoothness 9: actual apple, guess apple
175 g, smoothness 6: actual orange, guess apple
205 g, smoothness 4: actual orange, guess orange
170 g, smoothness 8: actual apple, guess apple
Confusion matrix (actual, guess): count
apple -> apple : 3
apple -> orange: 0
orange -> apple : 1
orange -> orange: 2
k-NN accuracy: 5/6
Baseline (always 'apple'): 3/6
The program got 5 of the 6 test fruits right. It mistook one orange (175 g, smoothness 6) for an apple. Look at the data and you can see why: that orange is lighter and smoother than the others, right where the apples are. The nearest neighbors were apples, so the vote went the wrong way. That is a real lesson about machine learning: a model can only be as good as the features it is given.
The lines a beginner trips on
(150, 9, "apple")The dataset is a list of tuples. A tuple is a fixed group of values in round brackets. Each tuple is one example: weight, smoothness, label. All of it is made up for this guide.random.seed(2)Shuffling uses random numbers. Setting the seed makes the "random" order the same every time, so you get exactly the output above. Change the seed and you get a different split and possibly a different score, which is worth trying.random.shuffle(fruit)The list was written with all the apples first. Without shuffling, the test set would be all oranges. Shuffling mixes them before the split.train = fruit[:10]andtest = fruit[10:]These are slices.[:10]means "items 0 up to but not including 10", so the first 10 fruits;[10:]means "item 10 to the end", the other 6. The model never sees the test fruits while it learns.def predict(weight, smooth, k=3):This defines a function.k=3is a default value: if you do not say how many neighbors, it uses 3. An odd number avoids ties between two labels.math.dist((weight / 10, smooth), (w / 10, s))math.distgives the straight-line distance between two points. Why divide the weight by 10? Weights differ by tens of grams while smoothness differs by a few points, so without scaling, weight would swamp smoothness completely. Dividing puts the two features on similar scales. Real projects scale features too.for w, s, label in train:This splits each tuple into three variables in one go.distances.sort()Sorting a list of (distance, label) pairs sorts by the first item, the distance, so the nearest fruits come first.Counter(nearest).most_common(1)[0][0]Countercounts how often each label appears.most_common(1)returns a list holding the single commonest (label, count) pair;[0]takes that pair and the second[0]takes the label out of it.confusion[(actual, guess)] += 1A Counter starts every count at 0, so this adds one to the box for that combination of true answer and guess.
Reading the confusion matrix
The four lines under "Confusion matrix" are the four boxes of a confusion matrix: what the fruit really was, against what the program guessed.
| Guessed apple | Guessed orange | |
|---|---|---|
| Really apple | 3 | 0 |
| Really orange | 1 | 2 |
Accuracy is the right answers divided by all answers: (3 + 2) / 6 = 5/6, about 0.8333. If you call "orange" the positive class, the counts are 2 true positives, 0 false positives, 3 true negatives and 1 false negative. Typing those into the Model Accuracy Predictor, which works out accuracy, precision and recall from a confusion matrix, gives accuracy 0.8333, precision 1, recall 0.6667 and F1 0.8: every fruit it called an orange really was one, but it caught only two of the three oranges. The guide to accuracy, precision and recall explains when each number matters.
The baseline: is it better than lazy guessing?
The last line compares the program with a "lazy" model that ignores the fruit and always guesses the commonest label in the training set (apple). That lazy model scores 3 out of 6. Our k-NN scores 5 out of 6, so it really has learned something. Always run a baseline like this. A model that cannot beat lazy guessing has learned nothing useful, however clever it looks.
Be honest about what six test fruits can tell you
Six test examples is a tiny test. One more mistake would drop the accuracy from 5/6 to 4/6. Treat the score as a rough sign, not a precise measurement. This whole dataset is 16 rows of 2 features; stored as 8-byte numbers that is 256 bytes, which the Dataset Size Calculator shows as 0 MB (it is under 0.01 MB). Real projects use hundreds or thousands of examples, and keep a separate validation set: if you try several values of k, choose between them on the validation set and look at the test set only once, at the end.
Things to try
- Change
k=3tok=1and tok=5. Does the score change? - Change the seed. How much does the score move with a different split?
- Remove the
/ 10scaling and see whether weight now drowns out smoothness. - Add a third fruit, such as pears, with its own made-up weights and smoothness, and extend the confusion matrix to three rows.
The next step
Writing k-NN by hand shows you what is happening inside. Real projects usually use a library instead. In Python the usual teaching library is scikit-learn, which includes k-nearest neighbors alongside many other models, plus tools for splitting data and measuring results. Once this program makes sense to you, its documentation at scikit-learn.org is a natural place to go next.