How does a machine know you wrote a 3?Comment une machine sait-elle que tu as écrit un 3 ?
Write one, then follow it through the machine a step at a time, down to the numbers. Everything you see is computed from your own drawing.Écris-en un, puis suis-le à travers la machine, étape par étape, jusqu'aux nombres. Tout ce que tu vois est calculé à partir de ton propre dessin.
A guidegdm course by Gedeon Matabaro. The machine runs on your device.Un cours guidegdm de Gedeon Matabaro. La machine tourne sur ton appareil.
Chapter 1, part 2Chapitre 1, partie 2
From your digit to an answer, written outDe ton chiffre à une réponse, en détail
Part 1 showed the machine working. This part is the written lesson: every step as maths, then as Python you can run, with the real output. Each section links back to the screen in part 1 where you saw it happen.
La partie 1 montrait la machine en action. Cette partie est la leçon écrite : chaque étape en maths, puis en Python que tu peux lancer, avec le vrai résultat. Chaque section renvoie à l'écran de la partie 1 où tu l'as vu se passer.
0. Where to run the code0. Où lancer le code
Open colab.research.google.com and sign in with a Google account. It is free and needs nothing installed.
Choose New notebook.
Paste each code block below into its own cell, in order, and press the play button on the left of the cell.
Ouvre colab.research.google.com et connecte-toi avec un compte Google. C'est gratuit et rien n'est à installer.
Choisis Nouveau notebook.
Colle chaque bloc de code ci-dessous dans sa propre cellule, dans l'ordre, et appuie sur le bouton lecture à gauche de la cellule.
Two libraries are used. NumPy does arithmetic on whole tables of numbers at once. TensorFlow is only used here to download the digits.
Deux bibliothèques sont utilisées. NumPy fait des calculs sur des tableaux entiers de nombres d'un coup. TensorFlow sert ici seulement à télécharger les chiffres.
1. The data: 60,000 labelled digits1. Les données : 60 000 chiffres étiquetés
MNIST is a set of handwritten digits collected from real people. Each image comes with a label: the digit it really is, written down by a person. A set of examples with their right answers is called a labelled dataset. This chapter only reads it; chapter 2 uses the labels to learn.
MNIST est un ensemble de chiffres écrits à la main par de vraies personnes. Chaque image vient avec une étiquette : le chiffre que c'est vraiment, noté par une personne. Un ensemble d'exemples avec leurs bonnes réponses s'appelle un jeu de données étiqueté. Ce chapitre ne fait que le lire ; le chapitre 2 utilise les étiquettes pour apprendre.
import numpy as np
from tensorflow.keras.datasets import mnist
(images, labels), _ = mnist.load_data()
print(images.shape, labels[:10])
(60000, 28, 28) [5 0 4 1 9 2 1 3 1 4]
images.shape reads as: 60,000 images, each 28 rows by 28 columns. The first ten labels say the first image is a 5, the second a 0, and so on.
images.shape se lit : 60 000 images, chacune de 28 lignes sur 28 colonnes. Les dix premières étiquettes disent que la première image est un 5, la deuxième un 0, et ainsi de suite.
2. An image is a matrix2. Une image est une matrice
A matrix is a table of numbers arranged in rows and columns. A 28 × 28 image is a matrix with 28 rows and 28 columns, so 784 numbers. We write the number in row r and column c as xr,c. See it in part 1, screen 3 →
Une matrice est un tableau de nombres rangés en lignes et en colonnes. Une image de 28 × 28 est une matrice de 28 lignes et 28 colonnes, soit 784 nombres. On note le nombre de la ligne r et de la colonne c : xr,c. Le voir dans la partie 1, écran 3 →
Image number 7 is a 3. img[10:17, 10:17] takes rows 10 to 16 and columns 10 to 16 (Python counts from 0): a 7 × 7 close-up, like the yellow box in part 1. The numbers here go from 0 to 255, not 0 to 1. The next section explains why.
L'image numéro 7 est un 3. img[10:17, 10:17] prend les lignes 10 à 16 et les colonnes 10 à 16 (Python compte à partir de 0) : un zoom de 7 × 7, comme le carré jaune de la partie 1. Ici les nombres vont de 0 à 255, pas de 0 à 1. La section suivante explique pourquoi.
3. Why 0 to 255, and why divide by 2553. Pourquoi 0 à 255, et pourquoi diviser par 255
Computer memory stores only bits: each bit is 0 or 1. With 8 bits there are 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 28 = 256 possible patterns, which can stand for the whole numbers 0 to 255. Eight bits are called a byte. Storing each square as one byte is cheap and precise enough for the eye, so image files use 0 (no ink) to 255 (full ink). See it in part 1, screen 4 →
La mémoire d'un ordinateur ne garde que des bits : chaque bit vaut 0 ou 1. Avec 8 bits, il y a 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 28 = 256 combinaisons, qui peuvent représenter les nombres entiers de 0 à 255. Huit bits s'appellent un octet. Garder chaque case dans un octet est économique et assez précis pour l'œil, donc les fichiers d'image utilisent 0 (pas d'encre) à 255 (encre pleine). Le voir dans la partie 1, écran 4 →
For the arithmetic we divide every value by 255, so each square becomes a number between 0 and 1:
Pour les calculs, on divise chaque valeur par 255, et chaque case devient un nombre entre 0 et 1 :
x = stored value255for example:171255 ≈ 0.67
x = valeur gardée255par exemple :171255 ≈ 0,67
This is called scaling or normalising. It does not change the picture; it only changes the units, the way you can write 50 cm as 0.5 m. Keeping inputs between 0 and 1 keeps the later sums small and makes training (chapter 2) behave well.
Cela s'appelle mettre à l'échelle ou normaliser. Ça ne change pas l'image, seulement l'unité, comme écrire 50 cm sous la forme 0,5 m. Garder les entrées entre 0 et 1 garde les sommes petites et aide l'entraînement (chapitre 2) à bien se passer.
4. Unrolling the matrix into a vector4. Dérouler la matrice en vecteur
A vector is a list of numbers in a fixed order. We put row 1 first, then row 2 after it, and so on, to get one list of 784 numbers: x1, x2, …, x784. The square in row r and column c lands at position i = 28 × (r − 1) + c. For example, row 14, column 14 lands at position 28 × 13 + 14 = 378. See it in part 1, screen 6 →
Un vecteur est une liste de nombres dans un ordre fixe. On met la ligne 1, puis la ligne 2 à la suite, et ainsi de suite, pour obtenir une seule liste de 784 nombres : x1, x2, …, x784. La case de la ligne r et de la colonne c arrive à la position i = 28 × (r − 1) + c. Par exemple, ligne 14, colonne 14 arrive à la position 28 × 13 + 14 = 378. Le voir dans la partie 1, écran 6 →
x = img / 255.0
x = x.reshape(784)
print(x.shape, x.min(), x.max())
(784,) 0.0 1.0
img / 255.0 divides all 784 values at once. reshape(784) unrolls the 28 × 28 matrix into a vector, row after row. The output confirms 784 numbers, the smallest 0 and the largest 1.
img / 255.0 divise les 784 valeurs d'un coup. reshape(784) déroule la matrice de 28 × 28 en vecteur, ligne après ligne. Le résultat confirme 784 nombres, le plus petit 0 et le plus grand 1.
5. The weighted sum5. La somme pondérée
A weight is a number that says how much one input counts. Positive means the input is evidence for the answer, negative means evidence against, and close to 0 means it barely matters. Multiply each input by its weight, add the results, then add one more number called the bias, the starting score before any input is looked at:
Un poids est un nombre qui dit combien une entrée compte. Positif veut dire un indice pour la réponse, négatif un indice contre, et proche de 0 qu'elle compte à peine. On multiplie chaque entrée par son poids, on additionne, puis on ajoute un dernier nombre, le biais : le score de départ avant de regarder les entrées :
s = w1x1 + w2x2 + … + wnxn + bthe same thing, written short:s = Σi=1…n wixi + b
s = w1x1 + w2x2 + … + wnxn + bla même chose, en abrégé :s = Σi=1…n wixi + b
Read it from left to right: s, the score we want, equals every input times its weight, all added up, plus b. There is only one b, added once at the end. It is not computed by this line: like the weights, it is a number the machine already holds. Where its value comes from: training, which moves b a little after each mistake (chapter 2 adds or takes away 1, chapter 3 moves it by its slope).
The sign Σ (sigma) means "add up": Σi=1…n wixi means w1x1 + w2x2 + … + wnxn, the letter i counting from 1 to n. Worked example with the tiny machine from part 1, inputs 1, 0.5, 0, weights 2, −1, 3 and bias 0.5: see screens 7 and 8 →
Lis-la de gauche à droite : s, le score qu'on cherche, égale chaque entrée multipliée par son poids, le tout additionné, plus b. Il n'y a qu'un seul b, ajouté une fois à la fin. Cette ligne ne le calcule pas : comme les poids, c'est un nombre que la machine a déjà. D'où vient sa valeur : de l'entraînement, qui bouge b un peu après chaque erreur (le chapitre 2 ajoute ou retire 1, le chapitre 3 le déplace selon sa pente).
Le signe Σ (sigma) veut dire « additionner » : Σi=1…n wixi veut dire w1x1 + w2x2 + … + wnxn, la lettre i comptant de 1 à n. Exemple avec la petite machine de la partie 1, entrées 1 ; 0,5 ; 0, poids 2 ; −1 ; 3 et biais 0,5 : voir les écrans 7 et 8 →
np.dot multiplies the two lists position by position and adds the products. It is called the dot product. In this tiny example the weights were made up; in the real machine they are learned (chapter 2).
np.dot multiplie les deux listes position par position et additionne les produits. On appelle ça le produit scalaire. Dans ce petit exemple, les poids sont inventés ; dans la vraie machine, ils sont appris (chapitre 2).
6. Many weighted sums at once: matrix × vector6. Plusieurs sommes pondérées d'un coup : matrice × vecteur
The machine needs one score per possible answer, so it needs one row of weights per answer. Stack those rows into a matrix W. Multiplying W by the vector x means: for each row, take the dot product with x. Then add each row's own bias. With 2 rows and 3 inputs: see screen 15 →
La machine a besoin d'un score par réponse possible, donc d'une ligne de poids par réponse. On empile ces lignes dans une matrice W. Multiplier W par le vecteur x veut dire : pour chaque ligne, faire le produit scalaire avec x. Puis on ajoute le biais de chaque ligne. Avec 2 lignes et 3 entrées : voir l'écran 15 →
The sizes must fit: a matrix with 2 rows and 3 columns can only multiply a vector of 3 numbers, and it gives 2 numbers, one per row. In general, (rows × columns) times (columns) gives (rows). For the real machine: (10 × 784) times (784) gives 10 scores.
Les tailles doivent correspondre : une matrice de 2 lignes et 3 colonnes ne peut multiplier qu'un vecteur de 3 nombres, et elle donne 2 nombres, un par ligne. En général, (lignes × colonnes) fois (colonnes) donne (lignes). Pour la vraie machine : (10 × 784) fois (784) donne 10 scores.
In Python the @ sign is matrix multiplication. The first row gives 2, the tiny machine from section 5, and the second row gives −0.3.
En Python, le signe @ est la multiplication de matrices. La première ligne donne 2, la petite machine de la section 5, et la deuxième donne −0,3.
7. The real machine: 10 rows of 784 weights7. La vraie machine : 10 lignes de 784 poids
Now W has 10 rows, one per digit 0 to 9, and 784 columns, one per square. Row d holds the 784 weights for digit d, the grid you saw in white and red. b holds 10 biases. The score for digit d is see screens 10 to 13 →
Maintenant W a 10 lignes, une par chiffre de 0 à 9, et 784 colonnes, une par case. La ligne d contient les 784 poids du chiffre d, la grille blanche et rouge que tu as vue. b contient 10 biais. Le score du chiffre d est voir les écrans 10 à 13 →
sd = Σi=1…784 Wd,i xi + bdfor all ten digits at once:s = W x + b
sd = Σi=1…784 Wd,i xi + bdpour les dix chiffres d'un coup :s = W x + b
We have not learned any weights yet, so here we fill W with small random numbers to see the shapes work.
Nous n'avons encore appris aucun poids, donc on remplit W de petits nombres au hasard pour vérifier que les tailles marchent.
rng = np.random.default_rng(0)
W = rng.normal(0, 0.1, (10, 784))
b = np.zeros(10)
print(W.shape, b.shape)
(10, 784) (10,)
8. Ten scores, and the highest wins8. Dix scores, et le plus grand gagne
scores = W @ x + b
for d in range(10):
print(d, round(scores[d], 2))
print("answer:", scores.argmax())
argmax gives the position of the largest value. Here the largest score, 1.03, is at position 5, so the machine answers 5. The image is a 3: with random weights the answer is a guess. The machine in part 1 answered well because its weights had been learned. See screen 14 →
argmax donne la position de la plus grande valeur. Ici le plus grand score, 1,03, est à la position 5, donc la machine répond 5. L'image est un 3 : avec des poids au hasard, la réponse est devinée. La machine de la partie 1 répondait bien parce que ses poids avaient été appris. Voir l'écran 14 →
9. Counting the parameters9. Compter les paramètres
A parameter is a number the machine is allowed to change while it learns. Here the parameters are all the weights and all the biases: 10 × 784 + 10 = 7,850. See screen 17 →
Un paramètre est un nombre que la machine a le droit de changer en apprenant. Ici, les paramètres sont tous les poids et tous les biais : 10 × 784 + 10 = 7 850. Voir l'écran 17 →
print(W.size, b.size, W.size + b.size)
7840 10 7850
SummaryRésumé
An image is a 28 × 28 matrix of values from 0 to 255 (one byte each).
Divide by 255 and unroll it into a vector x of 784 numbers between 0 and 1.
Each digit has a row of 784 weights and one bias. Its score is a weighted sum.
All ten scores at once: s = W x + b, a matrix times a vector, plus a vector.
The answer is the position of the highest score.
W and b hold 7,850 parameters. Chapter 2: how to learn them from the labelled data.
Une image est une matrice de 28 × 28 valeurs de 0 à 255 (un octet chacune).
On divise par 255 et on la déroule en un vecteur x de 784 nombres entre 0 et 1.
Chaque chiffre a une ligne de 784 poids et un biais. Son score est une somme pondérée.
Les dix scores d'un coup : s = W x + b, une matrice fois un vecteur, plus un vecteur.
La réponse est la position du plus grand score.
W et b contiennent 7 850 paramètres. Chapitre 2 : comment les apprendre à partir des données étiquetées.
Where the weights come from, written outD'où viennent les poids, en détail
Part 1 showed a machine learning its own weights from real handwriting. This part writes every step as maths, then as Python you can run, with the real output. The numbers are the same ones you saw in part 1, because the page runs the same rule on the same 2,000 digits.
La partie 1 montrait une machine qui apprend ses propres poids à partir de vraies écritures. Cette partie écrit chaque étape en maths, puis en Python que tu peux lancer, avec le vrai résultat. Ce sont les mêmes nombres que dans la partie 1, parce que la page applique la même règle aux mêmes 2 000 chiffres.
0. Where to run the code0. Où lancer le code
Same as chapter 1: open colab.research.google.com, choose New notebook, paste each block into its own cell in order, and press play. Only NumPy is used for the learning; TensorFlow only downloads the digits.
Comme au chapitre 1 : ouvre colab.research.google.com, choisis Nouveau notebook, colle chaque bloc dans sa propre cellule dans l'ordre, et appuie sur lecture. Seul NumPy sert à apprendre ; TensorFlow ne fait que télécharger les chiffres.
1. Learning digits and test digits1. Chiffres pour apprendre, chiffres pour tester
We take the first 2,000 labelled pictures to learn from. This is the training set. We also take 500 pictures the machine will never learn from, to check it afterwards. This is the test set. Each picture is unrolled into 784 numbers between 0 and 1, exactly as in chapter 1. See it in part 1, screen 4 →
On prend les 2 000 premières images étiquetées pour apprendre. C'est le jeu d'entraînement. On prend aussi 500 images dont la machine n'apprendra jamais rien, pour la vérifier ensuite. C'est le jeu de test. Chaque image est déroulée en 784 nombres entre 0 et 1, exactement comme au chapitre 1. Le voir dans la partie 1, écran 4 →
import numpy as np
from tensorflow.keras import datasets
mnist = datasets.mnist.load_data()
# 60,000 training pictures + labels
train_imgs, train_labels = mnist[0]
# 10,000 test pictures + labels
test_imgs, test_labels = mnist[1]
# X: 2,000 pictures, 784 numbers each
X = train_imgs[:2000].reshape(-1, 784)
X = X / 255
# Y: the right digit for each one
Y = train_labels[:2000]
# Xt, Yt: 500 pictures kept for testing
Xt = test_imgs[:500].reshape(-1, 784)
Xt = Xt / 255
Yt = test_labels[:500]
print(X.shape, Xt.shape)
print(Y[:12])
(2000, 784) (500, 784)
[5 0 4 1 9 2 1 3 1 4 3 5]
What each name holdsCe que contient chaque nom
mnist
the whole MNIST download: training part and test parttout le téléchargement MNIST : partie entraînement et partie test
train_imgs
60,000 training pictures, each a 28 × 28 grid of numbers 0 to 25560 000 images d'entraînement, chacune une grille 28 × 28 de nombres de 0 à 255
train_labels
the right digit for each of those 60,000le bon chiffre pour chacune de ces 60 000
test_imgs, test_labels
10,000 more pictures and their digits, kept apart10 000 autres images et leurs chiffres, gardées à part
X
the first 2,000 training pictures, each unrolled into 784 numbers from 0 to 1. Shape (2000, 784): one row per pictureles 2 000 premières images d'entraînement, chacune déroulée en 784 nombres de 0 à 1. Forme (2000, 784) : une ligne par image
Y
their 2,000 labels: Y[0] is the digit in picture 0leurs 2 000 étiquettes : Y[0] est le chiffre de l'image 0
Xt, Yt
500 test pictures and their labels, the same way. The t is for test500 images de test et leurs étiquettes, de la même façon. Le t veut dire test
X.shape reads as 2,000 rows of 784 numbers: one row per picture. The labels say the first picture is a 5, the second a 0, and so on. These are the digits on the wall in part 1.
X.shape se lit 2 000 lignes de 784 nombres : une ligne par image. Les étiquettes disent que la première image est un 5, la deuxième un 0, et ainsi de suite. Ce sont les chiffres du mur dans la partie 1.
2. Start from zero2. Partir de zéro
All 7,840 weights and all 10 biases start at 0. The scores are the same weighted sums as chapter 1, s = W x + b, so every score is 0. The guess is the position of the largest score; this is called the argmax. When several scores are equal, NumPy's argmax takes the first, so the guess is 0. See it in part 1, screen 3 →
Les 7 840 poids et les 10 biais commencent à 0. Les scores sont les mêmes sommes pondérées qu'au chapitre 1, s = W x + b, donc chaque score vaut 0. La réponse est la position du plus grand score ; on l'appelle l'argmax. Quand plusieurs scores sont égaux, argmax de NumPy prend le premier, donc la réponse est 0. Le voir dans la partie 1, écran 3 →
# W: 10 rows of 784 weights, all 0
W = np.zeros((10, 784))
# b: one bias per digit, all 0
b = np.zeros(10)
# the ten scores for the first picture
scores = W @ X[0] + b
print(scores)
print('guess', scores.argmax())
print('label', Y[0])
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
guess 0
label 5
What each name holdsCe que contient chaque nom
W
the weights: 10 rows (one per digit) of 784 numbers (one per square)les poids : 10 lignes (une par chiffre) de 784 nombres (un par case)
b
the 10 biases, one per digitles 10 biais, un par chiffre
scores
the 10 scores for picture 0: W @ X[0] + bles 10 scores de l'image 0 : W @ X[0] + b
@ is Python's sign for matrix multiplication, the W x of chapter 1.
@ est le signe de Python pour le produit de matrices, le W x du chapitre 1.
3. One nudge, and why it works3. Une correction, et pourquoi elle marche
First with 3 numbers. Take an example x = [1, 0.5, 0] and weights w = [0, 0, 0]. The score is 0. Now add the example to the weights: w becomes [1, 0.5, 0]. The new score on the same example is:
D'abord avec 3 nombres. Prenons un exemple x = [1 ; 0,5 ; 0] et des poids w = [0 ; 0 ; 0]. Le score vaut 0. Ajoutons l'exemple aux poids : w devient [1 ; 0,5 ; 0]. Le nouveau score sur le même exemple est :
1 × 1 + 0.5 × 0.5 + 0 × 0= 1 + 0.25 + 0 = 1.25
1 × 1 + 0,5 × 0,5 + 0 × 0= 1 + 0,25 + 0 = 1,25
The score went up by exactly x₁ × x₁ + x₂ × x₂ + x₃ × x₃. That is no accident. For any weights w, adding x gives:
Le score a monté de exactement x₁ × x₁ + x₂ × x₂ + x₃ × x₃. Ce n'est pas un hasard. Pour n'importe quels poids w, ajouter x donne :
(w + x) · x = w · x + x · xx · x = x12 + x22 + … + x7842 ≥ 0
The dot · is the dot product from chapter 1: multiply position by position, then add. A number times itself (its square, written x²) is never negative, so adding x to a digit's weights can only raise that digit's score on x. Taking x away lowers it by the same amount. On example 1 of the real data, x · x = 91.35. See it in part 1, screens 7 and 8 →
Le point · est le produit scalaire du chapitre 1 : multiplier position par position, puis additionner. Un nombre multiplié par lui-même (son carré, noté x²) n'est jamais négatif, donc ajouter x aux poids d'un chiffre ne peut que monter le score de ce chiffre sur x. Retirer x le baisse d'autant. Sur l'exemple 1 des vraies données, x · x = 91,35. Le voir dans la partie 1, écrans 7 et 8 →
# x: picture 1, y: its label
x, y = X[0], Y[0]
# g: the machine's guess
g = (W @ x + b).argmax()
W[y] += x; b[y] += 1 # help y
W[g] -= x; b[g] -= 1 # push g down
print(round(x @ x, 2))
# s: the ten scores after the nudge
s = W @ x + b
print(s[0].round(2), s[5].round(2))
print('guess now', s.argmax())
its label, the right digit (here 5)son étiquette, le bon chiffre (ici 5)
g
the machine's guess, the digit with the highest score (here 0)la réponse de la machine, le chiffre au plus grand score (ici 0)
W[y]
row y of W: the 784 weights of the right digitla ligne y de W : les 784 poids du bon chiffre
s
the 10 scores after the nudgeles 10 scores après la correction
s[5] is the score for 5: it went from 0 to 91.35 + 1 = 92.35 (the 1 is the bias). s[0], the score for 0, went down by the same amount. The other eight scores stay 0. W[y] += x means "replace row y of W by itself plus x".
s[5] est le score du 5 : il est passé de 0 à 91,35 + 1 = 92,35 (le 1 est le biais). s[0], le score du 0, a baissé d'autant. Les huit autres scores restent à 0. W[y] += x veut dire « remplacer la ligne y de W par elle-même plus x ».
4. The whole rule: the perceptron4. La règle entière : le perceptron
For each example x with label y: compute the guess g = argmax(W x + b). If g = y, change nothing. If g ≠ y, apply four updates. The arrow ← means "replace by":
Pour chaque exemple x d'étiquette y : on calcule la réponse g = argmax(W x + b). Si g = y, on ne change rien. Si g ≠ y, on fait quatre mises à jour. La flèche ← veut dire « remplacer par » :
wy ← wy + x by ← by + 1wg ← wg − x bg ← bg − 1
This is the perceptron rule, published by Frank Rosenblatt in 1958. It only acts on mistakes. See it in part 1, screen 9 →
5. Training: the rule on every example5. L'entraînement : la règle sur chaque exemple
Training means running the rule over the examples, one after another. One pass through the whole training set is called an epoch. Here we make one pass. See it in part 1, screen 10 →
Entraîner, c'est appliquer la règle aux exemples, l'un après l'autre. Un passage sur tout le jeu d'entraînement s'appelle une époque. Ici, on fait un seul passage. Le voir dans la partie 1, écran 10 →
# n: how many examples to learn from
def train(n):
W = np.zeros((10, 784))
b = np.zeros(10)
mistakes = 0 # wrong guesses
for i in range(n): # i: example
x, y = X[i], Y[i]
g = (W @ x + b).argmax()
if g != y: # wrong: nudge
W[y] += x; b[y] += 1
W[g] -= x; b[g] -= 1
mistakes += 1
return W, b, mistakes
# share of the pictures guessed right
def accuracy(W, b, X, Y):
s = X @ W.T + b # all scores
guesses = s.argmax(axis=1)
return (guesses == Y).mean()
# m: mistakes made while training
W, b, m = train(2000)
print('mistakes:', m)
print('own:', accuracy(W, b, X, Y))
print('new:', accuracy(W, b, Xt, Yt))
mistakes: 554
own: 0.8455
new: 0.8
What each name holdsCe que contient chaque nom
n
how many examples train() learns fromcombien d'exemples train() utilise pour apprendre
i
the number of the example being looked at: 0, 1, 2, …le numéro de l'exemple regardé : 0, 1, 2, …
mistakes, m
how many wrong guesses during trainingcombien de mauvaises réponses pendant l'entraînement
s (in accuracy)
all the scores at once: one row of 10 per picturetous les scores d'un coup : une ligne de 10 par image
guesses
the guessed digit for every picturele chiffre répondu pour chaque image
accuracy scores many pictures at once: X @ W.T + b is the matrix of all their scores, one row per picture, argmax(axis=1) takes each row's guess, and .mean() of the true/false comparisons is the share that are right. "own" is on the 2,000 training digits, "new" on the 500 test digits. Accuracy = right answers ÷ all answers.
accuracy note beaucoup d'images d'un coup : X @ W.T + b est la matrice de tous leurs scores, une ligne par image, argmax(axis=1) prend la réponse de chaque ligne, et .mean() des comparaisons vrai/faux donne la part de justes. « own » porte sur les 2 000 chiffres d'entraînement, « new » sur les 500 du test. La précision = réponses justes ÷ toutes les réponses.
6. Why the test digits are the ones that count6. Pourquoi ce sont les chiffres du test qui comptent
85 % on the training digits, 80 % on the test digits. The machine will be used on drawings it has never seen, like yours, so the test number is the honest one. Doing well on new data is called generalising. See it in part 1, screen 12 →
85 % sur les chiffres d'entraînement, 80 % sur ceux du test. La machine servira sur des dessins qu'elle n'a jamais vus, comme le tien, donc c'est le chiffre du test qui est honnête. Bien faire sur des données nouvelles s'appelle généraliser. Le voir dans la partie 1, écran 12 →
7. More data, less learning by heart7. Plus de données, moins de par cœur
for n in [50, 500, 2000]:
W, b, m = train(n)
# own: right on its n examples
own = accuracy(W, b, X[:n], Y[:n])
# new: right on the 500 test ones
new = accuracy(W, b, Xt, Yt)
print(n, round(own, 3), round(new, 3))
50 0.66 0.43
500 0.756 0.612
2000 0.846 0.8
What each name holdsCe que contient chaque nom
own
accuracy on the n examples it learned fromprécision sur les n exemples appris
new
accuracy on the 500 test picturesprécision sur les 500 images de test
Each line reads: number of examples, accuracy on its own digits, accuracy on the test digits. With 50 examples the gap between its own digits (66 %) and new digits (43 %) is large: it fitted those few pictures instead of the shapes of digits. This is called overfitting. With 2,000 the gap shrinks to about 5 points. The chapter 1 machine reaches 91.7 % with all 60,000 digits and a better method. See it in part 1, screen 14 →
Chaque ligne se lit : nombre d'exemples, précision sur ses propres chiffres, précision sur le test. Avec 50 exemples, l'écart entre ses propres chiffres (66 %) et les nouveaux (43 %) est grand : elle a collé à ces quelques images au lieu de la forme des chiffres. On appelle ça le surapprentissage. Avec 2 000, l'écart tombe à environ 5 points. La machine du chapitre 1 atteint 91,7 % avec les 60 000 chiffres et une meilleure méthode. Le voir dans la partie 1, écran 14 →
8. What the rule cannot see8. Ce que la règle ne voit pas
The rule asks one question: right or wrong? When the right digit's score is just below the guess, and when it is far below, the update is the same ±x. It also stops changing anything once an example is right, even barely right. Chapter 3 replaces "right or wrong" with a number that measures how wrong, called the loss, and moves every weight according to how much it affects that number. That method trained the chapter 1 weights. See it in part 1, screen 15 →
La règle pose une seule question : juste ou faux ? Que le score du bon chiffre soit juste en dessous de la réponse ou très loin, la correction est la même, ±x. Elle arrête aussi de changer quoi que ce soit dès qu'un exemple est juste, même de justesse. Le chapitre 3 remplace « juste ou faux » par un nombre qui mesure à quel point c'est faux, appelé la perte, et déplace chaque poids selon son effet sur ce nombre. C'est cette méthode qui a entraîné les poids du chapitre 1. Le voir dans la partie 1, écran 15 →
SummaryRésumé
Weights are not chosen by hand. They start at 0 and are learned from labelled examples (supervised learning).
The perceptron rule: on a mistake, add the example to the right digit's weights and subtract it from the guessed digit's weights; bias +1 and −1.
It works because x · x, a sum of squares, is never negative.
Training = the rule on every example; one pass = one epoch.
Judge a machine on a test set it never learned from. A big gap between training and test accuracy means overfitting.
More data helps. Chapter 3: measuring how wrong, and the slope that tells each weight which way to move.
Les poids ne sont pas choisis à la main. Ils partent de 0 et sont appris à partir d'exemples étiquetés (apprentissage supervisé).
La règle du perceptron : sur une erreur, on ajoute l'exemple aux poids du bon chiffre et on le retire des poids du chiffre répondu ; biais +1 et −1.
Elle marche parce que x · x, une somme de carrés, n'est jamais négatif.
Entraîner = la règle sur chaque exemple ; un passage = une époque.
On juge une machine sur un jeu de test dont elle n'a rien appris. Un grand écart entre entraînement et test veut dire surapprentissage.
Plus de données aide. Chapitre 3 : mesurer à quel point c'est faux, et la pente qui dit à chaque poids dans quel sens bouger.
Learning from how wrong it is, written outApprendre de son erreur, en détail
Part 1 replaced "right or wrong" with a number for how wrong, and followed its slope downhill. This part writes each step as maths and as Python, with the real output. The numbers are the ones you saw in part 1.
La partie 1 a remplacé « juste ou faux » par un nombre qui dit à quel point c'est faux, et a suivi sa pente vers le bas. Cette partie écrit chaque étape en maths et en Python, avec le vrai résultat. Ce sont les nombres de la partie 1.
0. Where to run the code0. Où lancer le code
Same as before: open colab.research.google.com, choose New notebook, and paste each block into its own cell, in order. Sections 1 to 4 need no data at all.
Comme avant : ouvre colab.research.google.com, choisis Nouveau notebook, et colle chaque bloc dans sa propre cellule, dans l'ordre. Les sections 1 à 4 n'ont besoin d'aucune donnée.
1. One weight and its loss1. Un poids et sa perte
The machine has one input x, one weight w, and we want its prediction p to equal a target t. The loss is the gap squared:
La machine a une entrée x, un poids w, et on veut que sa prédiction p soit égale à une cible t. La perte est l'écart au carré :
p = w × xL = (p − t)²with x = 0.8, t = 1, w = 0.5:L = (0.5 × 0.8 − 1)² = (−0.6)² = 0.36
p = w × xL = (p − t)²avec x = 0,8, t = 1, w = 0,5 :L = (0,5 × 0,8 − 1)² = (−0,6)² = 0,36
# x: one input, t: the target score
x, t = 0.8, 1.0
def loss(w):
p = w * x # p: the prediction
return (p - t) ** 2 # gap squared
w = 0.5 # w: the weight
print(loss(w))
0.36
What each name holdsCe que contient chaque nom
x
the one input, 0.8l'unique entrée, 0,8
t
the target, the score we want: 1la cible, le score voulu : 1
w
the one weight, starting at 0.5l'unique poids, qui commence à 0,5
p
the prediction, w × xla prédiction, w × x
loss(w)
the gap squared for a given weightl'écart au carré pour un poids donné
A function in Python, def loss(w), is a recipe: give it a weight, it gives back the loss. See it in part 1, screen 3 →
2. The slope, measured and exact2. La pente, mesurée et exacte
Nudge the weight by a tiny h and divide the change in loss by h. As h gets smaller, this ratio gets closer to the derivative, written dL/dw:
On pousse le poids d'un tout petit h et on divise la variation de la perte par h. Plus h est petit, plus ce rapport s'approche de la dérivée, notée dL/dw :
dL/dw ≈ ( L(w + h) − L(w) ) ÷ h
dL/dw ≈ ( L(w + h) − L(w) ) ÷ h
h = 0.001 # h: a tiny nudge
# slope: change in loss ÷ change in w
slope = (loss(w + h) - loss(w)) / h
print(round(slope, 4))
# the exact rule
print(2 * (w * x - t) * x)
-0.9594
-0.96
What each name holdsCe que contient chaque nom
h
the tiny nudge, 0.001la toute petite poussée, 0,001
slope
change in loss ÷ change in wvariation de la perte ÷ variation de w
The measured −0.9594 is close to the exact −0.96. The exact rule comes from two facts. The slope of u² is 2u. And u = w x − t changes by x each time w grows by 1. Multiply the two:
Le −0,9594 mesuré est proche du −0,96 exact. La règle exacte vient de deux faits. La pente de u² est 2u. Et u = w x − t change de x chaque fois que w grandit de 1. On multiplie les deux :
dL/dw = 2 (w x − t) × x= 2 × (−0.6) × 0.8 = −0.96
dL/dw = 2 (w x − t) × x= 2 × (−0,6) × 0,8 = −0,96
Multiplying slopes along a chain of steps like this is the chain rule. Chapter 4 uses it on whole networks. See it in part 1, screen 5 →
Multiplier les pentes le long d'une chaîne d'étapes comme ça, c'est la règle de dérivation en chaîne. Le chapitre 4 l'utilise sur des réseaux entiers. Le voir dans la partie 1, écran 5 →
3. Gradient descent3. La descente de gradient
Move the weight against the slope, by a step the size of the learning rate η:
On déplace le poids contre la pente, d'un pas de la taille du taux d'apprentissage η :
w ← w − η × dL/dw
w ← w − η × dL/dw
# lr: the learning rate (step size)
w, lr = 0.5, 0.5
for step in range(6):
p = w * x
slope = 2 * (p - t) * x
L = round(loss(w), 4) # L: loss
print(step, round(w, 4), L)
w = w - lr * slope # one step
the learning rate η, the step sizele taux d'apprentissage η, la taille du pas
step
the step number, 0 to 5le numéro du pas, de 0 à 5
L
the loss at that stepla perte à ce pas
Each line is one step: the step number, the weight, the loss. The weight walks to 1.25, the bottom of the valley, and the loss to 0. See it in part 1, screen 7 →
Chaque ligne est un pas : le numéro, le poids, la perte. Le poids marche vers 1,25, le fond de la vallée, et la perte vers 0. Le voir dans la partie 1, écran 7 →
4. Why the step size matters4. Pourquoi la taille du pas compte
# where w ends after 8 steps of size lr
def run(lr, steps=8):
w = 0.5
for _ in range(steps):
slope = 2 * (w * x - t) * x
w = w - lr * slope
return round(w, 3)
for lr in [0.1, 0.5, 1.6]:
print(lr, run(lr))
0.1 0.999
0.5 1.25
1.6 0.159
What each name holdsCe que contient chaque nom
run(lr, steps)
starts at w = 0.5, takes 8 steps of size lr, gives back where w endspart de w = 0,5, fait 8 pas de taille lr, et rend où w arrive
Here the slope is 1.28 × (w − 1.25), so one step multiplies the distance to the bottom by (1 − 1.28 η):
Ici la pente vaut 1,28 × (w − 1,25), donc un pas multiplie la distance au fond par (1 − 1,28 η) :
η = 0.1: × 0.872it creepsη = 0.5: × 0.36it arrives fastη = 1.6: × (−1.048)it jumps across and moves away
η = 0,1 : × 0,872elle avance à peineη = 0,5 : × 0,36elle arrive viteη = 1,6 : × (−1,048)elle saute de l'autre côté et s'éloigne
5. Many weights: the gradient5. Plusieurs poids : le gradient
With several weights, nudge one at a time and keep the others still. Each ratio is a partial derivative, written with a curly ∂. Put together, they form the gradient, written ∇L, and every weight takes its own step:
Avec plusieurs poids, on en pousse un à la fois en gardant les autres fixes. Chaque rapport est une dérivée partielle, notée avec un ∂ arrondi. Ensemble, elles forment le gradient, noté ∇L, et chaque poids fait son propre pas :
∇L = ( ∂L/∂w₁ , ∂L/∂w₂ )wᵢ ← wᵢ − η × ∂L/∂wᵢ
∇L = ( ∂L/∂w₁ ; ∂L/∂w₂ )wᵢ ← wᵢ − η × ∂L/∂wᵢ
In part 1 the two examples were x = (0.8, 0.2) with target 1 and x = (0.1, 0.9) with target 0, and the loss was the sum of their two squared gaps. See it in part 1, screen 9 →
Dans la partie 1, les deux exemples étaient x = (0,8 ; 0,2) de cible 1 et x = (0,1 ; 0,9) de cible 0, et la perte était la somme de leurs deux écarts au carré. Le voir dans la partie 1, écran 9 →
6. Softmax and cross-entropy6. Softmax et entropie croisée
Ten scores s₀ … s₉ become ten chances that add up to 1:
Dix scores s₀ … s₉ deviennent dix chances dont la somme fait 1 :
e ≈ 2.718. log is the natural logarithm, the opposite of e to a power: log(1) = 0 and log(0.1) ≈ −2.30. Before learning, every score is 0, so every chance is 1 ÷ 10: See it in part 1, screen 10 →
e ≈ 2,718. log est le logarithme naturel, l'inverse de e à une puissance : log(1) = 0 et log(0,1) ≈ −2,30. Avant d'apprendre, chaque score vaut 0, donc chaque chance vaut 1 ÷ 10 : Le voir dans la partie 1, écran 10 →
import numpy as np
from tensorflow.keras import datasets
mnist = datasets.mnist.load_data()
train_imgs, train_labels = mnist[0]
test_imgs, test_labels = mnist[1]
# the same 2,000 + 500 as chapter 2
X = train_imgs[:2000].reshape(-1, 784)
X = X / 255
Y = train_labels[:2000]
Xt = test_imgs[:500].reshape(-1, 784)
Xt = Xt / 255
Yt = test_labels[:500]
def softmax(s): # s: ten scores
e = np.exp(s - s.max())
return e / e.sum() # ten chances
W = np.zeros((10, 784))
b = np.zeros(10)
# p: ten chances for picture 1
p = softmax(W @ X[0] + b)
print(p.round(2))
# loss = -log(chance of right digit)
print(round(-np.log(p[Y[0]]), 4))
[0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]
2.3026
What each name holdsCe que contient chaque nom
X, Y, Xt, Yt
the same 2,000 learning and 500 test pictures as chapter 2 (see chapter 2, part 2, section 1)les mêmes 2 000 images d'apprentissage et 500 de test qu'au chapitre 2 (voir chapitre 2, partie 2, section 1)
s
ten scoresdix scores
e
each score passed through e to the power, made positivechaque score passé par e puissance, rendu positif
softmax(s)
the ten chances, adding up to 1les dix chances, dont la somme fait 1
W, b
weights and biases, all starting at 0les poids et les biais, tous à 0 au départ
p
the ten chances for picture 0les dix chances de l'image 0
s - s.max() subtracts the largest score first. It changes nothing in the result but stops e from overflowing on big scores. The loss 2.3026 is − log(0.1): a machine that knows nothing. See it in part 1, screen 11 →
s - s.max() retire d'abord le plus grand score. Ça ne change rien au résultat mais évite que e déborde sur de grands scores. La perte 2,3026 vaut − log(0,1) : une machine qui ne sait rien. Le voir dans la partie 1, écran 11 →
7. The slope of every weight7. La pente de chaque poids
With softmax and cross-entropy, the slope for the weight joining square j to digit k is short. Write y for the right answer as ten numbers: 1 for the right digit, 0 elsewhere:
Avec softmax et l'entropie croisée, la pente du poids qui relie la case j au chiffre k est courte. On écrit y la bonne réponse en dix nombres : 1 pour le bon chiffre, 0 ailleurs :
∂L/∂wₖⱼ = (pₖ − yₖ) × xⱼ∂L/∂bₖ = pₖ − yₖ
All 7,850 slopes at once: the ten numbers (p − y) times the 784 numbers x, every pair multiplied. That table is the outer product, np.outer(p - y, x), a 10 × 784 matrix the shape of W. Chapter 2's rule added x to one row and took it from another; this rule moves every row, by how wrong that row was. See it in part 1, screen 12 →
Les 7 850 pentes d'un coup : les dix nombres (p − y) fois les 784 nombres x, chaque paire multipliée. Ce tableau est le produit extérieur, np.outer(p - y, x), une matrice 10 × 784 de la forme de W. La règle du chapitre 2 ajoutait x à une ligne et le retirait d'une autre ; celle-ci bouge chaque ligne, selon son erreur. Le voir dans la partie 1, écran 12 →
8. Training on the 2,000 digits8. Entraîner sur les 2 000 chiffres
The same loop as chapter 2, with the slope rule in place of the perceptron rule. This needs X, Y, Xt and Yt from section 6.
La même boucle qu'au chapitre 2, avec la règle des pentes à la place du perceptron. Il faut X, Y, Xt et Yt de la section 6.
# passes: times through the 2,000
# lr: the learning rate
def train(passes, lr=0.01):
W = np.zeros((10, 784))
b = np.zeros(10)
for _ in range(passes):
for i in range(2000):
x, y = X[i], Y[i]
p = softmax(W @ x + b)
p[y] -= 1 # now p minus y
# all 7,850 slopes, one step
W -= lr * np.outer(p, x)
b -= lr * p
return W, b
def accuracy(W, b, X, Y):
s = X @ W.T + b # all scores
guesses = s.argmax(axis=1)
return (guesses == Y).mean()
for n in [1, 3]: # n: passes
W, b = train(n)
print(n, accuracy(W, b, X, Y),
accuracy(W, b, Xt, Yt))
1 0.896 0.848
3 0.9285 0.888
What each name holdsCe que contient chaque nom
passes
how many times it goes through the 2,000 picturescombien de fois elle passe sur les 2 000 images
lr
the learning rate, 0.01le taux d'apprentissage, 0,01
x, y
one picture and its labelune image et son étiquette
p (after p[y] -= 1)
the ten chances minus the right answer: pₖ − yₖles dix chances moins la bonne réponse : pₖ − yₖ
np.outer(p, x)
the 10 × 784 table of slopes, one per weightle tableau 10 × 784 des pentes, une par poids
n
passes in the last loop: 1, then 3les passages dans la dernière boucle : 1, puis 3
Each line: passes over the data, accuracy on its own digits, accuracy on the 500 test digits. On the test, the perceptron of chapter 2 reached 0.8. Slopes reach 0.848 in one pass and 0.888 in three. See it in part 1, screen 13 →
Chaque ligne : nombre de passages, précision sur ses propres chiffres, précision sur les 500 du test. Sur le test, le perceptron du chapitre 2 atteignait 0,8. Les pentes atteignent 0,848 en un passage et 0,888 en trois. Le voir dans la partie 1, écran 13 →
SummaryRésumé
The loss turns "how wrong" into one number: (p − t)² for one score, − log(pright) for a choice between digits.
The slope (derivative) says how the loss changes when one weight moves. You can measure it by nudging.
Gradient descent: every weight steps against its slope, w ← w − η × slope.
The learning rate η sets the step: too small is slow, too big overshoots.
Softmax turns scores into chances; the slope of each weight is (pₖ − yₖ) × xⱼ.
On the same data, slopes beat the right-or-wrong rule: 85 % and 89 % against 80 %.
La perte transforme « à quel point c'est faux » en un nombre : (p − t)² pour un score, − log(pjuste) pour un choix entre chiffres.
La pente (dérivée) dit comment la perte change quand un poids bouge. On peut la mesurer en poussant.
Descente de gradient : chaque poids fait un pas contre sa pente, w ← w − η × pente.
Le taux d'apprentissage η règle le pas : trop petit, c'est lent ; trop grand, ça dépasse.
Softmax transforme les scores en chances ; la pente de chaque poids est (pₖ − yₖ) × xⱼ.
Sur les mêmes données, les pentes battent la règle juste-ou-faux : 85 % et 89 % contre 80 %.