In P0.4 you ran your first cells: print, a variable, a list, a NumPy array. That was just enough to start. Now we slow down and learn the language properly, because every later lesson in this part, and most of the code you will meet in ML, is made of a small set of Python pieces.
You do not need all of Python. You need a small set of ideas, and you need them to be solid. This lesson walks through them in the order that makes them easiest, always with a cell you can run. By the end you will build a tiny training and test split, a word counter and a classifier from scratch, using nothing but what is on this page.
How to use this page. Every box on this page starts fresh, as P0.4 explained, so each box defines what it needs. Edit the code and press Run again as often as you like: changing a value and re-running is the fastest way to learn. Outputs below each box are what you should see. (The first Run on a page downloads Python, about 6 MB, once.)
Values and types
Everything in Python is a value, and every value has a type. The five you need first:
| Type | Example | What it is for in ML |
|---|---|---|
int | 7, -3, 1000000 | counts: examples, epochs, batch size |
float | 7.0, 0.001, 1e-4 | real numbers: learning rate, loss, accuracy |
str | "cat", '7' | text: labels, words, file names |
bool | True, False | yes or no: is this prediction correct? |
None | None | “no value”: a missing result, an option not set |
type(v) tells you the type of v. Run this and compare each line with the value that made it:
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
7 int
7.0 float
'7' str
True bool
None NoneType
3.5 3 1 1024
-4 1
13 5.0 34
2 True True
int
str
Read it line by line:
7,7.0and'7'look alike and are three different things: an integer, a float and a piece of text.repr(v)shows a value the way you would type it, so the string shows its quotes.- Division has three forms.
/always gives a float (7 / 2is3.5).//is floor division: it divides and rounds down (7 // 2is3).%is the remainder (7 % 2is1).**is the power. Rounding down means toward minus infinity, so-7 // 2is-4and not-3. The pair always fits together: , so-7 % 2is1, and the remainder is never negative when the divisor is positive. - Conversion is explicit:
int("12")makes the number 12,float("2.5")makes 2.5,str(3)makes the text"3". Adding text to text joins them ("3" + "4"is"34"). TrueandFalseare numbers too:True + Trueis2. This is handy, because the number of correct predictions is just thesumof a list ofTrueandFalse.==asks “are these equal?” (3 == 3.0isTrue). ForNoneyou writeis None, because there is only oneNone, andischecks “is this the very same object?”. Use==for values andisonly forNone.- Dynamic typing. The name
vfirst points to an int and then to a string, and Python does not complain. The type belongs to the value, not to the name. This is flexible, and it also means type mistakes show up only when the code runs.
Integers in Python can be as large as memory allows (2 ** 100 prints all 31 digits), so integer arithmetic never overflows. Floats do not behave like that: they have limited precision. P1.G1 showed how a float is stored, and here is the everyday consequence:
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
0.30000000000000004
False
True
Python (like most languages, which use the same 64-bit floats, P1.G1) stores 0.1 as the closest number it can, and the closest number is not exactly 0.1. So never compare two floats with ==. Ask whether they are close: the difference is smaller than a tolerance. (math.isclose does this for you.) One more surprise: round(2.5) is 2 and round(3.5) is 4, because Python rounds exact halves to the even neighbour. And round(2.675, 2) is 2.67, not 2.68, because the float nearest to 2.675 is a hair below it.
Variables are names, not boxes
Here is the single most useful picture in this lesson. When you write
a = [1, 2, 3]
Python makes a list object in memory, and then attaches the name a to it, like a sticky note. The name is not the list, and the list is not stored “inside” a. Writing b = a attaches a second sticky note to the same object. It does not make a copy.
This does not matter for numbers and strings, because they cannot be changed in place. It matters a lot for lists, which can. Run this and watch which lines change together:
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3]
True False True
[[9, 0], [0, 0]] [[9, 0], [0, 0]] [[0, 0], [0, 0]]
[[1, 0], [1, 0]]
b.append(4)changedatoo, becauseaandbare the same list.a is bisTrue.cis a copy, so it kept[1, 2, 3].c == [1, 2, 3]isTruebecause==asks whether two lists hold equal contents, whilea is cisFalsebecauseisasks whether they are the same object.- A shallow copy (
grid.copy(), orgrid[:], orlist(grid)) makes a new outer list, but the inner lists are still shared. Changinggrid[0][0]showed through inshallow. A deep copy (copy.deepcopy) copies everything inside too, sodeepstayed zero. - The last line is a famous trap.
[[0] * 2] * 2repeats the same inner list twice, so setting one entry changes both rows. To make independent rows, use a comprehension (you will meet it soon):[[0] * 2 for _ in range(2)].
Intuition
Think of a name as a sticky note and an object as a thing on a table. b = a puts a second note on the same thing. A copy buys a second thing. Changing the thing (append) is seen through every note on it. Moving a note (b = [9]) changes only that note.
Where the picture breaks: numbers and strings cannot be changed in place, so notes on them behave as if each note had its own copy. Only changeable objects (lists, dicts, sets, and objects of your own classes) show the sharing.
Math
There is no new maths, but there is a cost to know. Reading a[i] takes the same time however long the list is. Asking x in a for a list has to look at the items one by one, so it grows with the length (we say , P1.G4). Asking x in s for a set or a dict key is, on average, independent of the size (), because they use a hash table. That is why you turn a list into a set before you test membership many times. The measured numbers come with NumPy in P2.2 and with growth rates in P1.G4.
Code
Changing a list in place and building a new one look alike and are not the same. The difference is exactly the sticky-note picture.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
True
[1, 2] [1, 2, 3] False
[1, 2, 3] [1, 2, 3] Trueid(x) is a number that identifies the object. b = b + [3] makes a new list, so a is safe. b += [3] extends the existing list in place, so a changes too. For numbers, += always makes a new value.
Strings and f-strings
A string is text in quotes (single or double, the same). You can index and slice it like a list ("hello"[1:3] is "el"), join pieces with +, repeat with *, and use methods such as .split(), .strip(), .upper(), .lower(), ",".join(items). A string cannot be changed in place; every method returns a new string.
The tool you will use every day is the f-string: put f before the quote and write any expression in braces. After a colon you can give a format: .2f means two digits after the point, .1% means percent with one digit, , adds thousands separators, >9 right-aligns in nine characters, and 04d pads an integer with zeros to width 4.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
model_A: accuracy 0.91
91.2% of 12,345 examples
[ model_A] [0003]
7
acc=0.91234
The last form, {acc=}, prints the expression and its value, which is a quick way to debug. Training logs in ML code are mostly f-strings like these.
Lists
A list is an ordered, changeable collection, written with square brackets. It can hold anything, even a mix of types, and even other lists. It is the workhorse of Python.
index 0 1 2 3 4
value 10 20 30 40 50
negative -5 -4 -3 -2 -1
- Indexing starts at 0:
a[0]is the first item. A negative index counts from the end:a[-1]is the last. - Slicing
a[start:stop:step]gives a new list fromstartup to, but not including,stop. Leave a part out to use the default:a[:2]is the first two,a[3:]is everything from index 3,a[::2]is every second item,a[::-1]is the list reversed. A slice never raises an error for going past the end. - Lists are changeable:
a[0] = 99replaces an item,a.append(x)adds one item at the end,a.extend([x, y])adds each item of another list, anda.pop()removes and returns the last.len(a)is the length andx in aasks whetherxis an item.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
10 50 40
[20, 30, 40] [10, 20] [40, 50]
[10, 30, 50] [50, 40, 30, 20, 10]
[99, 20, 30, 40, 50, 60, 70, 80] 8
True 2
9 [1, 2]
[1, 2, 3] None
Two things to notice in the last lines. append([1, 2]) added the list as one item (the length went from 8 to 9), while extend adds each of its items. And sorted(x) returns a new sorted list, while x.sort() sorts in place and returns None. A very common bug is writing x = x.sort(), which leaves x equal to None.
Tuples, dictionaries and sets
A tuple is like a list that cannot be changed: point = (3, 4). Use it for a fixed group of values, such as a shape (28, 28) or a pair (features, label). Unpacking splits a tuple (or list) into names: x, y = point. It gives the swap x, y = y, x, and first, *rest = [1, 2, 3, 4] puts the first item in first and all the others in rest.
A dictionary (dict) maps keys to values: {"ann": 31, "bo": 25}. Look up with d["ann"]; a missing key raises a KeyError, while d.get("dan") gives None and d.get("dan", 0) gives your default. Add or change with d["cy"] = 40. d.items() gives (key, value) pairs, d.keys() the keys and d.values() the values. Since Python 3.7 a dict keeps insertion order. Keys must be hashable, which in practice means unchangeable: strings, numbers and tuples of such values are fine; lists, sets and dicts are not.
A set keeps only distinct items and tests membership fast: {1, 2, 2, 3} is {1, 2, 3}. You can combine sets: & for items in both, | for items in either. A set has no useful order and no indexing (small whole numbers happen to print in order; do not rely on it); use sorted(s) when you need a list in order. The empty set is set(), because {} is an empty dict.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
(3, 4) 4 3 1 [2, 3, 4]
None 0 True
ann 31
bo 25
cy 40
['ann', 'bo', 'cy'] [31, 25, 40]
[1, 2, 3] 3 True
{2} {1, 2, 3}
{(0, 1): 'a tuple works as a key'}
In ML code a dict is the usual home of settings ({"lr": 0.1, "epochs": 3}), vocabularies ({"the": 0, "cat": 1}), and results ({"loss": 0.4, "acc": 0.9}).
Control flow
if, elif, else choose a branch. for walks over anything you can loop over (a list, a string, a dict, a range). while repeats as long as a condition holds. break leaves a loop, continue skips to the next round. Python uses indentation (four spaces) to mark what is inside a block, so the spaces are part of the code, not style.
Three helpers for loops come up constantly:
range(n)counts ;range(a, b, step)counts fromaup to but not includingb.enumerate(xs)gives(index, item)pairs, so you do not count by hand.zip(xs, ys)pairs items from two lists,(xs[0], ys[0]),(xs[1], ys[1]), and so on. It stops at the shorter list, which can hide a length mismatch.
Conditions use truthiness: 0, 0.0, "", [], {} and None count as false, and almost everything else counts as true, so if items: means “if the list is not empty”.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
0 cat 0.9 sure
1 dog 0.4 no
2 cat 0.75 maybe
8
3 1.0
[0, 1, 2] [2, 5, 8]
False False False False False False True
[(1, 'a'), (2, 'b')]
The sum is : k = 2 was skipped by continue and the loop stopped at k = 5 by break. The while loop halved the loss and stopped when it was no longer above 1, so it ran 3 times. Beware: a while whose condition never turns false runs forever. (If a cell on this page seems stuck, reload the page.) Note the last test: [0] is a list with one item, so it counts as true even though that item is 0. Since Python 3.10, zip(xs, ys, strict=True) raises an error if the lengths differ.
Functions
A function packages a piece of code under a name so you can reuse it. def starts it, the parameters go in brackets, and return sends a value back.
- A parameter can have a default:
threshold=0.5. The caller may skip it. - Arguments can be passed by position, or by keyword (
threshold=0.8), in any order. Keywords make calls readable, so ML libraries use them for nearly every setting. - A function with no
returnreturnsNone. To return several values, return a tuple and unpack it:lo, hi = min_max(v). - Scope. Names made inside a function are local: they exist only during the call. Assigning to a name inside a function makes a new local name; it does not change a global name of the same spelling (unless you declare it
global).
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
0.6666666666666666
1.0
0.6666666666666666
With the default threshold 0.5 the prediction 0.7 counts as “yes”, which is wrong, so 2 of 3 are right. With threshold 0.8 all three are right.
The mutable default trap
A default value is created once, when the def line runs, and then reused on every call. For a number or a string that is harmless. For a list or dict it is a classic bug: every call that uses the default shares the same list.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
[1]
[1, 2]
[1]
[2]
The first function remembered the 1 from the first call. The fix is the standard pattern: default to None, and make the list inside the function.
*args, **kwargs, scope and lambda
Two short forms you will see in library code. *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. At a call, * and ** do the opposite: they spread a list or a dict into arguments. A lambda is a function with no name written in one line: lambda v: v * v. It is used mostly as a short key= for sorting (below). If it needs more than one line, write a def.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
(1, 2) {'lr': 0.1, 'epochs': 3}
(1, 2) {'lr': 0.1}
25 [1, -2, -3]
100 0
bump() returned 100 but the global count stayed 0. (Inside a function, a name you only read is looked up outside; a name you assign is local. Reading a name before you assign it inside the same function raises UnboundLocalError.)
Comprehensions
A list comprehension builds a list in one line: [expression for item in iterable if condition]. It reads like set-builder notation, “the squares of x for x in the list”. The if at the end keeps only some items. An if ... else ... placed before the for chooses between two values. The same idea with braces builds a dict ({k: v for ...}) or a set. With round brackets, as in sum(x * x for x in xs), it is a generator expression, which makes the items one at a time without building the whole list.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['odd', 'even', 'odd', 'even', 'odd', 'even']
{'cat': 0, 'dog': 1, 'fish': 2}
{3, 4}
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
91
The dict line builds a vocabulary: each word gets a number, which is how text is turned into numbers for a model. The nested one (for a ... for b ...) reads left to right like two nested loops.
When a plain loop is clearer. A comprehension is for building one collection from another. If you need several steps, early exits, or side effects such as printing, write a normal for loop. A comprehension that does not fit on one line is usually a loop in disguise.
Classes
A class bundles data and the functions that work on it into one new kind of object. You write the recipe once (class Dataset:) and then make as many instances as you like. Three words to know:
__init__runs when you create an instance. It sets up the instance’s attributes (its data), such asself.xs.- A method is a function inside the class. Its first parameter is
self, the instance it was called on. You writeds.mean_label(), and Python passesdsin asselffor you. - Special methods with double underscores let your object work with built-in syntax.
__len__makeslen(obj)work.__getitem__makesobj[i]work, and also lets you loop over the object.
Below is a tiny Dataset: a list of inputs and a list of labels, kept together. This is the same shape as a PyTorch Dataset (P2.7), which must define __getitem__ to fetch one example, and in practice also __len__, because a DataLoader and samplers use it to know how many examples there are.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
3 (2.0, 1) 0.6666666666666666
1.0 0
2.0 1
3.0 1
ds[1] called __getitem__(1) and got the pair (2.0, 1). The for x, y in ds loop worked with no extra code: when an object has __getitem__ and no other way to loop, Python asks for item 0, 1, 2, … until it gets an IndexError.
A class instance is a changeable object, so the sticky-note rule applies: two names for one dataset share it.
Errors and exceptions
You met NameError in P0.4. Python has many error types, and each one is a hint. When code fails, Python raises an exception, and the program stops, unless you catch it. Here are the ones you will see most:
IndexError: a list position that does not exist, such as[1, 2, 3][5].KeyError: a dict key that is not there, such as{"a": 1}["b"].TypeError: the wrong kind of value for an operation, such as"2" + 2, or changing a tuple.ValueError: the right type but a bad value, such asint("abc").AttributeError: an attribute or method that does not exist, such asNone.append(1). Very often the value isNonewhen you expected a list.ZeroDivisionError: dividing by zero,1 / 0.UnboundLocalError: using a local name before it has a value (see the scope note above).
Reading a traceback
When an error escapes, Python prints a traceback: the chain of calls that led to it, oldest first, ending with the error line. This is a short program saved as train.py:
def mean(values):
return sum(values) / len(values)
def report(batches):
for b in batches:
print(mean(b))
report([[1, 2, 3], []])
It prints 2.0 and then fails. Your computer shows this (the ^^^ marks depend on your Python version, and the file paths are your own):
Traceback (most recent call last):
File "train.py", line 8, in <module>
report([[1, 2, 3], []])
File "train.py", line 6, in report
print(mean(b))
File "train.py", line 2, in mean
return sum(values) / len(values)
ZeroDivisionError: division by zero
Read it from the bottom: the error type and message (ZeroDivisionError), then the line that raised it (line 2), then the lines above it, which are the callers. The line that raised the error is not always the line that is wrong: here mean did what it was told, and the real cause is that an empty batch [] was passed in at line 8. Ask “which value was unexpected, and where did it come from?”
try and except
try / except lets you handle an error you expect and can recover from. Name the error type, so you do not hide real bugs.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
list index IndexError
dict key KeyError
str plus int TypeError
bad int ValueError
None method AttributeError
divide by zero ZeroDivisionError
tuple item TypeError
caught: invalid literal for int() with base 10: 'abc'
(The tests are lambdas so each could be run inside the same try; normally you put the risky line itself in the try.) A few rules: catch the narrowest error you can name (except ValueError), and avoid a bare except: that swallows everything, including your typos. Use raise ValueError("message") to signal a problem yourself. For a bug, it is usually better to let the program stop with a clear traceback than to hide the error.
Modules, imports and type hints
A module is a file of Python code, and import brings it in. The standard library comes with Python and has tools you will use all the time: math (square roots, pi), random, collections (such as Counter), json, and itertools. There are three forms:
import math # use as math.sqrt(16)
import numpy as np # a short name; everyone writes np
from collections import Counter # bring in one name
Libraries outside the standard library (NumPy, pandas, PyTorch) must be installed first. On this site, NumPy is available and loads when your cell imports it. On your own computer you install packages with pip (P2.8).
Type hints are optional notes about the types a function expects: def mean(xs: list[float]) -> float:. Python does not enforce them when the code runs; they help readers and tools such as editors and type checkers. You will see them in most modern ML code, and you may skip them in your own small scripts.
Idioms you will see in ML code
A handful of patterns appear again and again. Recognising them makes other people’s code readable.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
4.0 3.1416
[('the', 3), ('and', 2)]
3 0
[('ann', 3.9), ('cy', 3.7), ('bo', 3.2)]
('ann', 3.9)
True True
for x, y in zip(xs, ys):walks two lists together (features and labels, predictions and targets).for i, item in enumerate(items):gives a counter for free (start=1to count from 1).for key, value in d.items():walks a dict.sorted(items, key=..., reverse=True)sorts by any rule: thekeyfunction turns each item into the value to compare.max(items, key=...)andmintake the samekey. This is how you find the class with the highest score.Countercounts items (a missing item counts 0, with noKeyError), and.most_common(k)lists the top .any(...)andall(...)ask whether some, or every, item passes a test.sum(...),min(...),max(...),len(...)work on any list of numbers.
Where plain lists stop
Lists hold numbers too, but they are not made for number crunching. + joins lists and * repeats them, so they do not add or multiply entries, and you need a loop or a comprehension for the maths. Even the dot product of P1.B3 needs zip:
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
[3, 1, 1, 2.5]
[3, 1, 3, 1]
5.5
That 5.5 is the same dot product as in P1.B3. It works, but each number is a separate Python object, and a loop in Python does one step at a time. For arrays of thousands or millions of numbers this gets slow. NumPy (P2.2) stores numbers in one block, does a * b and a @ b in a single operation, and is the tool for arrays. Keep lists and dicts for what they are good at: records, words, settings, results.
Go deeper Iterators and generators: how loops get their items
A for loop asks its object for an iterator, and then asks that iterator for one item at a time. A generator function is a function that uses yield instead of return: it hands out one item, pauses, and continues when asked for the next. Nothing is computed until the loop asks. This is how data loaders hand out one batch at a time without holding every batch in memory.
def batches(items, size):
for start in range(0, len(items), size):
yield items[start:start + size]
for b in batches([1, 2, 3, 4, 5], 2):
print(b)[1, 2]
[3, 4]
[5]A generator can be used only once: after it is used up, looping over it again gives nothing. g = (x * x for x in range(3)) is a generator, and list(g) gives [0, 1, 4] the first time and [] the second time. A list, by contrast, can be looped over again and again.
Go deeper Files, the with statement and other things left for later
On your own computer you read a file with with open("data.txt") as f:; the with block closes the file for you when it ends. Cells on this site have no files of yours to read, so the lessons here keep their data in the code. Other topics that are useful but not needed yet: global and nonlocal (changing a name from an outer scope), decorators (the @something line above a function), dataclasses (a short way to write classes that mostly hold data), and virtual environments (P2.8).
Bugs that catch every beginner
b = aand then changingb: you seeachanged too. Fix:b = a.copy(), orcopy.deepcopy(a)for nested lists.[[0] * n] * mfor a grid: you see changing one row changes all. Fix:[[0] * n for _ in range(m)].def f(x, bag=[]): you see the list remembers earlier calls. Fix: defaultNone, make the list inside.x = x.sort(): you seexisNone. Fix:x.sort()alone, orx = sorted(x).- looping twice over a generator: you see the second loop does nothing. Fix: make a list first, or build the generator again.
0.1 + 0.2 == 0.3: you seeFalse. Fix: compare with a tolerance (math.isclose).7 / 2when you wanted whole numbers: you see3.5. Fix:7 // 2for floor division.zipof two lists of different length: you see the extra items vanish silently. Fix: checklen, orzip(..., strict=True)."2" + 2: you seeTypeError. Fix: convert:int("2") + 2.d["missing"]: you seeKeyError. Fix:d.get("missing", default).- indentation off by one space: you see
IndentationError, or code in the wrong block. Fix: four spaces for each level, always.
Practice: in-browser exercises
Each task has a short cell, the output to aim for, and a hidden answer. Write your own solution first. Then press Run and compare the output with the one shown.
1. f-strings. correct is 87 and total is 120. Print the accuracy as a percent with one decimal.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output: Accuracy: 72.5%
Show answer
print(f"Accuracy: {correct / total:.1%}"). The format .1% multiplies by 100, adds the percent sign and keeps one digit after the point.2. Slicing. For a = list(range(10, 20)), print the last three items and then every second item from the start.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output:
[17, 18, 19]
[10, 12, 14, 16, 18]
Show answer
print(a[-3:]) and print(a[::2]).3. Counting with a dict. Count how many times each letter appears in "banana", without Counter.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output: {'b': 1, 'a': 3, 'n': 2}
Show answer
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)counts.get(ch, 0) gives 0 for a letter not seen yet, so there is no KeyError. The keys appear in the order the letters were first seen.
4. A function and a comprehension. Write normalize(xs) that rescales a list to the range 0 to 1: subtract the smallest value and divide by (largest minus smallest).
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output: [0.0, 0.25, 0.5, 1.0]
Show answer
def normalize(xs):
lo, hi = min(xs), max(xs)
return [(x - lo) / (hi - lo) for x in xs]With lo = 2 and hi = 10, the value 4 becomes . If every value is the same, hi - lo is 0 and you get a ZeroDivisionError: real code must decide what to do then.
5. A class. Write a class RunningMean with a method add(x) that remembers the total and the count, and a method mean(). Add 2, 4 and 9.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output: 3 5.0
Show answer
class RunningMean:
def __init__(self):
self.total = 0.0
self.count = 0
def add(self, x):
self.total += x
self.count += 1
def mean(self):
return self.total / self.countThe attributes total and count live on the instance (self), so they survive between calls of add. This is the same idea as keeping a running average of the loss during training.
6. Find the bug. The goal is to keep the original order in backup and sort scores. The output should be [3, 1, 2] [1, 2, 3]. Run it as it is first, and look at what it prints.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output after the fix: [3, 1, 2] [1, 2, 3]
Show answer
The buggy version prints[1, 2, 3] [1, 2, 3], because backup = scores is a second name for the same list, and sort() changes the list in place. Change the second line to backup = scores.copy().Mini project: a tiny word classifier
Now put the pieces together. This program has a class that holds labelled text reviews, a train and test split, a word counter and a classifier made only of lists, dicts and functions. The idea of the classifier: count how often each word appears in positive and in negative reviews, and score a new text by adding, for each of its words, (positive count minus negative count). A positive total says “positive”.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
10 8 2
overlap: set()
positive: [('great', 3), ('loved', 2), ('acting', 2)]
negative: [('boring', 2), ('slow', 2), ('not', 2)]
'great fun' -> 1
'slow and bad' -> 0
'loved it' -> 1
What each part did:
TextDatasetis theDatasetidea again, with__len__and__getitem__, plus asplitmethod that shuffles the positions (not the data), takes the first part as the test set and the rest as the training set. Shuffling before splitting stops the split from depending on how the file was ordered. The two parts do not overlap, asoverlap: set()confirms. P3.A4 explains why we hold out test data.word_countsloops over the data and usesCounter.updateto add the words of each matching review.pos[w]for a word never seen gives 0.predictis a sum over a generator expression.1 if score > 0 else 0is a one-lineif.- The seed makes the shuffle repeatable (P1.G3), but Python does not promise the same shuffle across versions. So the program prints only what never depends on the shuffle (the sizes and the overlap), and the counts and predictions use all ten reviews.
Do not do this in a real project: see Exercise 8. This is a toy, and an honest one: the classifier was counted on all ten reviews and then tried on texts, so it says nothing about how it would do on new data. The next step, which is Exercise 8, is to count on train only and measure on test.
Common misconceptions
Check yourself
Check your understanding
After
a = [1, 2, 3],b = aandb.append(4), what isa?b = aattaches a second name to the same list, so appending throughbchanges the one list that both names point to. A copy (a.copy()) would have kept[1, 2, 3]. Lists can be changed in place; tuples cannot.A function is defined as
def add(x, bag=[]): bag.append(x); return bag. What does the second calladd(2)return, if the first call wasadd(1)?The default list is created once when the function is defined, so both calls append to the same list. The function that starts with
bag=Noneand makes a new list inside would return[2]. There is no error: the default is a real list.What does
-7 // 2give in Python?Floor division rounds down, toward minus infinity, and -3.5 rounded down is -4. The value -3 would be rounding toward zero, which is not what
//does. The float -3.5 is what/gives. Then-7 % 2is 1, because -4 times 2 plus 1 is -7.Which of these can be used as a key in a dict?
Keys must be hashable, which in practice means unchangeable. A tuple of numbers qualifies. Lists, sets and dicts can be changed in place, so Python refuses them as keys with a TypeError.
What does
list(zip([1, 2, 3], ["a", "b"]))give?zipstops when the shorter input runs out, so the 3 is silently dropped. It does not pad with None and does not raise an error unless you passstrict=True. Pairing item by item gives (1, a) and (2, b), not two groups.You write a class with the methods
__len__and__getitem__. Which statements now work on an instanceds?The built-in
lencalls__len__, and square brackets call__getitem__, on any object that defines them. No inheritance is needed. A PyTorch map-style Dataset must define__getitem__, and in practice also__len__, because samplers and the DataLoader use it.
Exercises
Try each one in a box first. Then open the answer.
- For
a = [5, 6, 7, 8, 9], what area[-2],a[1:3]anda[::-1][:2]?Show answer
8,[6, 7]and[9, 8]. The reversed list is[9, 8, 7, 6, 5], and its first two items are 9 and 8. - What does this print:
x = [1, 2],y = x,y += [3],z = x + [4],print(x, y, z)?Show answer
[1, 2, 3] [1, 2, 3] [1, 2, 3, 4]. The+=extended the shared list in place, soxchanged, andx + [4]built a new list inz. - Write
count_labels(labels)that returns a dict of how often each label occurs. For["cat", "dog", "cat"]it should give{'cat': 2, 'dog': 1}.Show answer
Loop over the labels and usecounts[lab] = counts.get(lab, 0) + 1, then returncounts. (collections.Counterdoes the same.) - From
words = ["a", "tree", "is", "green"], build a dict from each word to its length, keeping only words longer than 3 letters.Show answer
{w: len(w) for w in words if len(w) > 3}gives{'tree': 4, 'green': 5}. mean([])crashes withZeroDivisionError. Changemeanso it returnsNonefor an empty list.Show answer
if not xs: return Nonebefore the division, because an empty list is false. Thenmean([1, 2, 3])is2.0andmean([])isNone. Whoever calls it must then handleNone, or you meet anAttributeErroror aTypeErrorlater.- Add a method
batches(size)to theDatasetclass that returns a list of lists, each with at mostsizeexamples. For 3 examples andsize=2the result is[[(1.0, 0), (2.0, 1)], [(3.0, 1)]].Show answer
return [[self[i] for i in range(s, min(s + size, len(self)))] for s in range(0, len(self), size)]. The outer loop steps through the starting positions 0, 2, …;min(...)stops the last batch at the end of the data. A data loader (P2.7) does this idea for you. - In the traceback shown earlier, the error is raised in
meanon line 2. Which line would you change to fix the bug, and why?Show answer
It depends on what you want. The data contained an empty batch[](line 8). Either remove empty batches where the data is made, or makemeanhandle an empty list on purpose. The line that raises an error is where Python noticed the problem, and the cause can be earlier. - Extend the mini project: count words on
trainonly, then measure the fraction oftesttexts thatpredictgets right. Is the number reliable with a test set of two?Show answer
Usepos = word_counts(train, 1)andneg = word_counts(train, 0), thensum(predict(t, pos, neg) == y for t, y in test) / len(test). With two test items the accuracy can only be 0, 0.5 or 1, so one example changes it by 50 percentage points: it is far too noisy to trust. Real projects use much more data, and the number can change with the seed of the shuffle (P1.G3).
Go deeper Inheritance: a class built from another class
Inheritance makes a new class that starts as a copy of another and changes a little. super().__init__(...) calls the parent’s set-up. It is common in PyTorch, where your model inherits from nn.Module (P2.7), and otherwise best used sparingly.
class ScaledDataset(Dataset):
def __init__(self, xs, ys, factor):
super().__init__([x * factor for x in xs], ys)
sd = ScaledDataset([1.0, 2.0, 3.0], [0, 1, 1], 10)
print(sd[1], sd.mean_label(), isinstance(sd, Dataset))(20.0, 1) 0.6666666666666666 Trueisinstance(obj, Class) asks whether an object belongs to a class, or to a class built from it.