Milestone 1

System Modeling and Error Budget

Defining what mathematical problem we're actually trying to solve

🎯 Learning Objectives

  • Understand the real-world problem: can Population and GDP explain US Retail Sales?
  • Learn the difference between independent/dependent variables
  • Choose and justify a linear model with three unknown parameters
  • Understand residuals, SSE, and the least-squares objective
  • Recognize the trade-off between model complexity and generalization

Let's learn only Milestone 1 now. Don't worry about matrices, Gauss-Jordan, LU, interpolation, or forecasting yet.

The goal of Milestone 1 is to answer one question:

What mathematical problem are we actually trying to solve?

Start with the real-world problem

Your dataset contains:

  • Population
  • GDP per capita
  • Total retail sales

We want to investigate:

Can Population and GDP per Capita be used to explain/predict US Total Retail Sales?

In plain English:

Population + GDP → Retail Sales

We can call:

  • Population → input
  • GDP per Capita → input
  • Retail Sales → output

Independent vs dependent variables

These are basic statistical terms that you should understand.

Independent variables

These are the variables we use as inputs. Here:

X₁ = Population

X₂ = GDP

They're called independent variables, or more commonly in ML: features / predictors.

Dependent variable

This is what we're trying to explain or predict.

Y = Retail Sales

It's called the: dependent variable, response variable, target, or output.

So your problem is:

X₁, X₂ → Y

or:

Population, GDP → Sales

Why don't we simply say "Sales depends on Population and GDP"?

Because that's still just a hypothesis. We haven't yet specified how Sales depends on them. For example, maybe:

Sales = 2 + 3·GDP

Maybe:

Sales = GDP²

Maybe:

Sales = √(GDP)

Maybe:

Sales = Population × GDP

There are countless possibilities. So we need to choose a mathematical form. That is the first real modeling decision.

What is a model?

A model is a mathematical representation of a relationship we believe approximately exists in reality. For example, y = 2x + 5 is a mathematical model. If x = 10, then y = 25.

For your project, we're going to use:

Sales = β₀ + β₁·Population + β₂·GDP

Why choose a linear model?

This is probably the most important conceptual decision in Milestone 1. We could make the model much more complicated. But we're starting with the simplest model that can reasonably capture the relationship.

Start simple. Add complexity only when the data provides evidence that simplicity is insufficient.

What does "linear" actually mean?

This causes confusion. People sometimes think "Linear means the data must form a straight line." Not quite.

With one feature, y = β₀ + β₁x is a straight line. But with two features, y = β₀ + β₁x₁ + β₂x₂ is a plane in 3-dimensional space.

"Linear" refers to how the parameters enter the equation.

What are β₀, β₁ and β₂?

These are called parameters or coefficients. Our equation is:

Sales = β₀ + β₁·P + β₂·G

We don't know their values. Our dataset will help us estimate them.

β₀ — intercept

The intercept is primarily a mathematical parameter that allows the model to position itself appropriately. Don't interpret it as "The US would have β₀ trillion dollars of sales if its population and GDP were zero."

β₁ — Population coefficient

How much does predicted Sales change when Population changes, while GDP is held constant?

∂Sales/∂Population = β₁

β₁ = Population sensitivity

β₂ — GDP coefficient

How much predicted Sales changes when GDP changes, while Population is held constant.

∂Sales/∂GDP = β₂

β₂ = GDP sensitivity

Why do we need 10 years of data?

Because we don't know the coefficients. Our model contains three unknown parameters. One year gives us one equation. So we have 10 equations for 3 unknowns.

But there's a problem

Can the same three β values satisfy all ten observations exactly? Usually not. Because real-world data isn't perfectly generated by our simple equation. There are other factors: consumer behavior, interest rates, inflation, COVID-19, government policies, and factors we haven't included.

Prediction vs actual

Suppose our model produces ŷ₂₀₂₀ = 5.50T but the actual value is y₂₀₂₀ = 5.56T. The difference is called the residual:

eᵢ = yᵢ − ŷᵢ

A residual answers: "How wrong was the model for this observation?"

The error budget idea

Think: Actual = Prediction + Residual. The residual represents everything our model didn't capture.

A model isn't perfect, and we need to keep track of what it doesn't explain.

Why square the residuals?

Suppose we have residuals +0.2 and −0.2. Adding them gives 0 — it looks like there's no error, but clearly there is. So we square them: 0.04 + 0.04 = 0.08.

Sum of squared errors

SSE = Σ(yᵢ − ŷᵢ)²

Our goal will be: Find β₀, β₁, β₂ that minimize SSE.

This is why it's called least squares — we're trying to find the model with the least total squared error.

Why not minimize absolute error?

We could use Σ|yᵢ − ŷᵢ|, but least squares has very convenient mathematical properties. Most importantly: it is smooth and differentiable, which allows us to use calculus to derive the optimal coefficients.

The model doesn't have to hit every point

Our fitted relationship might run through the middle of the observations. That's okay. We're looking for the relationship that provides the best overall approximation.

Why not create a model that passes through every point?

With 10 points, you can construct a sufficiently flexible polynomial that passes through every point. Then residuals are 0 for all observations. But that can be terrible for prediction.

Because the model may be learning the individual quirks of these 10 observations rather than the underlying relationship. That's called overfitting.

Parameters as a complexity budget

Your linear model has 3 parameters. A degree-9 polynomial would have 10 parameters for 10 points. More flexibility isn't automatically better.

Start simple. Add complexity only when the data provides evidence that simplicity is insufficient.

📝 Summary

Milestone 1 transforms a vague question ("does GDP affect sales?") into a precise mathematical problem:

  • Model: Sales = β₀ + β₁·Population + β₂·GDP
  • Unknowns: β₀, β₁, β₂
  • Residual: eᵢ = yᵢ − ŷᵢ
  • Objective: Minimize SSE = Σ(yᵢ − ŷᵢ)²

The natural next question: How do we represent those 10 equations in a form a computer can solve? That's Milestone 2.

Milestone 2

Data Structuring: From Real Data to a Mathematical System

Converting 10 rows of CSV into matrices a computer can work with

🎯 Learning Objectives

  • Understand the design matrix X and how it encodes intercepts and features
  • Learn why X is (10×3) and why the system is overdetermined
  • Understand how the normal equations (XᵀXβ = Xᵀy) convert a rectangular problem into a square one
  • Learn basic matrix operations: transpose, multiplication, hstack

Milestone 1 answered: What are we trying to model?

We decided: Sales = β₀ + β₁·Population + β₂·GDP

Now Milestone 2 asks:

How do we convert our 10-row CSV into a mathematical structure that a computer can solve?

This is where matrices enter.

The system of equations

Your first three observations give:

β₀ + β₁(318301008) + β₂(54973) = 4.63
β₀ + β₁(320635163) + β₂(56573) = 4.72
β₀ + β₁(322941311) + β₂(57638) = 4.83

And seven more. That's a system of equations.

Why do we want a matrix?

Writing ten equations separately is inconvenient. Instead:

Xβ ≈ y

This is the central transformation of Milestone 2.

Why do we add a column of 1s?

Our equation is Sales = β₀ + β₁·P + β₂·G. We want to write it as y = Xβ. So we construct:

        X = 
[ 1   P₁   G₁ ]
[ 1   P₂   G₂ ]
[ ...  ...  ... ]
[ 1   P₁₀  G₁₀ ]

The first row [1, P₁, G₁] multiplied by [β₀, β₁, β₂]ᵀ gives β₀ + β₁P₁ + β₂G₁. The column of ones isn't a programming trick — it's how we mathematically encode the intercept.

Your actual design matrix

Your X has shape (10, 3):

  • 10 rows = one per observation/year
  • 3 columns: intercept, Population, GDP

What is β?

We collect all unknown coefficients into one vector:

β = [β₀, β₁, β₂]ᵀ

This is called the parameter vector. The entire regression problem is essentially: Find β.

What is y?

Your target vector contains the 10 Sales values: [4.63, 4.72, 4.83, 5.04, 5.25, 5.40, 5.56, 6.51, 7.04, 7.22]ᵀ. It has shape (10,).

Why do we write ≈ instead of =?

Because our model won't perfectly predict every observation. For example, ŷ₂₀₂₀ = 5.50 while y₂₀₂₀ = 5.56. Therefore Xβ ≠ y in general. Instead, is as close as possible to y under our least-squares criterion.

The fundamental problem

You have 10 equations and only 3 unknowns. This is an overdetermined system. We generally cannot satisfy all ten equations exactly.

Why can't we simply solve Xβ = y?

A lot of introductory linear algebra teaches Ax = b → x = A⁻¹b. But that assumes A is a square matrix. Your X is (10×3) — it isn't square. You cannot simply do X⁻¹.

How do we turn it into something solvable?

We start with Xβ ≈ y and the least-squares objective. The mathematical derivation eventually gives:

XᵀXβ = Xᵀy

These are called the normal equations.

Why does XᵀX become square?

Your X is (10×3). Transpose Xᵀ is (3×10). Multiply: (3×10)(10×3) = (3×3). That's square! And Xᵀy is (3×10)(10×1) = (3×1).

So the normal equations have the structure: (3×3)(3×1) = (3×1). Now we have a standard square linear system.

But why multiply by Xᵀ at all?

This isn't done merely because "we need a square matrix." It naturally emerges from minimizing the least-squares error. XᵀX isn't an arbitrary trick — it's the mathematical consequence of taking derivatives and setting them to zero.

You'll see the actual derivation in Milestone 6. For now, remember:

Least Squares → Normal Equations → XᵀXβ = Xᵀy

The complete transformation

CSV DATA (10 years)
        ↓
DESIGN MATRIX X  (10 × 3)
        ↓
XᵀX and Xᵀy
        ↓
A = XᵀX  (3 × 3)
b = Xᵀy  (3 × 1)
        ↓
Aβ = b   →  MILESTONE 3

What is a transpose?

Transpose swaps rows ↔ columns. If X is (10×3), then Xᵀ is (3×10).

What does @ mean?

In Python, X @ beta means matrix multiplication. So X.T @ X means XᵀX.

What does hstack do?

np.hstack([A, b]) places A and b side-by-side to create the augmented matrix [A|b]. For a 3×3 A and 3×1 b, the result is 3×4.

Scale problem

Your features operate on wildly different scales: Population ≈ 320,000,000 vs GDP ≈ 60,000. When you calculate XᵀX, Population gets squared to ~10¹⁷. This creates a numerical stability problem — your condition number eventually shows ~1.9×10²¹. That's the problem Milestone 6 will fix.

📝 Summary

Milestone 2 converts the regression problem into a form a computer can solve:

  • Build the design matrix X (10×3) with an intercept column
  • Collect target values in y (10×1)
  • Transform the overdetermined system Xβ ≈ y into the square normal equations XᵀXβ = Xᵀy
  • Now we have a 3×3 system: Aβ = b, ready for Milestone 3's solvers
Milestone 3

Correlation Solver: Actually Solving the System

Gauss-Jordan, LU decomposition, and finding the regression coefficients

🎯 Learning Objectives

  • Understand what it means to "solve" a linear system Aβ = b
  • Implement Gauss-Jordan elimination with partial pivoting
  • Understand LU decomposition and why it's efficient for repeated solves
  • Learn forward and backward substitution
  • Cross-check implementations against NumPy's reference solver

Milestone 2 stopped at Aβ = b. Now Milestone 3 asks:

We have transformed our regression problem into a system of equations. How do we actually find β₀, β₁, β₂?

This milestone is about numerical linear algebra.

Three versions of solving

  1. Gauss-Jordan — built from scratch
  2. LU decomposition — built from scratch
  3. NumPy's np.linalg.solve() — library reference

The first two teach you the mathematics. The third gives you a trusted benchmark.

Why use two different algorithms?

  • Gauss-Jordan: "Eliminate everything until the answer is directly visible."
  • LU decomposition: "Break the problem into two simpler triangular problems."

Both solve Aβ = b, but they organize the work differently.

Elementary row operations

We can perform three operations without changing the solution:

  1. Swap rows
  2. Multiply a row by a nonzero number
  3. Add a multiple of one row to another

The basic idea

Gauss-Jordan tries to transform the augmented matrix [A|b] into [I|β], where I is the identity matrix. Then the answer is simply the final column.

Partial pivoting

For each column, we find the largest absolute value and swap that row to the pivot position. This protects against numerical instability. If the pivot is essentially zero, the algorithm raises a singularity error.

Normalize and eliminate

Divide the pivot row by the pivot value (making it 1), then eliminate all other entries in that column (both above and below — that's what makes it Gauss-Jordan, not just Gaussian elimination).

Why is pivoting important?

Real computers use floating-point numbers. Dividing by a tiny number can amplify numerical errors. Choosing a larger pivot generally makes elimination more stable.

The idea

Instead of directly solving Aβ = b, decompose:

A = LU

where L is lower triangular and U is upper triangular.

Two simpler problems

  1. Solve Lz = Pb using forward substitution
  2. Solve Uβ = z using backward substitution

P is a permutation matrix representing row swaps from pivoting. We must apply the same swaps to b: pb = P @ b.

Why is LU useful for repeated solves?

If A doesn't change but b does, you decompose A=LU once and reuse it for every new b. That's much more efficient than re-doing the entire elimination.

Doolittle's method

Constructs L with ones on the diagonal. The elimination factors are stored in L while U gets the resulting upper-triangular matrix. Think of L as a record of the elimination operations.

Forward and backward substitution

Forward substitution solves Lz = Pb starting from the first equation downward. Backward substitution solves Uβ = z starting from the last equation upward.

The library reference

np.linalg.solve(A, b) acts as your reference implementation. If all three solvers agree:

β_GJ ≈ β_LU ≈ β_NumPy

That's strong evidence your implementation is correct.

Singularity and near-singularity

A singular matrix doesn't have a unique solution — the equations are redundant. A near-singular matrix has equations that are almost redundant, making tiny input errors cause large changes in the answer.

The condition number

Your raw XᵀX shows a condition number of ~1.9×10²¹. That's enormous. After standardization in Milestone 6, it drops to ~22. That's one of the most important results in your project.

📝 Summary

Milestone 3 solves Aβ = b using three methods:

  • Gauss-Jordan: Eliminates until the identity matrix appears — direct but less reusable
  • LU decomposition: Breaks into triangular systems — efficient for repeated solves
  • NumPy: Reference implementation for cross-checking

All three should produce the same β. We now have a fitted model.

Milestone 4

Market Threshold Analysis

Bisection vs. Newton's Method — finding the GDP that reaches a target Sales value

🎯 Learning Objectives

  • Turn a business question into a root-finding problem
  • Understand Bisection: bracket-based, slow but reliable
  • Understand Newton's method: slope-based, fast but less safe
  • Compare convergence: 29 Bisection iterations vs 3 Newton iterations
  • Appreciate the engineering trade-off between speed and reliability

Milestone 3 gave us the regression coefficients. The question changes:

Milestone 3: "What is the model?"
Milestone 4: "At what GDP does the model reach a particular Sales target?"

The target is Sales = 8.0 trillion USD, with Population fixed at its 2023 value.

This is no longer a regression problem

We already fitted the model. We're not changing β₀, β₁, β₂. We're using the model to solve a new mathematical problem. We have one unknown: GDP.

Turn it into a root-finding problem

Define: g(GDP) = PredictedSales(GDP) − 8. When predicted sales equals 8, g(GDP) = 0. That's called root finding.

Why do we need numerical methods?

For this particular linear model, we could rearrange algebraically. But many real mathematical models cannot be rearranged neatly. Numerical root-finding is much more general.

The basic idea

Give me an interval containing the root, and I'll keep cutting that interval in half.

The bracket condition

If f(a) and f(b) have opposite signs (f(a)·f(b) < 0), there must be a root between them — this relies on the Intermediate Value Theorem.

The algorithm

  1. Compute midpoint m = (a+b)/2
  2. Evaluate f(m)
  3. If f(a)·f(m) < 0, root is in [a, m]; otherwise in [m, b]
  4. Repeat until the interval is small enough

Why is Bisection "safe"?

It never leaves the original bracket. Every subsequent interval remains inside it. Bisection can't suddenly produce an absurd answer. That's why we describe it as:

Slow but robust

Convergence rate

The interval is halved every iteration. After n iterations, the interval width is (b−a)/2ⁿ. This is linear convergence — the number of correct digits increases at a steady but slow rate.

A radically different idea

Instead of shrinking a safe interval, Newton says: Look at the slope of the function and jump toward the root.

The Newton formula

x_new = x − f(x)/f'(x)

This is one of the most important formulas in numerical methods.

Where does it come from?

Use the tangent-line approximation. Set y = 0 and solve for x_new. The derivative f'(x) gives the slope, and the formula tells you where the tangent line crosses zero.

For our problem

Because our model is linear in GDP, the derivative is simply β₂ (the GDP coefficient). Each iteration asks: how far are we from the target, and how strongly does Sales respond to GDP?

Why did Newton take only 3 iterations?

For a perfectly linear function, the tangent line is the function itself. Therefore Newton can jump directly to the root.

BisectionNewton
Main ideaKeep halving bracketFollow tangent line
Needs bracket?YesNo
Needs derivative?NoYes
SpeedSlowVery fast near root
ReliabilityHighLower
Your result29 iterations3 iterations

Bisection = safety · Newton = speed

Newton's weakness

Newton is not guaranteed to stay near the root. For complicated functions, it can converge to a different root, oscillate, or diverge. It only sees the function locally — it doesn't know the global shape.

Why both methods gave the same answer

Your project obtained ≈$87,138.33 from both. They agree because your model is linear and well-behaved. If the function were nonlinear with multiple roots, the methods could behave very differently.

The deeper lesson

Milestone 3 gave us the model parameters β. Milestone 4 turns those parameters into a decision question:

What input is required to achieve a desired output?

📝 Summary

Milestone 4 applies the fitted model to answer a business question:

  • Question: What GDP per capita corresponds to $8T in sales?
  • Method: Root-finding on g(GDP) = PredictedSales(GDP) − 8
  • Result: GDP* ≈ $87,138.33
  • Trade-off: Bisection (29 iterations, reliable) vs Newton (3 iterations, faster but needs derivative)
Milestone 5

Regional Prediction

Lagrange vs. Newton Interpolation — estimating Sales at unobserved GDP values

🎯 Learning Objectives

  • Understand interpolation (inside known range) vs extrapolation (outside)
  • Implement Lagrange interpolation using basis polynomials
  • Implement Newton divided differences
  • Recognize Runge's phenomenon with high-degree polynomials
  • Apply local interpolation using k-nearest points for stability

So far:

  • Milestone 1: What relationship are we modeling?
  • Milestone 2: How do we represent the data mathematically?
  • Milestone 3: How do we solve the resulting equations?
  • Milestone 4: Given a target Sales value, what GDP would produce it?

Now:

We know some GDP values and their corresponding Sales values. What Sales should we expect at a GDP value that we never observed?

For example, GDP = $66,000 — there isn't a row with exactly that GDP. We need to estimate between known observations.

Interpolation vs. extrapolation

If the target GDP is inside the observed range [54,973, 81,032], that's interpolation. If outside, that's extrapolation — much more dangerous.

The clever idea

Build a special polynomial for each data point that gives that point a weight of 1 and all other points a weight of 0. Then combine them:

p(x) = y₀L₀(x) + y₁L₁(x) + y₂L₂(x) + ...

At x = x₀: p(x₀) = y₀(1) + y₁(0) + y₂(0) = y₀. The polynomial passes through every point.

The basis formula

Lᵢ(x) = ∏ⱼ≠ᵢ (x − xⱼ)/(xᵢ − xⱼ)

A tiny example

Points: (1,2) and (3,6). At x=2: L₀(2) = (2−3)/(1−3) = 0.5, L₁(2) = (2−1)/(3−1) = 0.5. So p(2) = 2(0.5) + 6(0.5) = 4.

The idea

Instead of constructing all basis polynomials directly, calculate divided differences — generalized slopes, then changes in slopes, then changes in those changes.

First divided difference = slope

f[x₀, x₁] = (y₁ − y₀)/(x₁ − x₀)

Second divided difference

f[x₀, x₁, x₂] = (f[x₁,x₂] − f[x₀,x₁])/(x₂ − x₀)

Conceptually: how is the slope changing? This corresponds to curvature.

Newton's formula

p(x) = f[x₀] + f[x₀,x₁](x−x₀) + f[x₀,x₁,x₂](x−x₀)(x−x₁) + ...

The key advantage: you can extend the polynomial by adding another term when a new data point arrives.

Same polynomial

Given n distinct x-values, there is exactly one polynomial of degree at most n−1 that passes through all n points. Lagrange and Newton are just different representations of the same polynomial.

The dangerous part

You have 10 observations. Using all 10 produces a degree-9 polynomial. It passes through every point perfectly — but between and beyond the points, it can behave wildly.

This is called Runge's phenomenon.

Your project demonstrates this

Full degree-9 polynomial at GDP=66,000 gives ≈$3.9677T. Local (k=4) interpolation gives ≈$4.9780T. That's a huge difference — and 66,000 is inside the data range.

Extrapolation disaster

At GDP=86,032 (just outside the range), the degree-9 polynomial produces ≈$24,478.83T. That's absurd — but the computer correctly evaluated the polynomial. The problem is the model.

A mathematically valid model can still be practically useless.

The solution: local interpolation

Instead of using all 10 points, use the k nearest observations. With k=4, you get a degree-3 polynomial — much more restrained. The idea: nearby information is usually more relevant.

The central lesson

Exact fit ≠ good general behavior

This is one of the most important ML principles hiding inside numerical analysis.

📝 Summary

Milestone 5 estimates Sales at unobserved GDP using polynomial interpolation:

  • Lagrange & Newton: Two representations of the same polynomial
  • Global (degree 9): Passes through all points but can be unstable
  • Local (k=4): Uses nearby points for more stable estimates
  • Key lesson: More flexibility ≠ better prediction. Overfitting is real.
Milestone 6

Global Model Optimization

Multivariate Linear Regression + Least Squares — fitting the best global model to all observations

🎯 Learning Objectives

  • Understand why least squares is needed (10 equations, 3 unknowns)
  • Connect calculus (partial derivatives) to the normal equations
  • Implement standardization to fix numerical conditioning
  • Evaluate model fit using R²
  • Understand the distinction between interpolation and optimized approximation

Milestone 6 is the central milestone of the whole project. It connects everything:

  • Milestone 1: Define the relationship
  • Milestone 2: Turn data into matrices
  • Milestone 3: Build methods for solving linear systems
  • Milestone 4: Find the GDP that reaches a target Sales value
  • Milestone 5: Estimate Sales at an unobserved GDP
  • Milestone 6: Actually fit the best global linear model to all 10 observations
How do we find the Population and GDP coefficients that make our Sales predictions as close as possible to the actual Sales values?

The immediate problem

We have 10 equations but only 3 unknowns (β₀, β₁, β₂). We usually cannot make all 10 equations exactly true.

What does "error" mean?

For observation i: the residual is eᵢ = yᵢ − ŷᵢ. This is how wrong the model was for that observation.

Why not simply add all errors?

Errors can cancel: +2 + (−2) = 0 looks like no error. So we square them:

SSE = Σ(yᵢ − ŷᵢ)²

Our optimization problem: find β₀, β₁, β₂ that minimize SSE.

The connection to linear algebra

The design matrix X and target vector y give us:

ŷ = Xβ

The error is y − Xβ. Least squares minimizes |y − Xβ|².

Setting the gradient to zero

We take partial derivatives with respect to each β and set them to zero. This gives the normal equations:

XᵀXβ = Xᵀy

These are called the normal equations — one of the most important equations in classical linear regression.

The big connection

Minimize squared error
        ↓ (calculus)
XᵀXβ = Xᵀy
        ↓ (linear algebra)
Aβ = b
        ↓ (Milestone 3 solvers)
Best β
        ↓
Predictions

The scale problem

Your two features have wildly different scales: Population ≈ 3×10⁸ vs GDP ≈ 6×10⁴. That's roughly a 10,000× difference. When you calculate XᵀX, the scale difference gets squared to ~10⁸ or more.

Standardization

Convert each feature to a z-score: z = (x − μ) / σ. After standardization, both features are roughly centered around 0 with standard deviation 1.

The dramatic improvement

Raw condition number: 1.8999 × 10²¹ (extremely ill-conditioned)
Standardized condition number: 22.0227 (dramatically better)

This is one of the most important results in the project.

The fix was data preprocessing, not a better solver

When we encounter numerical problems, the better response is often: "Is the system poorly conditioned because of how we represented the data?" Standardization changes the geometry and numerical conditioning of the optimization problem.

Prediction uses the same scaler

During prediction, we reuse the same mean and standard deviation learned during training. We do not recalculate them. This principle is extremely important in ML: Fit preprocessing on training data; reuse it on new data.

How well does the model explain the data?

R² = 1 − SS_res / SS_tot

where SS_res is unexplained squared error and SS_tot is total variation around the mean.

What does R² mean?

Your result: R² = 0.9755. This means approximately 97.55% of the variation in Sales is explained by the fitted linear relationship with Population and GDP.

But be careful: don't say "Population and GDP cause 97.55% of Sales." R² measures explained variation by the model, not causation.

Don't overinterpret with n=10

With only 10 observations, R² = 0.9755 does not prove the model will predict future Sales with 97.55% accuracy. It only describes fit to these observations.

Standardized coefficients

Because the model standardizes features, β₁ and β₂ correspond to: change in predicted Sales associated with a one-standard-deviation increase in that feature, holding the other constant. For raw-space sensitivity, use the chain rule: ∂Sales/∂x = β/σ.

Milestone 5Milestone 6
InterpolationRegression
Can fit points exactlyDoesn't need exact fit
Degree can become 9Only 3 parameters
Goal: pass through observationsGoal: minimize squared error
Can become unstableMuch more constrained

Milestone 5: exact interpolation vs Milestone 6: optimized approximation

📝 Summary

Milestone 6 is the heart of the project. Three equations to remember:

  • Model: ŷ ≈ Xβ
  • Objective: min_β |y − Xβ|²
  • Solution: XᵀXβ = Xᵀy

Key results: Standardization drops the condition number from ~10²¹ to ~22. R² = 0.9755. The fitted model explains about 97.55% of observed Sales variation.

Milestone 7

Error Propagation

If Population and GDP are uncertain, how uncertain is our predicted Sales?

🎯 Learning Objectives

  • Understand how input uncertainty creates output uncertainty
  • Use partial derivatives as sensitivities for analytical error propagation
  • Implement Monte Carlo simulation to empirically estimate uncertainty
  • Build an uncertainty budget to identify the dominant source of error
  • Convert standardized coefficients back to raw units using the chain rule

From Milestone 6, we have a model: Sales = β₀ + β₁·Population + β₂·GDP

Think of it as a machine:

Population ───────┐
                  ↓
               [ MODEL ] ───→ Predicted Sales
                  ↑
GDP ──────────────┘

But here's the real-world problem: Are those inputs perfectly accurate? No. Population might be 335M ± 335K. GDP might be $85K ± $850.

Uncertainty in the inputs creates uncertainty in the prediction.

What is error propagation?

Error here means uncertainty or measurement variation — not a mistake. Propagation means how that uncertainty travels through the mathematical system. So: error propagation = determining how uncertainty in inputs affects uncertainty in the output.

Why do we need this?

Milestone 6 gave us a prediction, but it doesn't tell us how trustworthy it is. Instead of saying "Sales will be $7.50T," we should say: "Our model predicts approximately $7.50T, with about $0.08T of uncertainty from input measurement errors."

Partial derivatives as sensitivities

For our linear model:

∂Sales/∂Population = β₁
∂Sales/∂GDP = β₂

Think of β₁ and β₂ as sensitivities — how strongly the output reacts to each input.

The chain rule for standardization

Because the model was trained on standardized features, we need to convert back to raw units:

∂Sales/∂Population = β₁/σ_Population
∂Sales/∂GDP = β₂/σ_GDP

The key equation

σ_Sales ≈ √((∂Sales/∂P · σ_P)² + (∂Sales/∂G · σ_G)²)

This is the delta method / first-order error propagation formula. We square independent uncertainties and combine them using root-sum-of-squares.

The idea

Instead of doing calculus, generate thousands of plausible Population/GDP values and see how much the prediction changes.

Simulation 1: Pop=334.8M, GDP=$85,431 → Sales=7.48T
Simulation 2: Pop=335.2M, GDP=$84,721 → Sales=7.42T
Simulation 3: Pop=334.9M, GDP=$85,177 → Sales=7.45T
...
Simulation 20,000: → Sales=7.44T

The standard deviation of all those predictions gives us our empirical estimate of Sales uncertainty.

Why Monte Carlo?

The analytical method assumes linearity and independence. Monte Carlo doesn't depend on those assumptions — it tests the uncertainty empirically. If both methods agree, that gives us confidence.

Your results

Analytical uncertainty ≈ 0.08333T · Monte Carlo uncertainty ≈ 0.08448T. They're extremely close — good validation.

Variance contributions

Population contribution ≈ 0.000012 · GDP contribution ≈ 0.006932

GDP contributes roughly 580× more variance to predicted Sales than Population.

What is an uncertainty budget?

Like a financial budget, but for uncertainty. You want to know: where is most of the uncertainty coming from?

Total prediction uncertainty
├── Population → tiny contribution
└── GDP → dominant contribution

If your objective is to improve the reliability of Sales prediction: improving the quality of the GDP input is potentially much more valuable than improving Population.

The volume knob analogy

Population is a small knob — move it a little, Sales barely changes. GDP is a large knob — move it the same relative amount, Sales changes much more. If the GDP knob itself is shaky, your final prediction becomes shaky too.

📝 Summary

Milestone 7 quantifies how uncertain our prediction is:

  • Analytical method: Uses partial derivatives (sensitivities) × input uncertainties
  • Monte Carlo: Simulates thousands of possible inputs to empirically measure output spread
  • Result: ~$0.083T uncertainty, with GDP dominating (~580× more than Population)
  • Business insight: Improving GDP data quality would have the greatest impact on prediction reliability
Milestone 8

Time-Series Extension: Forecasting 2025/2026

Predicting the future when the model's own inputs don't exist yet

🎯 Learning Objectives

  • Understand why prediction becomes a two-stage process for future years
  • Fit trend models: Year → Population and Year → GDP
  • Distinguish interpolation (inside known range) from extrapolation (outside)
  • Understand why uncertainty grows with forecast horizon
  • See the complete 8-milestone pipeline as one connected system

Milestone 8 is where the project changes from explaining the past to predicting the future.

Our Sales model needs Population and GDP, but for 2025 and 2026 we don't know Population and GDP yet. So how can we predict Sales?

Prediction becomes a two-stage process

Previously:
Population ──┐
             ├──→ Sales model ──→ Sales
GDP ─────────┘

Now:
                ┌──→ Population forecast ──┐
Year ───────────┤                           │
                └──→ GDP forecast ─────────┤
                                            ↓
                                      Sales model
                                            ↓
                                      Sales forecast

So we now have two models before we get Sales:

  1. Year → Population
  2. Year → GDP
  3. Population, GDP → Sales (the Milestone 6 model)

We use Year as the input

Your data shows Population generally increasing and GDP generally increasing over time. So we can fit: Population = a + b(Year) and GDP = c + d(Year).

Why use regression again?

This is a beautiful connection. Milestone 6 already taught us how to fit y = β₀ + β₁x. Now we reuse the same machinery. We're not inventing a new algorithm — we're reusing what we already built.

Why use degree 1 (linear trend)?

You only have 10 years of data. A high-degree polynomial could memorize historical fluctuations rather than learn the underlying trend. A simple linear trend is a reasonable baseline. Remember Milestone 5: more flexibility isn't automatically better.

The most important terminology

Interpolation — predict inside known data

known ─── unknown ─── known
          ↑
       interpolation

Generally safer.

Extrapolation — predict outside known data

known ───────────────→ unknown
                       ↑
                  extrapolation

Generally riskier.

Milestone 5 vs Milestone 8

Milestone 5 used interpolation (estimating inside the observed GDP range). Milestone 8 uses extrapolation (predicting beyond 2023). That's why we should be much more cautious.

Why extrapolation is dangerous

Inside the range, neighboring observations constrain the curve. Outside the range, there are no observations telling the curve what to do. The historical data cannot tell you with certainty what happens after the last observation.

Forecasting is not just extending a line. It is extending an assumption.

Why we care about residuals

Historical Population trend errors (residuals) give us a rough measure of how uncertain our trend prediction is. We calculate their standard deviation: pop_resid_std and gdp_resid_std.

Uncertainty grows with forecast distance

The code uses: σ_future = σ_historical × (1 + 0.5d), where d = years beyond the last observation. For 2025 (d=2): uncertainty is 2× historical. For 2026 (d=3): 2.5×.

This is a naive uncertainty-growth heuristic — a modeling choice, not a fundamental law. Sophisticated models (ARIMA, Bayesian forecasting, etc.) could estimate uncertainty differently.

The complete pipeline

MILESTONE 1: Define the relationship
        ↓
MILESTONE 2: Matrix construction
        ↓
MILESTONE 3: Solve equations
        ↓
MILESTONE 6: Fit Sales model
        ↓
Sales = f(Pop, GDP)
        ↓
   ┌────┴────┐
   ↓         ↓
M4: Target  M7: Uncertainty
GDP?        propagation
   ↓         ↓
   └────┬────┘
        ↓
MILESTONE 8
        ↓
Future Year → Pop forecast → GDP forecast
        ↓
   Sales model → Future Sales
        ↓
   Uncertainty interval
TermMeaning
Time seriesData measured over time
TrendGeneral direction of a variable over time
ForecastingPredicting future values from past observations
InterpolationEstimate inside known range
ExtrapolationEstimate outside known range
ResidualActual − predicted
Forecast horizonHow far into the future we predict
HeuristicPractical rule, not a fundamental law
Recursive propagationUncertainty moving through multiple models

The single most important equation

Year → {Population, GDP} → Sales

Milestone 6 was: Population, GDP → Sales. Milestone 8 adds: Year → Population, GDP. We had the Sales model already. The missing problem was: where do future Population and GDP come from?

📝 Summary

Milestone 8 extends the project into the future:

  • Two-stage forecasting: Year → Population/GDP, then Population/GDP → Sales
  • Extrapolation: Predicting beyond the 2014–2023 observed range is inherently riskier than interpolation
  • Uncertainty grows with forecast distance — 2026 predictions are less certain than 2025
  • The complete chain: We started by building a mathematical relationship; converted it into a solvable problem; solved and stabilized it; used it for target finding and interpolation; quantified its uncertainty; and finally extended it into the future

The entire 8-milestone journey in one sentence: We started by building a mathematical relationship between Sales, Population, and GDP; converted it into a solvable linear-algebra problem; solved and stabilized it; used it for target finding and interpolation; quantified its uncertainty; and finally extended it into the future by forecasting the inputs that the Sales model itself requires.