Here is a puzzle. A model gives each of 1000 training examples a probability of 0.1. Multiply all 1000 probabilities together in Python and you get exactly 0.0. Python prints zero, although the true answer is a tiny positive number. Add the logarithms of the same 1000 probabilities and you get a perfectly fine number, about . Logarithms are the cure, and by the end of this lesson you will know why it works.
You met exponential functions in P1.A1 ( multiplies by 2 for every +1 in ). Here we go deeper: the rules for exponents, the logarithm that undoes them, and why machine learning uses them everywhere.
Exponents: repeated multiplication
An exponent (or power) says how many times to multiply a number by itself. In the number is the base and is the exponent:
Read as “2 to the power 3”. Now we build the rules from small examples. Each rule is checked with numbers, so you never have to memorize it blindly.
Rule 1: multiplying powers of the same base adds the exponents
Five 2s multiplied together: three from the first power and two from the second. In general .
Rule 2: dividing powers of the same base subtracts the exponents
Two 2s cancel. In general .
Rule 3: a power of a power multiplies the exponents
In general .
Rule 4: the exponent zero
Look at the pattern as the exponent goes down by one: , , . Each step divides by 2. So the next one has to be . This also follows from Rule 2: , and anything divided by itself is 1. So for every .
Rule 5: negative exponents mean “one over”
Keep going down the same pattern: , then , , . So
A negative exponent does not make the number negative: is positive. It means “divide” instead of “multiply”.
Rule 6: fractional exponents are roots
What should be? By Rule 1, , so is a number that times itself gives 9: the (positive) square root, . In the same way
Checks: (because ), and . For fractional exponents we use a positive base, so the answer is a real number.
Rule 7: powers of a product
. Check: .
| Rule | Formula | Small check |
|---|---|---|
| Product | ||
| Quotient | ||
| Power of a power | ||
| Zero | ||
| Negative | ||
| Fractional | ||
| Product base |
Exponential growth and decay
In P1.A1 you saw that multiplies by for every +1 in . That one idea covers many real processes:
- Doubling. 100 bacteria that double every hour: . After 3 hours there are 800, after 10 hours there are 102,400.
- Halving (decay). A quantity that halves each step: . After 10 steps only of it is left.
- Percentage growth. Growing 5% a year multiplies by each year: . After 100 years that is about 131,501. (Money doubles in about years at 5%; see the log rules below.)
A line adds the same amount each step; an exponential multiplies by the same factor each step. That is why the exponential eventually beats any line.
The number e
One base is special: the number
It is an irrational number (its digits never end or repeat), like . Why do we love it? The function is the one exponential whose growth rate at every point equals its own value: when is 5, it is growing at 5 per unit of ; when it is 20, it is growing at 20 per unit. (Slopes of curves are the subject of P1.C1; for now, remember that this makes the cleanest exponential to do calculus with.) No other base has this property exactly. A different base has growth rate times its value, and .
You will see constantly in ML: the sigmoid (P1.A5), softmax (P3.A8), and Gaussian bell curves (P1.D3). In NumPy it is np.exp(x). Some values: , , , .
Go deeper Where e comes from: compound interest
Put 1 unit of money in a bank paying 100% interest a year. If the interest is paid once at the end of the year, you have . Paid twice (50% each half year): . Paid monthly: . Daily: . A million times a year: about . As the payments become more and more frequent, the result settles toward a limit. That limit is :
So is what you get from growth that compounds continuously. This is why continuous growth and decay, such as radioactive decay and the Gaussian, use .
Logarithms: the undo button for powers
Powers answer: “2 to the power 3 is what?” (8). A logarithm asks the question the other way round:
is the power you must raise to in order to get .
The two statements and say the same fact in two ways. A logarithm is the inverse function of the exponential (the “undo” idea from P1.A1): the exponential turns an exponent into a number, the logarithm turns the number back into the exponent.
The three bases you will meet
- (common log): counts digits and powers of ten. .
- (binary log): counts doublings, and bits in information theory (P1.E1). .
- (natural log) : the inverse of . .
Watch out for the notation. Many ML books and all of NumPy write log for the natural log. In NumPy, np.log is ; np.log10 and np.log2 are the others. In this course we write the base when it matters and write for the natural log. When a formula in ML has “log” with no base, the base only changes the answer by a constant factor (see change of base below), so the ideas do not depend on it.
Easy values to remember
For any base : (because ) and (because ).
Domain and shape
- The input must be positive. A power with is always positive, so there is no power that gives 0 or a negative number. So is defined only for . In code,
np.log(0)gives-infandmath.log(-1)raises an error. - The output can be any real number. Range: all real numbers.
- For any base , it is increasing, but slowly: climbs only from 0 to 6 as goes from 1 to a million. Each time is multiplied by 10, goes up by only 1. (The base must be positive and not 1; this course almost always uses bases 2, 10 and .)
- Below 1 it is negative. when (for ).
- Near 0 it plunges. As gets closer to 0 from above (), . For example , , and so on without end. It never reaches a value for .
The log rules
Logarithms turn multiplication into addition. Why? Because exponents add when you multiply powers (Rule 1). Take of : and . The same thing, in general, for any base:
| Rule | Formula | Small check |
|---|---|---|
| Product becomes sum | ||
| Quotient becomes difference | ||
| Reciprocal | ||
| Power becomes multiplication | ||
| Change of base |
Why each rule is true. Write and , so and . Then by Rule 1, so . Rule 2 gives the quotient in the same way, and Rule 3 gives , so . The reciprocal rule is the quotient rule with (because ).
Change of base lets you compute any log with just : . It also shows that logs of different bases differ only by a constant factor: .
A worked use. How long does money take to double at 5% a year? We need . Take logs of both sides and use the power rule: , so years. Taking the log brought the unknown down from the exponent.
Log scales: reading numbers that span many sizes
Some quantities range from tiny to huge: a training loss that falls from 5 to 0.001, a population that grows from 100 to 100 million, a learning rate between and . On an ordinary linear axis the biggest values flatten everything else against the bottom.
A log axis fixes this by plotting instead of . Equal steps up the axis now mean equal multiplications (here, ) instead of equal additions. The tick labels are written as powers of 10: , , . (We plot of each value and label the tick at height as .)
- A quantity that grows or shrinks by the same factor each step (an exponential) becomes a straight line. The slope of that line is of the factor: for doubling, per step.
- Each order of magnitude (a factor of 10) gets the same height, so you can see tiny and huge values in one picture.
In ML you will meet log scales again and again:
- Learning rates are searched on a log scale: try , not . A factor of 10 matters more than a difference of 0.001 (P4.14).
- Loss curves that fall over several orders of magnitude are drawn with a log y-axis.
- A power law becomes a straight line when both axes are log, because . Many scaling-law plots are drawn this way (P10.B3).
Why machine learning loves logs
1. Products become sums
Probabilities of independent things multiply. If a model gives probability to each of independent training examples, the probability of the whole data set is the product (P1.D10 explains when and why). Taking the log:
A product of numbers has become a sum of numbers. Sums are easier for everything: they are numerically safe (next), their gradients are simple (a sum of small pieces, one per example), and they average nicely.
2. Underflow: why the product breaks
A computer stores a normal Python number as a 64-bit float. The smallest positive number a float can hold is about , and anything much smaller is rounded to exactly 0.0. (Just above that, floats also lose precision, which is one more reason to avoid tiny numbers.) This is called underflow. Multiply 1000 probabilities of 0.1 and the true answer is , far below that limit. The sum of logs, , is an ordinary number.
3. Log is increasing, so the best stays the best
The log function is increasing: a bigger input always gives a bigger output. So if one number is larger than another, its log is also larger. This means that the input that maximizes the likelihood also maximizes the log-likelihood, so we may optimize whichever is easier. Example: a coin shows heads, heads, tails. If the chance of heads is , the likelihood of that data is :
| likelihood | |||
| log-likelihood |
Both rows rank the three candidates the same way, and both pick (the best of the three; in P1.D10 you will prove it is the best of all). Remember the effect on direction: a negative log makes a bigger probability a smaller loss, which is why we minimize the negative log-likelihood.
4. Log loss: surprise at the wrong answer
If a model gives probability to the correct answer, its log loss (the cross-entropy loss of P1.E3 for one example) is :
| given to the right answer | |||||
|---|---|---|---|---|---|
| loss |
A confident correct answer costs almost nothing; a confident wrong answer ( near 0) costs a lot, without limit. That is exactly the shape of the log near 0 that you saw above. The base only sets the units: gives “nats”, gives “bits” (P1.E1).
5. Logs squeeze huge ranges
Raw numbers in ML vary enormously: word counts from 1 to millions, learning rates over four powers of ten, probabilities near zero. compresses a factor of a million into a step of 6 (base 10), making these quantities easier to plot, compare and feed to models.
Go deeper The mirror problem: overflow, and a preview of log-sum-exp
Underflow has a twin, overflow: numbers too big. A 64-bit float tops out near , and is far above it (Python’s math.exp(1000) raises an error, and NumPy gives inf). Softmax divides by a sum of such terms, so a raw implementation breaks for large scores . The cure combines logs and a shift of the scores; it is called log-sum-exp and is the subject of P1.G2. The same two ideas, “work with logs” and “never let a number leave the safe range”, solve both problems.
Intuition
An exponent counts how many times you multiplied. A logarithm counts them back: “how many times did I multiply by 10 to get from 1 to this?” That is why of a number is roughly “the number of digits minus one”, and why logs turn multiplication into addition: multiplying numbers just adds up the counts of multiplications. Where the picture breaks: this “counting” is whole numbers only for neat cases like 8 or 1000. For other numbers the log is a fraction (), but the rules are exactly the same.
Math
For , and :
For , is increasing; for it is decreasing, but ML uses . Domain , range all real numbers. Exponent rules: , , , , .
Code
import numpy as np
np.log(np.e) # 1.0 (natural log)
np.log10(1000) # 3.0
np.log2(8) # 3.0
np.exp(0) # 1.0
np.log(20 * 3) # = np.log(20) + np.log(3)
np.sum(np.log(np.full(1000, 0.1))) # about -2302.585, fine
np.prod(np.full(1000, 0.1)) # 0.0, underflowThe cell below runs all of this and more.
Try it in Python
Run the cell, then change the numbers. Try different and , and see which of the “log rules” still hold when you break them.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge: find how many 0.5 probabilities you can multiply before the product becomes 0.0 (use a loop). Then check that the sum of their logs is still fine. (It happens at 1075 of them.)
Putting it together
Exponents multiply; logarithms undo them and so turn multiplying into adding. Exponentials give growth, decay and the clean base . Logs give slow growth, a domain of positive numbers, and a way to read numbers of every size. In ML, that means log-likelihoods instead of products, log loss for classification, and log axes for learning rates and loss curves.
Check your understanding
What is ?
A negative exponent means "one over": . It does not make the number negative.
What is ?
It is the power of 2 that gives 32. Since , the answer is 5.
Which statement is correct for all positive and ?
The log of a product is the sum of the logs. With and : , whereas .
A program multiplies 1000 probabilities that are each 0.1 and prints 0.0. What happened, and what is the standard fix?
The true product is , which is positive but far smaller than the smallest 64-bit float (about ), so it is rounded to 0.0. The sum of logs is about , an ordinary number.
A plot has a log10 y-axis, and a curve rises as a straight line. What does that tell you about the data?
On a log axis equal steps up mean equal multiplications. A straight line means each step multiplies by the same factor, which is exponential growth. A linear growth pattern would curve flat on a log axis.
Exercises
- Compute , and as single powers, and give their values.
Show answer
; ; . - Evaluate , , and .
Show answer
; ; (because ); . - A population of 50 doubles every day. Write its size after days and compute it for .
Show answer
. At : . - Find , and .
Show answer
(since ); (since ); (since ). - Why are and undefined?
Show answer
is positive for every , so no power of 10 gives or . The log is defined only for positive inputs. - Given and , use the log rules to estimate and and .
Show answer
. . . - Is equal to ? Say what it equals instead.
Show answer
No. , while . - Use change of base to compute from values.
Show answer
. - A model gives probability 0.25 to the correct class. What is its log loss ? What would it be at ?
Show answer
. At : . Making the model twice as confident in the right answer lowers the loss by . - You multiply 400 probabilities, each 0.1. Does a Python float hold the product? Use the widget or compute with logs.
Show answer
No. , below the float limit of about , so Python gives0.0. The sum of logs, , is fine. - On a log10 y-axis, a curve is a straight line that rises by 1 gridline (one power of 10) every 5 steps. By what factor does the quantity multiply every step?
Show answer
Over 5 steps it multiplies by 10, so each step multiplies by . - In the log-inverse widget, set the base to 2 and the exponent to 3. Read the two lines, then do it again with base 10 and exponent 0.9.
Show answer
Base 2: and . Base 10, exponent 0.9: (the widget shows 7.94; more precisely 7.943) and .