Functions you meet in ML: lines, powers, exp and log
Before this lesson: lesson 02 (functions, , , argmax) and lesson 03 (arrays and plots). You need school algebra: solve . Time: about 55 minutes, plus the notebook.
Why this matters #
Every model in this site is built from these functions. Linear regression predicts (with many features, ). The squared error is a power. Logistic regression, softmax classifiers and every language model use to turn scores into probabilities (lesson 05). Training minimizes the negative log-likelihood (the cross-entropy loss), a sum of logs. Learning rates are searched on a log scale (), loss curves are plotted on log axes, and neural scaling laws (loss against model size) are straight lines on log-log plots.
1. Predict first #
2. The picture #
A graph is a set of points. The graph of a function is the set of all points . The input is on the horizontal axis, the output on the vertical axis. To read , go to and up (or down) to the curve.
Lines. The graph of is a straight line. The number is the slope: when grows by 1, changes by . For two points on the line, the slope is "rise over run": . The number is the intercept: the height where the line crosses the vertical axis, because .
Drag the two blue points. The orange line goes through both. The aqua triangle shows the run and the rise ; their ratio is the slope . The yellow dot is the intercept . Make the slope negative, then zero. Then put both points at the same : why does the formula fail?
Moving and scaling a graph. Many ML functions are a basic function that is moved or stretched. From we build . Each number does one thing: moves the graph right, moves it up, stretches it up and down, squeezes it left and right. The figure lets you test each one.
Move one slider at a time, and predict before you look. The dashed blue curve is the base function , the orange curve is . The aqua arrow shows where one marked point of goes. Notice that moves the graph to the right, not to the left.
Exp and log are mirror images. The exponential (for a base , ) takes every real to a positive . Its inverse, the logarithm , goes back: is the power you need, so . If is on the graph of , then is on the graph of . Swapping the two coordinates is a mirror image across the line .
Drag the orange point along . Its mirror point on the violet curve follows; the aqua segment joins them across . Every exponential passes through , so every logarithm passes through . Try base , and then move to 1: why is there no ?
What is the slope of the line through the points and ?
The slope is rise over run: . The answer is the rise alone, and is run over rise (the ratio upside down).
The graph of has its lowest point at . Where is the lowest point of ?
. Here moves the graph 2 to the right and moves it 1 up. Check: , and , so no point is lower. The minus sign inside makes many people move left by mistake.
3. Definitions and main results #
3.1 Lines and affine functions #
A function is called affine (school books say "linear function"; in linear algebra, "linear" also needs , so only is linear; see Linear Algebra lesson 01).
Line through two points. Let and be two points with .
- The slope is (rise over run). Use the same order of points above and below.
- The line goes through , so . Solve for : .
If , the run is 0 and the slope is undefined: the vertical line is not the graph of a function, because one input would have many outputs.
- : the line goes up from left to right; : it goes down; : it is flat.
- In ML, is a model with one feature : is the weight and is the bias. With features, .
3.2 Moving and scaling graphs #
For :
| Change | Effect on the graph of | Example with |
|---|---|---|
| , | moves right by | : lowest point at |
| , | moves up by | |
| , | stretches up and down by the factor | is narrower |
| , | squeezes left and right by the factor | |
| mirror image across the -axis | opens downward | |
| mirror image across the -axis | is mirrored |
Why moves right. The new graph at shows the old value at . So the old point at appears where , that is, at : to the right.
3.3 Powers #
For a number and a positive integer , ( factors). The rules come from counting factors:
| Rule | Reason |
|---|---|
| factors, then more factors | |
| groups of factors | |
| reorder the factors | |
| () | needed so that |
| () | needed so that |
| () | needed so that |
The last three lines are definitions: they are the only choices that keep the first rule true. For a non-integer power we assume (for example, is not a real number).
Non-rules. (the correct expansion is ), and (example: , but ).
A polynomial is a sum of powers with coefficients, ; its degree is the largest power with . The graph of is a U-shaped curve (a parabola) with its lowest point at 0. This is the shape of the squared error : an error of 2 costs 4, an error of 10 costs 100, so large errors count much more. The graph of is increasing and changes sign at 0.
3.4 The exponential function #
For a base , the exponential function is defined for every real (the rules of 3.3 fix its values at fractions, and the graph fills in the rest without gaps).
- for every , and .
- : exponential growth (the function increases). : exponential decay (it decreases). : the constant 1.
- The rules of 3.3 hold for all real powers: , , .
The number . The most used base is Euler's number . One way to define it: is the limit of as grows (interest of per year, paid in small parts). We write . Why this base? The graph of has slope exactly at every point; at the slope is 1. This makes derivatives simple (lesson 07 shows it).
Exponential growth is fast. Each step of 1 in multiplies by . So
, , and is larger than the
largest float64 number (about ): np.exp(710) returns inf.
Lesson 05 shows how ML code avoids this.
Doubling time. If with rate , then doubles every time units. Reason: , and exactly when (the log is defined next).
3.5 The logarithm #
Definition. Let , . For , the logarithm to base , , is the number with . In words: "which power of gives ?"
- because . . because .
- Inverse pair: for every real , and for every .
- (because ) and .
- Domain: exists only for , because is never 0 or negative. For and , ; as goes down to 0, goes to .
- For , is strictly increasing: implies . (If , apply the increasing function to both sides: .)
Notation. In this site, as in ML papers and in NumPy, without a base is the natural
logarithm, base (np.log). School books write . We write (np.log2) and
(np.log10) when we need another base.
The logarithm grows slowly: of a million is only 6. For a whole number , is its number of digits. For , is the number of times you halve to reach 1.
3.6 The log rules, and why they are true #
Let and write , , so and . Each log rule is a power rule read backwards:
- Product: , so .
- Quotient: , so .
- Power: , so for every real .
- Change of base: start from and take the natural log of both sides. Rule 3 gives , so . Every log is the natural log times a constant. Example: .
- Every exponential is a power of : , because .
Non-rules (common errors):
- . Counterexample : , but .
- , and (in fact ).
- ; only .
Which expression equals for ?
The product rule gives , and the power rule gives . The option confuses with ; the first option turns the sum into a product.
3.7 Why ML loves logs #
(a) The log does not move the maximum. Let for all parameters (for example a likelihood, the probability of the data under the model with parameters ).
Claim. .
Proof. Because is strictly increasing, for any two parameters : holds exactly when . So " is at least as good as every " means the same thing for and for .
The maximum value changes ( instead of ), but the location does not. The same proof works for any strictly increasing function, and for argmin.
(b) A product becomes a sum. For independent data points, the likelihood is a product , where is the probability of point . By the product rule,
Sums are easier to differentiate and to average, and they are safe on a computer. The product of 1000 numbers equal to 0.01 is . The smallest positive float64 number is about , so the product underflows: the computer stores 0.0. The log-likelihood is , a normal number. Training minimizes the negative log-likelihood .
(c) Log scales show many orders of magnitude. A learning rate of and one of differ by a factor . On a log axis they are 4 equal steps apart, and every factor 10 in between gets the same space.
Why do we maximize the log-likelihood instead of the likelihood ?
The argmax does not change under a strictly increasing function, so we lose nothing. The sum of logs avoids the product of many small numbers, which rounds to 0. The value is not larger: for the log-likelihood is negative. A likelihood is never negative.
3.8 Log-scale plots #
On a log axis, the distance between two values is the difference of their logs. Ticks 1, 10, 100, 1000 are equally spaced: equal distances mean equal ratios, not equal differences.
- Semilog plot (log , linear ). If , then . This is a line in the variables , with slope and intercept . So exponential growth or decay is a straight line on a semilog plot.
- Log-log plot (log and log ). If (a power law), then : a straight line in with slope , the exponent. The slope does not depend on the base of the log, as long as both axes use the same base.
Switch the axes. The blue dots are , the orange dots are . The dashed lines are least-squares lines in the current axes; means a perfect line. Notice which data set becomes straight on semilog axes (slope ) and which on log-log axes (slope 3).
A training loss, plotted on a semilog plot (log , linear step count), falls on a straight line with negative slope. What does this mean?
A straight line in means , so with when the slope is negative. Equal steps in multiply by . A power law would be straight on a log-log plot. An exponential decay never reaches 0.
3.9 Exponentials beat polynomials, but maybe late #
Fact. For every base and every power , grows without limit as grows. So is eventually larger than , however large is.
A plot on a small range can hide this. For , the two curves and cross twice: on , on , and for every . At , while ; at , while .
Start at with a linear -axis: (orange) seems to win and (violet) looks flat. Move past 60, then switch to a log -axis. The yellow lines mark where crosses (blue) and .
Why exponentials win: a short argument
Take logs: . The ratio goes to 0 as grows. One way to see it: for all (the difference is smallest at , where it is ; finding this minimum uses a derivative, lesson 07). So for , which goes to 0. Then the bracket tends to , the product with grows without limit, and so does .
In computer science this is the gap between polynomial and exponential cost. A grid search over hyperparameters with 10 values each needs runs: this grows exponentially in .
Answers to section 1. (1) At , is much larger than
. At , beats
. The exponential wins for every . (2) It prints 0.0: the true value
underflows. The sum of the logs, , is fine. (3) No. Counterexample
: . The true rule is about products: .
4. Worked example #
(a) A line from two points. Find the line through and .
- Slope: .
- Intercept: .
- The line is . Check the second point: ✓.
- Use it: at the model predicts .
(b) Solve for a power.
- . Since , .
- . Divide by 3: . Take : . Check: ✓.
(c) Likelihood and log-likelihood of coin flips. A coin shows heads with probability . We see H, H, T, H (independent flips). The likelihood is the product of the four probabilities:
Both columns are largest at (in the notebook you check a fine grid of ). The maximizer is the fraction of heads. (Lesson 07 finds it exactly by setting the slope of to 0: gives .)
(d) Read an exponential from a semilog plot. Data lie on a straight line on a semilog plot and pass through and . So .
- At : , so .
- At : , so and .
- The data follow : doubles with each step of 1 in . On a base-10 semilog plot the slope is , as in the figure of section 3.8.
5. In code #
NumPy checks the worked example. The notebook for this lesson has these cells and the exercises.
import numpy as np
from scipy.optimize import brentq
# (a) line through two points
x1, y1, x2, y2 = 1.0, 2.0, 3.0, 8.0
w = (y2 - y1) / (x2 - x1)
b = y1 - w * x1
print(w, b, w * 2 + b) # 3.0 -1.0 5.0
# (b) solve 3 * 2**x = 100
x = np.log(100 / 3) / np.log(2)
print(round(x, 3), 3 * 2**x) # 5.059 100.00000000000006
# log rules: True, and the non-rule: False
a, c = 7.0, 0.3
print(np.isclose(np.log(a * c), np.log(a) + np.log(c))) # True
print(np.isclose(np.log(a + c), np.log(a) + np.log(c))) # False
# (c) the product underflows, the sum of logs does not
p = np.full(1000, 0.01)
print(np.prod(p), np.sum(np.log(p))) # 0.0 -4605.17018598809
# 2**x = x**10: compare logs to avoid huge numbers, then find the two crossings
g = lambda x: x * np.log(2) - 10 * np.log(x)
print(brentq(g, 1.01, 2), brentq(g, 10, 100)) # 1.0775501500027171 58.77010593792138
# (d) slope of exponential data on a semilog plot
xs = np.arange(0, 6.0)
ys = 3 * 2**xs
slope, intercept = np.polyfit(xs, np.log10(ys), 1)
print(round(slope, 4), round(10**intercept, 4)) # 0.301 3.0
The function np.log is the natural log. np.log(0) returns -inf and np.log(-1) returns nan,
both with a warning: the log of a number is not defined.
6. Where it shows up #
- Linear models. Linear regression ; one neuron computes an affine function before its activation. The slope says how much the prediction changes per unit of a feature.
- Losses. The squared error (a power) in regression; the negative
log-likelihood , also called the cross-entropy loss, in classification and in
language models (link: the
/information-theory/track explains cross-entropy). - The exponential inside models. Sigmoid and softmax use (lesson 05); the Gaussian density uses (lesson 08); exponential learning-rate decay ; the discount factor in reinforcement learning; exponential moving averages in the Adam optimizer.
- Log scales. Learning-rate and regularization searches on a log grid; loss curves on log axes; scaling laws: the test loss of language models falls as a power law of model size, data size and compute, so it is a straight line on a log-log plot (Kaplan et al., 2020).
- Log transforms of data. Skewed positive features (prices, incomes, counts) are often replaced by or before training, so that factors become differences.
- ML for science. Radioactive decay and drug concentration (exponential decay); the Arrhenius law of reaction rates ; the pH and decibel scales are logarithms; power laws in turbulence and in network degree distributions are read on log-log plots.
7. Common mistakes #
- . False. The log turns products into sums, not sums into sums.
- Taking the log of 0 or of a negative number. The log is defined only for inputs . In code,
a probability that rounds to 0 gives
-inf; add a check, or compute the log directly in a stable way (lesson 05). - Mixing up bases.
np.logis the natural log ().np.log10andnp.log2are other bases;math.log(x, b)takes a base. Results in different bases differ by a constant factor. - Moving the graph the wrong way. moves right, moves left.
- Slope with mixed order. In , use the same point first above and below; has the wrong sign.
- . False; the cross term is missing.
- Reading a log axis as linear. On a log axis, the middle between 1 and 100 is 10, not 50.
- Python precedence.
-2**2is-4in Python (the power comes first), and(-2)**2is4. - Judging growth from a small range. On , looks faster than ; on , it is not.
8. Check yourself #
- Find the line through and . Where does it cross the -axis?
Answer
. Then . The line is ; it crosses the -axis at . Check: ✓. - Compute without a calculator: , , , .
Answer
(since ), (since ), , and : exp and log undo each other. - Write as a sum and difference of , , ().
Answer
: product rule, quotient rule, then the power rule for . - A quantity grows as . What is its doubling time? How long until it is 10 times larger?
Answer
Doubling: , so . Factor 10: . The starting value 5 does not matter. - Data on a log-log plot lie on a line through and . Give the formula for .
Answer
Slope , intercept , so . So . Check: gives , and ✓. - Your code computes
np.prod(probs)for 5000 probabilities around 0.3 and gets0.0. Is the model wrong? What should you compute instead?Answer
Not necessarily: underflows to 0 in float64. Compute the log-likelihood `np.sum(np.log(probs))` instead; it is about and has the same maximizer.
How do you get the slope of the line through and ?
(rise over run), for . Then .
Compute the slope of the line through and .
; the line is .
In which direction does move the graph of , and why?
2 to the right: the new graph shows at the old value at , so the old point appears at .
Why is and (for )?
These are the only choices that keep true: and .
Define , and give its domain.
The number with (, ). It is defined only for .
State the product, power and change-of-base rules of the logarithm.
; ; .
Why does maximizing give the same as maximizing ?
is strictly increasing, so it keeps the order of the values: exactly when . The argmax stays; only the max value changes.
What does Python give for the product of 1000 numbers equal to 0.01, and what is the fix?
0.0, because underflows in float64. Use the sum of logs: .What does a straight line on a semilog plot (log , linear ) mean? And on a log-log plot?
Semilog: exponential, , slope . Log-log: power law, , slope .
What is the doubling time of ?
, independent of .
9. Interview angle #
- "Why do we train with the log-likelihood?" — The log is strictly increasing, so the maximizer is the same. The product of many probabilities becomes a sum, which does not underflow, is easy to differentiate, and splits into one term per example (so mini-batches work).
- "What does a straight line on a log-log plot tell you?" — A power law with exponent equal to the slope. Example: neural scaling laws for loss against parameters, data and compute.
- "When would you log-transform a feature or a target?" — When it is positive and skewed, or when effects are multiplicative: after the log, a factor becomes a difference, and a model with additive effects fits better. Use when zeros occur.
- "Why are learning rates searched on a log grid?" — Good values differ by orders of magnitude; equal steps in give each factor of 10 the same number of trials.
10. Practice #
The notebook for this lesson runs in Colab or in your browser. It has five exercises, each with a check cell and a folded solution:
- Write
line_through(p, q)that returns and ; check it on a third point of the line. - Check the log rules on random positive numbers, and find a counterexample to .
- See the product of 1000 probabilities underflow, and compute the log-likelihood as a sum of logs instead.
- Find both crossings of and with bisection, written by you.
- Recover the growth rate of noisy exponential data with
np.polyfiton .
11. Watch and read #
- Jay Abramson et al., Algebra and Trigonometry 2e (OpenStax, free): chapter 3 (functions; §3.5 moves and stretches graphs), chapter 4 (linear functions) and chapter 6 (exponential and logarithmic functions), with many exercises and answers.
- Deisenroth, Faisal and Ong, Mathematics for Machine Learning (free PDF): §8.3 uses the negative log-likelihood for parameter estimation.
- Kaplan et al. (2020), Scaling Laws for Neural Language Models: figure 1 shows power laws as straight lines on log-log plots.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.