Linear Regression and Gradient Descent

Learn how a linear regression model predicts a number from one or many features, and how training finds its parameters. Measure fit with the squared-error cost, minimize it step by step with gradient descent and directly with the normal equation, and write both as vectorized NumPy code. Scale features so training converges quickly, add polynomial features to fit curved relationships, and fit, evaluate and interpret models with scikit-learn.

IntermediateLesson 2 of 9 in Machine Learning Course

What you will learn

  1. Describe a regression task with a training set, write the one-feature model fw,b(x)=wx+b, and measure how well a choice of parameters fits the data with the squared-error cost.
    • Set up the linear model for one feature
      Use the standard notation for training data, write the model with its weight and bias, and read both parameters in the units of the data.
    • Measure fit with the squared-error cost function
      Compute the errors of a model on the training set, combine them into the squared-error cost J(w, b), and read the cost as a bowl-shaped function of the parameters.
  2. Minimize the cost step by step with gradient descent, choose a learning rate that converges, and know when to use batch, stochastic or mini-batch updates.
    • Apply the gradient descent update rule
      Compute the partial derivatives of the cost for linear regression and update the weight and bias together, step by step, toward the minimum.
    • Choose the learning rate and check convergence
      Recognize learning rates that are too small or too large, read a learning curve, choose a rate by trying a range of values, and decide when training has converged.
    • Compare batch, stochastic and mini-batch gradient descent
      Explain how batch, stochastic and mini-batch gradient descent differ in the data used per update, the shape of the learning curve and when each is useful, and set them up in scikit-learn.
  3. Write the multiple linear regression model with vectors and a design matrix, interpret its weights, and implement predictions, cost and gradient descent with NumPy array operations instead of loops.
    • Write and interpret the multiple linear regression model
      Write the model with n features as a dot product, organize the data in a design matrix, and interpret each weight with the other features held fixed.
    • Compute predictions and cost with NumPy arrays
      Replace loops with vectorized NumPy operations to compute all predictions and the cost at once, and avoid the shape and broadcasting errors that silently give wrong results.
    • Run vectorized gradient descent for many features
      Update all weights and the bias together with a vectorized gradient, write the full training loop, and check the result against an independent solution.
  4. Rescale features so gradient descent converges quickly, apply the same scaling to new data without leakage, and fit curved relationships by adding polynomial and engineered features to a linear model.
    • Rescale features with min-max, mean normalization or standardization
      Explain why features on very different scales slow gradient descent, and compute min-max scaling, mean normalization and z-score standardization by hand.
    • Apply scaling correctly in a machine learning workflow
      Fit the scaling on the training set only, apply the same stored values to validation, test and new inputs, and interpret weights learned from scaled features.
    • Fit curves with polynomial and engineered features
      Create new features from existing ones, use powers of a feature to fit curved relationships with the same linear regression methods, and choose a polynomial degree without overfitting.
  5. Find the least-squares parameters directly with the normal equation, decide when it beats gradient descent, fit models with scikit-learn, and evaluate and interpret the fitted model.
    • Solve for the parameters with the normal equation
      Set the gradient of the cost to zero, solve the normal equation for all parameters at once, and compute it by hand for a small dataset and with NumPy.
    • Choose between the normal equation and gradient descent
      Compare the two methods on speed, settings and scalability, and recognize and handle a matrix that cannot be inverted because of redundant features or too few examples.
    • Fit linear and polynomial models with scikit-learn
      Train, inspect and use LinearRegression and SGDRegressor in scikit-learn, combine them with scaling and polynomial features in pipelines, and compare them with your own implementation.
    • Evaluate and interpret a fitted regression model
      Measure prediction error with MSE, RMSE and R² on held-out data, read residual plots, compare with a simple baseline, and state carefully what the weights mean.

Linear Regression study guide

5 chapters

1

Build a model and measure its errors

Predicting a delivery time starts with two choices: which input describes the delivery, and how to measure a missed prediction. A line turns distance into a predicted time through a weight and a bias. The observed times let you compare candidate lines using squared errors. Reading the parameters in their units and separating predictions from observations prepares you to judge what the fitted line can tell you about a new delivery.

1.1 Predict a number with a line

A delivery service records distances and delivery times. The distance is an input feature; the recorded time is the target. Learning a rule from these labeled examples is supervised learning. Predicting a numeric time is regression. Predicting a category such as "late" or "on time" would be classification.

Name the data and the prediction

Write the number of training examples as m. Example i is (x(i),y(i)): its feature and its observed target. The superscript in parentheses is an index. Thus x(2) means the second input, while x2 means a squared input.

Our training set contains four deliveries: (1 km, 10 min), (2 km, 14 min), (3 km, 15 min), and (4 km, 21 min). Here m=4 and the third example has x(3)=3 and y(3)=15. Each row connects an input with the target measured for that same delivery.

The one-feature model is

y^=fw,b(x)=wx+b.

The hat marks a prediction. The target y comes from the observations; the prediction y^ comes from the model. Statistics texts often write this as y^=β0+β1x, with β0=b and β1=w.

Read the weight and bias

The weight w is the slope. It gives the change in predicted target for one extra unit of input. The bias b is the intercept: the prediction when the input is zero. Training chooses these two parameters. The learning rate and number of training iterations are hyperparameters chosen to control training.

For the delivery data, the best-fitting line is y^=3.4x+6.5. The weight has units of minutes per kilometer. Increasing distance by 1 km increases the predicted time by 3.4 minutes. At 2.5 km, multiply first: 3.4⋅2.5=8.5. Then add the bias: 8.5+6.5=15 minutes. This is a prediction for a delivery, not a claim that every delivery at this distance takes exactly 15 minutes.

The intercept is 6.5 minutes at 0 km. Reading it as fixed handling time would require knowledge of the delivery process. These observations only cover distances from 1 to 4 km; they give no direct evidence at zero.

Keep interpretation within the evidence

A prediction between observed distances is an interpolation. Using the line at 10 km gives 3.4⋅10+6.5=40.5 minutes, an extrapolation beyond the observed range. The arithmetic still works, but the relationship may change over longer journeys. An intercept can also lack a practical interpretation when a zero input is impossible.

The fitted slope describes an association in the data. It does not establish that changing distance alone would cause that change in time; route conditions and other related factors can matter. Training selects the line using a measure of error on the training set. Testing its predictions on held-out data checks how well that learned relationship carries to new examples.

Key Takeaways

  • Linear regression learns a numeric target from labeled examples.
  • In y^=wx+b, training learns the weight and bias.
  • The weight has target units per feature unit; the bias has target units.
  • A prediction and an observed target are different quantities.
  • Extrapolation and causal interpretations need evidence beyond the fitted line.

1.2 Measure the errors of a fitted line

Two lines can both look close to a scatter plot. A cost function gives each line one number so their fits can be compared. Hold the training data fixed and change the parameters; the cost measures how the resulting predictions miss those targets.

Square before adding

Define the prediction error as e(i)=y^(i)−y(i). A positive error means an overprediction. A residual plot commonly uses the opposite sign, y(i)−y^(i). Squaring either gives the same result.

The squared-error cost is

J(w,b)=12m∑i=1m(y^(i)−y(i))2.

Squaring prevents positive and negative errors from canceling. It also makes large misses count much more heavily: one error of 10 minutes contributes 100 min², as much as 100 errors of 1 minute. An outlier can therefore pull a least-squares line toward itself. Check unusual observations for errors and for whether they belong to the problem being modeled.

Dividing by m averages across examples. The additional factor of one half simplifies the derivatives used for training. Mean squared error, or MSE, omits that half, so MSE=2J. Both select the same parameters.

Compare two lines

For the four deliveries, try w=3 and b=7.

Distance (km)Target (min)Prediction (min)Error (min)Squared error (min²)
1101000
21413−11
3151611
42119−24

The squared errors sum to 6. Divide by twice the four examples: J(3,7)=6/8=0.75. The MSE is 6/4=1.5 min².

For w=3.4 and b=6.5, predictions are 9.9, 13.3, 16.7, and 20.1 minutes. Their errors are −0.1, −0.7, 1.7, and −0.9. Squaring gives 0.01, 0.49, 2.89, and 0.81, totaling 4.2. Thus J=4.2/8=0.525. This line minimizes the sum of squared errors: it is the least-squares fit.

Adding raw errors would fail. Both the best line and many worse lines pass through the mean point, (2.5,15), and have raw errors summing to zero. A zero sum can hide large misses on opposite sides.

Picture cost in parameter space

A cost plot uses parameters as axes, not delivery distance and time. Holding b=6.5, the costs at weights 2, 3.4, and 5 are 7.875, 0.525, and 10.125. These lie on a U-shaped parabola. Allowing both parameters to vary gives a bowl; a contour joins parameter pairs with equal cost.

This cost is convex: every local minimum is global. With one feature and input values that are not all equal, the minimizing weight and bias are unique. A suitable gradient descent step can therefore move toward the best fit without becoming trapped in a worse local minimum.

Read error in useful units

MSE and cost have squared target units. Taking the square root of MSE gives RMSE, in target units. For the best delivery line, MSE=1.05 min² and RMSE=1.05≈1.02 minutes. RMSE describes error magnitude on the evaluated examples; it is not the error of every individual prediction.

Key Takeaways

  • Compute prediction minus target, square each error, and then average.
  • J=MSE/2; minimizing either gives the same fit.
  • Squaring makes least squares sensitive to large errors.
  • The cost varies over parameters and is convex for linear regression.
  • RMSE returns squared error to the target’s own units.
  • A raw sum of errors can be zero for a poorly fitting line.
2

Train with gradient descent

Training can find the best-fitting line through repeated small changes to its parameters. The gradient gives a direction, the learning rate controls each step, and a cost curve shows whether the steps are working. You will calculate an update, diagnose rates that are slow or unstable, and compare methods that use all examples or only a small group at a time. The amount of data per update changes both the computational work and the noise in training.

2.1 Move the parameters downhill

Gradient descent improves a model by repeating a small calculation. At the current parameters, find the slope of the cost in each parameter direction. Then move in the opposite direction. A positive slope calls for a decrease; a negative slope calls for an increase.

Calculate both slopes

A partial derivative is the slope as one parameter varies while the others stay fixed. For the cost with the factor 1/(2m),

gw=∂J∂w=1m∑i(y^(i)−y(i))x(i),gb=∂J∂b=1m∑i(y^(i)−y(i)).

The weight gradient multiplies each error by its input. The bias gradient averages the errors without that multiplication, because a change in bias adds the same amount to every prediction. The derivative of a square supplies a factor of 2, canceling the half in the cost.

Choose a positive learning rate α and update:

w←w−αgw,b←b−αgb.

These assignments use the same old parameters. Calculate both gradients first. If the weight changes before the bias gradient is calculated, the two slopes no longer describe the same point on the cost surface.

Work through the first update

Start the delivery model at w=b=0 and use α=0.1. Every prediction is zero, so the errors are −10, −14, −15, and −21 minutes.

For the weight, multiply the errors by the distances:

(−10)(1)+(−14)(2)+(−15)(3)+(−21)(4)=−167.

Divide by four: gw=−41.75. For the bias, the error sum is −60, so gb=−15. Now apply both updates:

wnew=0−0.1(−41.75)=4.175, bnew=0−0.1(−15)=1.5.

Both parameters increase because their gradients were negative. The cost drops from 120.25 to about 5.59. The next iteration must compute fresh predictions at these new values; reusing the first errors would keep stepping in an outdated direction.

Turn the rule into code

With one-dimensional NumPy arrays x and y, one batch update is:

err = w * x + b - y
grad_w = (err * x).mean()
grad_b = err.mean()
w = w - alpha * grad_w
b = b - alpha * grad_b

The gradients are stored before either assignment. Subtracting them matches the convention prediction minus target. Reversing that error sign while keeping the same subtraction sends the update uphill. Omitting the average makes a step four times as large on these four examples; adding more examples would then change the effective step size.

What happens near the bottom

A fixed learning rate can still produce shrinking steps: the gradient becomes smaller as the bowl flattens. At a minimum, both derivatives are zero. With a suitable rate, the convex cost allows convergence from any starting parameters. On these deliveries, rate 0.1 comes within 10−6 of the minimum cost after about 480 steps. The stopping rule determines how close the final parameters come to 3.4 and 6.5.

Key Takeaways

  • Subtract the learning rate times each partial derivative.
  • Compute every gradient from the same current parameters.
  • The weight gradient includes the input; the bias gradient does not.
  • A fixed learning rate still gives shorter steps as gradients shrink.

2.2 Choose a rate and recognize convergence

A correct gradient can still train badly if its steps are poorly sized. The learning rate controls how much of the gradient becomes a parameter change. Its useful scale depends on the data and the feature units, so inspect training progress instead of borrowing a rate without checking it.

Read a learning curve

Plot training cost against iteration number. For batch gradient descent on the linear-regression cost, a suitable rate gives a falling curve that flattens near the minimum. This is a learning curve for optimization; its horizontal axis counts updates.

On the delivery data, rate 0.01 gives costs about 101.4, 85.5, 72.2, 61.1, and 51.7 after the first five steps. The direction is useful, but progress is slow. It takes about 4,800 steps to reach a cost within 10−6 of 0.525. Rate 0.1 reaches that accuracy in about 480 steps.

Rate 0.3 gives costs about 269.1, 606.7, 1,371.5, 3,104.1, and 7,029.4. The steps overshoot the bottom and move farther away. This is divergence. For these unscaled data, rates above about 0.24 are unstable in the steep direction. That threshold belongs to this dataset, not to linear regression generally.

Curve behaviorLikely interpretationNext check
Falls steadily but very slowlyRate may be too smallTry a larger rate
Rises or oscillatesRate may be too largeReduce it and inspect the code
Falls quickly, then flattensNear convergenceCheck a stopping criterion
Search over rates

Try a spread such as 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, and 1. Start each run from the same parameters and compare curves over the same number of updates. A factor of about three exposes useful differences without requiring many nearly identical runs. Choose a rate that lowers cost quickly and steadily; a slightly smaller rate leaves room for numerical variation.

If cost rises, reduce the rate by a factor of 3 or 10. If even a very small rate fails, inspect the update sign, averaging, and array shapes. A prediction vector minus a target column can silently create a matrix, so a scalar cost alone does not establish that the code is correct.

Decide when to stop

One automatic rule stops when the cost decrease in an iteration is less than a small tolerance, for example 10−3. Interpret that threshold in relation to the scale of the cost. A tiny rate can also cause a tiny improvement while the parameters are still far from the best fit. Check the curve and compare with a longer run or an independent least-squares result.

Set a maximum iteration count as a computational limit. Reaching it means training stopped; it does not establish convergence. Different problems may need dozens or thousands of steps.

Separate rate problems from scale problems

With features on very different scales, a stable rate for one direction can make another direction move slowly. Rescale the features before searching again. Standardizing the delivery distance allows rate 0.5 to reach the same cost accuracy in about 14 steps. Scaling changes the geometry of training, so a rate suitable for raw features need not be the best rate after transformation.

Key Takeaways

  • Judge batch training with cost plotted against iterations.
  • Too small a rate is slow; too large a rate can diverge.
  • Compare several rates from the same starting point.
  • A tiny cost change needs interpretation alongside the rate and cost scale.
  • An iteration limit is not evidence of convergence.
  • Feature scaling can make a much faster stable rate possible.

2.3 Choose how much data each update uses

An update does not always need the whole training set. Batch, stochastic, and mini-batch gradient descent use different amounts of data to estimate the direction of improvement. This changes the work per update, the number of updates in a pass, and the appearance of the learning curve.

Count updates and epochs

An epoch is one full pass through the training examples. It is different from an update.

MethodExamples per updateUpdates in an epoch of 10,000 examples
BatchAll 10,0001
Stochastic110,000
Mini-batch of 100100100

Batch gradient descent computes the full training gradient each time. Its cost curve is smooth when the rate is suitable, but every update must process every example. With millions of examples, waiting for a single update can be expensive.

Stochastic gradient descent, or SGD, changes the parameters after each example. A single update is cheap and can begin improving the model before a full pass finishes. A mini-batch uses a small group, often 32 to 256 examples, and processes that group with vectorized operations. This combines frequent updates with efficient array computation.

Expect noisy progress

A gradient from one example may point against the full training gradient. It improves the fit to that example, which can temporarily worsen the fit to others. SGD and mini-batch costs therefore fluctuate while trending down on average. An upward jump after one update is not the same diagnosis as a rising full-batch curve. Inspect full-data cost per epoch or use a moving average.

With a fixed rate, SGD keeps fluctuating near the minimum. A learning schedule lowers the rate over time so later changes become smaller. The default inverse-scaling schedule in SGDRegressor uses η=η0/t0.25, with initial setting eta0=0.01. The update count t controls the decay.

Shuffle and choose a method

Shuffle training examples, ideally each epoch. Sorted deliveries place similar distances next to one another, creating correlated updates and making the result sensitive to order. Shuffling mixes those influences. SGDRegressor uses shuffle=True by default.

For small and medium datasets, a direct least-squares solver is convenient. Batch gradient descent is useful for learning and for an explicit iterative implementation. Stochastic and mini-batch methods suit large datasets, streaming observations, and data that cannot all be held in memory. An online workflow still needs a consistent feature transformation; changing scaling without adapting the model changes the meaning of its weights.

Read scikit-learn’s parameter names

In handwritten formulas, α means learning rate. In SGDRegressor, eta0 controls the initial learning rate and alpha controls regularization strength. Its defaults include penalty='l2' and alpha=0.0001, so its default objective is penalized. Set penalty=None for plain least squares, and place a scaler before it in a pipeline. Comparing a penalized model with an unpenalized direct fit would compare different objectives.

Key Takeaways

  • An epoch visits the whole training set; an update changes parameters.
  • Batch uses all examples, SGD one, and mini-batch a small group.
  • Noisy methods need progress checks over more than one update.
  • Shuffling reduces patterns caused by example order.
  • A decreasing learning schedule reduces late SGD fluctuations.
  • In SGDRegressor, eta0 and alpha control different settings.
3

Predict and train with many features

Most prediction tasks have several useful inputs. A design matrix keeps their roles consistent while a weight vector turns each row into one prediction. NumPy expresses the repeated calculations as matrix operations, making predictions, costs, and gradients concise and fast. Following the shapes at each step also reveals errors that can silently produce the wrong result. Numerical derivative checks and an independent fit give complementary ways to inspect your implementation.

3.1 Combine several features in one prediction

Distance alone leaves some delivery time unexplained. A model can also include the number of stops. Multiple linear regression keeps one numeric target and gives each input feature its own weight, with one shared bias.

Arrange rows and columns

With n features, one example is the vector 𝐱(i)=(x1(i),…,xn(i)). The subscript selects a feature; the superscript in parentheses selects an example. Place examples in rows of the design matrix X and features in columns. Its shape is m×n. The target vector has length m, the weight vector has length n, and the bias is a scalar.

For distance and stops, keep column 1 as kilometers and column 2 as stop counts. A new row must follow that same order. Swapping columns at prediction time changes the meaning of the calculation even if the software accepts the shape.

The model is

y^=w1x1+⋯+wnxn+b=𝐰⋅𝐱+b.

The dot product multiplies each feature by its matching weight and adds the products. It does not multiply features together.

Work a two-feature prediction

Suppose the distance weight is 2.5 minutes per kilometer, the stop weight is 4 minutes per stop, and the bias is 5 minutes. For a 6 km delivery with 3 stops,

y^=2.5⋅6+4⋅3+5=15+12+5=32 minutes.

The distance contribution is 15 minutes, the stop contribution is 12, and the bias adds 5. A delivery with the same distance and one extra stop receives a prediction 4 minutes higher. Holding other inputs fixed is essential when reading a multiple-regression weight.

Interpret weights in their units

The distance weight in a distance-only model can differ from its weight in a model that also includes stops. The second model assigns a separate contribution to stops; the first cannot. Adding or removing a related feature can substantially change another weight, including its sign.

A larger numerical coefficient is not necessarily a more important feature. Expressing distance in meters changes 2.5 min/km to 0.0025 min/m without changing any prediction. Scaling the inputs to comparable units makes coefficient magnitudes easier to compare, though correlated features can still make individual weights unstable.

Know what an additive model expresses

Each ordinary input adds a fixed amount per unit, whatever the other inputs are. If the effect of distance depends on the number of stops, add a product feature to express that interaction. A curved effect can be represented by powers of an input. These are additional columns with their own weights.

All input columns must be numeric. Encode a category such as vehicle type into numeric indicators, for example 0/1 columns. When fitting an intercept, a full set of category indicators introduces redundancy because those indicators add up to the intercept’s column of ones.

The term multiple regression means several input features and one target. Some sources use "multivariate" for this, while others use it for several targets. Check which meaning is intended before comparing implementations.

Key Takeaways

  • Rows represent examples; columns represent features.
  • The model has one weight per feature and one bias.
  • Interpret a weight with the other features held fixed.
  • Feature units and correlated inputs affect coefficient comparisons.
  • Powers and products add curved effects and interactions.

3.2 Calculate predictions and cost with arrays

NumPy can evaluate the model for every example with one array operation. This is vectorization: express the calculation over complete arrays and let compiled numerical code carry out the repeated work. The array shapes must still match the mathematical roles.

From a loop to a dot product

One prediction can be calculated by starting with the bias and adding weighted features:

f = b
for j in range(n):
    f += w[j] * x[j]

The equivalent expression is np.dot(w, x) + b. For all training rows, write y_hat = X @ w + b. Here X.shape == (m, n) and w.shape == (n,), so the matrix product has shape (m,). NumPy broadcasts the scalar bias to all entries.

The multiplication operator matters. X * w scales each column element by element and returns an (m, n) array. It has not added the feature contributions within each row. X @ w does that addition; (X * w).sum(axis=1) is another way to obtain the same product.

Calculate a complete cost

Use three deliveries with two features:

X = np.array([[2, 1], [4, 3], [6, 2]])
y = np.array([12, 24, 27])
w = np.array([2.5, 4.0])
b = 5.0

The rows contain distance in kilometers and stops. The first prediction is 2(2.5)+1(4)+5=14 minutes. The other predictions are 27 and 28. Subtract the targets to get errors 2, 3, and 1. Their squares sum to 4+9+1=14, so J=14/(2⋅3)≈2.33.

The vectorized calculation is:

y_hat = X @ w + b
err = y_hat - y
cost = np.mean(err ** 2) / 2

A mean already divides by the number of examples. Dividing by that number again would make the cost too small. NumPy executes its array loops in compiled code and can use optimized linear algebra routines, which is especially useful for many rows and columns.

Catch a silent shape error

A target column (m, 1) and a prediction vector (m,) do not subtract row by row. Broadcasting can produce an (m, m) matrix, pairing every target with every prediction. No exception is required, so an apparently valid cost can describe the wrong errors.

Keep targets one-dimensional with y = y.ravel() when that matches the intended one-target data. Inspect the shapes of predictions and errors; both should be (m,). For a single new example with several features, pass a row of shape (1, n) to an estimator that expects a design matrix.

Put the bias into the matrix

An alternative adds a first column of ones to create Xb and stores 𝜽=(b,w1,…,wn). Then predictions are Xb𝜽. The first product contributes the bias to every row. This convention is useful for the normal equation; keep its parameter order consistent so the intercept is not mistaken for a feature weight.

Key Takeaways

  • X @ w + b gives one prediction per row.
  • X * w still needs a row sum to produce predictions.
  • np.mean(err ** 2) / 2 computes the squared-error cost.
  • Keep predictions and targets one-dimensional to avoid accidental broadcasting.

3.3 Train all weights with vectorized gradients

The multiple-feature update follows the same rule as the one-feature update. Every weight needs an average of error times its feature. A matrix product computes all those averages together, while the bias uses the plain mean error.

Follow the dimensions

With errors err = X @ w + b - y, use:

grad_w = X.T @ err / m
grad_b = err.mean()

The transpose X.T has shape (n, m). Multiplying by the length-m error vector gives a length-n gradient, one value per weight. In symbols,

∇𝐰J=1mX⊤(X𝐰+b−𝐲).

Each column of the original design matrix is paired with the errors from its rows. Writing X @ err reverses these roles. It usually causes a shape error; if the matrix happens to be square, it can silently calculate the wrong result.

Work one update

Take X = [[2, 1], [4, 3], [6, 2]], targets [12, 24, 27], zero weights and bias, and learning rate 0.01. Predictions start at zero, giving errors −12, −24, and −27.

For distance, the weighted-error sum is −24−96−162=−282; its mean is −94. For stops, the sum is −12−72−54=−138; its mean is −46. The bias gradient is (−12−24−27)/3=−21.

Subtract 0.01 times each gradient. The new weights are (0.94,0.46) and the bias is 0.21. The cost falls from 241.5 to about 141.06. Every new value came from the same old predictions.

Keep the loop consistent
m, n = X.shape
w = np.zeros(n)
b = 0.0
history = []
for _ in range(num_iters):
    err = X @ w + b - y
    grad_w = X.T @ err / m
    grad_b = err.mean()
    w = w - alpha * grad_w
    b = b - alpha * grad_b
    new_err = X @ w + b - y
    history.append(np.mean(new_err ** 2) / 2)

This records cost after each update. Label the curve consistently when comparing it with a curve that includes the initial cost. Avoid changing one weight inside a feature loop before computing the other gradients. Scale features when their ranges differ greatly so one learning rate can work efficiently across directions.

Check the formula and the fitted result

A finite-difference check changes one parameter by a small amount while fixing all others:

gj≈J(wj+ε)−J(wj−ε)2ε.

Try ε=10−4 at a point away from the minimum and compare this numerical slope with the coded derivative. Check the bias in the same way. A missing average or wrong sign shows up even if another learning rate could partly hide it during training.

Also compare a converged fit with an independent least-squares solver on the same transformed data. When the solution is unique, parameters should agree within numerical tolerance. With redundant features, different parameter vectors can give the same best predictions. Compare training predictions and cost in that case. Agreement at the minimum checks the fitted result; it cannot establish that every intermediate gradient was correct.

Key Takeaways

  • X.T @ err / m gives one averaged gradient per weight.
  • Compute weight and bias gradients before updating any parameter.
  • Recompute errors when recording post-update cost.
  • Finite differences test the derivative at a chosen point.
  • Independent fits check the result; redundancy can prevent coefficient agreement.
4

Scale inputs and fit curved relationships

The inputs determine both the shapes a model can fit and how easily its training algorithm finds a fit. Scaling puts columns in comparable coordinates, while powers and products add curved effects and interactions. These transformations become part of the prediction workflow: learn their settings from training data and reuse them on new examples. Validation data help choose useful flexibility without mistaking a close training fit for good prediction.

4.1 Put features on comparable scales

A floor-area feature may span hundreds of square meters while bedroom counts span only a few units. In gradient descent, those scales stretch the cost surface into a narrow valley. Steps can zigzag across it while barely moving along it. Feature scaling makes a faster stable path possible.

Compare three transformations

Compute each transformation separately for each training feature.

MethodTransformationWhat it sets
Min-maxx′=(x−min⁡)/(max⁡−min⁡)Training range from 0 to 1
Mean normalizationx′=(x−μ)/(max⁡−min⁡)Training mean 0; values within −1 to 1
Standardizationz=(x−μ)/σTraining mean 0 and standard deviation 1

For areas from 30 to 200 m², min-max scaling sends 120 m² to (120−30)/(200−30)=90/170≈0.53. The endpoints become zero and one.

For the training areas 50, 80, 110, 140, and 170 m², the mean is 110 and the range is 120. Mean normalization sends 170 to (170−110)/120=0.5. Centering by the mean is different from centering by the minimum.

Calculate standardization

The deviations from the training mean are −60, −30, 0, 30, and 60 m². Their squared sum is 9,000 m⁴. Divide by five and take the square root:

σ=9000/5=1800≈42.43 m2.

The standardized value for 170 m² is 60/42.43≈1.41; 50 m² becomes about −1.41. StandardScaler uses this population-style divisor, equivalent to NumPy’s ddof=0, not the sample-standard-deviation divisor of four.

Standardization changes location and scale. It does not turn a skewed distribution into a normal one. Min-max scaling is sensitive to extreme values: one very large maximum can squeeze most observations into a small part of the interval. Inspect the feature distribution before choosing a transformation.

See why training accelerates

For the delivery distances, the training mean is 2.5 km and the standard deviation is about 1.118 km. With raw distances, learning rate 0.1 takes about 480 steps to reach a cost within 10−6 of the minimum. After standardizing distance, rate 0.5 takes about 14 steps. Scaling reduces the imbalance between parameter directions. Strong correlations can still leave a narrow valley, so comparable ranges do not guarantee circular contours.

Translate the model, not the predictions

The standardized delivery fit has weight about 3.80 minutes per standard deviation of distance and bias 15 minutes. It still predicts 9.9, 13.3, 16.7, and 20.1 minutes for the original four deliveries. With an intercept and unpenalized least squares, shifting and rescaling nonconstant features preserves the available predictions; the coefficients express them in new coordinates.

Exact identical ranges are unnecessary. Features on roughly comparable scales, such as around −3 to 3 or 0 to 1, usually address the scale imbalance.

Key Takeaways

  • Scaling reduces optimization problems caused by very different feature ranges.
  • Min-max uses the range and minimum; mean normalization uses the range and mean.
  • Standardization divides centered values by the training standard deviation.
  • Standardization preserves distribution shape and does not remove correlation.
  • Unpenalized least-squares predictions can stay the same while coefficients change.

4.2 Reuse the training transformation on new data

A trained regression model expects features in the coordinate system used during fitting. The scaling values are part of that fitted workflow. Learn them from training data, store them, and use them unchanged on validation, test, and future examples.

Keep test information out of fitting

Suppose training floor areas have mean 110 m² and standard deviation about 42.43 m². A new area of 200 m² becomes (200−110)/42.43≈2.12. Do not calculate a new mean from that example or refit the scaler on the test set. Either action changes the coordinate system received by fixed weights.

A new standardized value can lie beyond the training values. A new min-max value can exceed 1 or fall below 0. These values describe inputs outside the training range; they are valid outputs of the stored transformation.

Fitting scaling statistics on the combined training and test data is data leakage. Test observations then influence the model-building process, making the evaluation less representative of truly unseen data. Even a transformation that does not use targets can leak information about the test distribution.

Apply the fitted scaler
scaler = StandardScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)

Use fit or fit_transform on training inputs and transform on other inputs. Calling fit_transform(X_test) learns a second transformation. Feeding raw area 200 into a model trained on z-scores is worse: it is treated as a standardized value of 200, and the software may report no shape error.

A pipeline keeps these steps together:

model = make_pipeline(
    StandardScaler(),
    SGDRegressor(penalty=None, random_state=0)
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

fit learns the scaler and then trains the regressor on transformed inputs. predict applies the stored scaler before prediction. The same arrangement keeps fitting inside each training fold when validation procedures later use the pipeline.

Read scaled coefficients

After standardization, a coefficient describes the predicted change for a one-training-standard-deviation increase, holding other inputs fixed. Divide it by that feature’s standard deviation to recover the original-unit slope. For distance, 3.80/1.118≈3.4 minutes per kilometer.

Centering also changes the intercept. In a one-feature standardized model, the intercept is the prediction at the training mean input. To reconstruct the original model from y^=az+c and z=(x−μ)/σ, use slope a/σ and intercept c−aμ/σ.

Handle constant inputs and targets

A feature constant in all training rows has standard deviation zero and supplies no varying information. Remove it. StandardScaler avoids dividing by zero by using scale 1; with centering, the constant training column becomes zeros.

Linear regression does not require target scaling. If the target is transformed for numerical reasons, invert that transformation before reporting predictions and errors in original units. Direct dense least-squares solvers do not require scaling as an iterative optimizer does, although numerical conditioning and coefficient comparisons can still benefit from sensible units.

Key Takeaways

  • Learn scaling statistics from training data only.
  • Apply stored statistics to every later input.
  • A pipeline keeps preprocessing and prediction consistent.
  • Divide a standardized weight by the feature standard deviation to recover its original-unit slope.
  • Remove constant training features or handle their zero scale explicitly.
  • Undo any target scaling before reporting errors in original units.

4.3 Fit a curve by adding features

A straight line can miss a curved relationship even when its average error is small. Change the features to change the shapes the model can fit. The fitting machinery still works when the added columns are powers or products of the original inputs.

Build useful columns

Feature engineering creates inputs that express useful relationships. For a rectangular land plot, width times depth gives area in square meters. Positive inputs can also be transformed with logarithms or square roots when those shapes match the problem.

A degree-two polynomial model is

y^=w1x+w2x2+b.

It draws a curve against the original input but remains linear in the learned parameters. The column containing squared inputs is fixed before fitting; its coefficient enters as a simple multiplication. Degree three adds a column of cubes.

Diagnose and fit a missing curve

Consider inputs 0, 1, 2, 3, and 4 with targets 1, 2, 5, 10, and 17. These follow y=x2+1. The best straight line is y^=4x−1. Its residuals, target minus prediction, are 2, −1, −2, −1, and 2. Their squared sum is 14.

Plotting these residuals against the inputs reveals a U-shaped pattern: the line underpredicts at both ends and overpredicts in the middle. Add the squared-input column. Then w1=0, w2=1, and b=1 reproduce every target exactly. The feature transformation made that curve available to least squares.

Include products and manage scale

For two inputs, degree-two PolynomialFeatures produces 1,x1,x2,x12,x1x2,x22 by default. The product is an interaction: its contribution lets the effect of one input depend on the other. Two inputs at degree three produce 10 columns including the constant; 100 inputs at degree two produce 5,151. Feature counts can become large quickly.

Create the powers first and scale the resulting columns. If an input reaches 100, its square reaches 10,000 and its cube reaches 1,000,000. Leaving those scales together makes a useful gradient-descent rate hard to find. Use include_bias=False when the regressor already fits an intercept, avoiding a redundant constant column.

model = make_pipeline(
    PolynomialFeatures(degree=2, include_bias=False),
    StandardScaler(),
    LinearRegression()
)
Choose complexity with new examples

A higher-degree unpenalized least-squares model contains the lower-degree model as a special case. Its best training cost cannot increase. Training error therefore favors extra flexibility even when it captures noise. At distinct inputs, a polynomial of degree one less than the number of observations can interpolate every training point and still make poor predictions elsewhere.

Fit candidate degrees on training data, compare validation errors, and choose the degree with the best validation performance. Use the held-out test set for the final evaluation after that choice. A residual pattern can guide which feature to try, but a perfect training fit alone is not a reason to choose it. Outside the observed range, high powers can grow rapidly, making polynomial extrapolation especially unstable.

Key Takeaways

  • Polynomial regression is linear in its parameters even when its graph is curved.
  • Powers model curvature; products model interactions.
  • Generate polynomial columns before scaling them.
  • Adding polynomial terms cannot increase the optimal training error.
  • Use validation error to choose the degree and test data for final evaluation.
  • A flexible model can fit training points exactly and extrapolate poorly.
5

Solve, fit, and evaluate regression models

Least squares can be solved directly as well as by repeated gradient updates. The feature matrix determines whether the fitted parameters are unique and whether solving for them is computationally practical. Library estimators package these calculations with a consistent fit-and-predict interface. After fitting, error metrics, a mean baseline, and residual plots show how well the model predicts held-out data and where its remaining errors have structure.

5.1 Solve least squares directly

Gradient descent approaches the minimum through updates. Least squares also has a direct route: set every derivative to zero and solve the resulting linear equations. This finds the same minimum without selecting a learning rate.

Include the intercept in the system

Add a first column of ones to the design matrix and call it Xb. Put the bias first in 𝜽=(b,w1,…,wn). Predictions are then Xb𝜽, and the zero-gradient equations are

Xb⊤Xb𝜽=Xb⊤𝐲.

This is the normal equation. The matrix on the left has shape (n+1)×(n+1), one row and column per parameter. The right side has length n+1. Multiplying in the other order, XbXb⊤, gives an m×m matrix with a different role.

When the parameter matrix is invertible, the solution can be written

𝜽=(Xb⊤Xb)−1Xb⊤𝐲.

This expression explains the algebra. Numerical code should solve the system without explicitly forming the inverse.

Solve the delivery example

For distances 1, 2, 3, and 4 km, each row of Xb is a one followed by the distance. Summing products of columns gives

Xb⊤Xb=(4101030),Xb⊤𝐲=(60167).

The two equations are 4b+10w=60 and 10b+30w=167. Multiply the first by 2.5 and subtract it from the second: 5w=17. Thus w=3.4, then b=(60−34)/4=6.5.

The determinant is 4(30)−10(10)=20, so the inverse exists. Multiplying its numerator matrix by the right side gives entries 30(60)−10(167)=130 and −10(60)+4(167)=68. Dividing by 20 gives the same bias and weight.

Use the one-feature formula

For a nonconstant input, the slope also has the form

w=∑i(x(i)−xˉ)(y(i)−yˉ)∑i(x(i)−xˉ)2,b=yˉ−wxˉ.

Here the means are 2.5 km and 15 minutes, the numerator is 17, and the denominator is 5. The fitted line passes through (xˉ,yˉ) because its intercept satisfies that equation. The denominator becomes zero when all inputs are equal, so the unique-slope formula then fails.

Choose numerical code
Xb = np.column_stack([np.ones(len(X)), X])
theta = np.linalg.lstsq(Xb, y, rcond=None)[0]

lstsq solves the least-squares problem directly and also handles redundant columns. For a nonsingular normal-equation matrix, np.linalg.solve(Xb.T @ Xb, Xb.T @ y) solves the displayed system. Forming that matrix can worsen rounding problems when features are nearly dependent, so lstsq is usually the more reliable choice.

Leaving out the column of ones fits a model constrained through the origin. That is a different model, not a shortcut for estimating an intercept. The same normal-equation reasoning applies after adding polynomial or engineered feature columns because the predictions remain linear in the parameters.

Key Takeaways

  • The normal equation sets every least-squares derivative to zero.
  • Add a column of ones and put the bias first in the parameter vector.
  • The parameter system has one row and column per fitted parameter.
  • Solve numerically with lstsq or an appropriate system solver, without forming an inverse.

5.2 Choose a solver and handle redundant features

A direct solution and gradient descent optimize the same unpenalized squared-error objective. The practical choice depends on feature count, available memory, and whether the inputs provide independent information about the parameters.

Compare the work
MethodMain workSettings and data access
Normal-equation systemForming the matrix costs about mn2; solving it about n3No learning rate; all needed cross-products
Batch gradient descentEach update costs about mnRate, stopping rule, repeated full passes
SGD or mini-batchEach update processes one example or a small groupRate schedule, shuffling, streamed batches

A direct least-squares solver is often convenient with up to a few thousand features. With hundreds of thousands, building a square parameter matrix can be prohibitive. Gradient methods avoid that matrix and can process data in batches. Runtime also depends on the hardware and implementation.

Recognize exact redundancy

The matrix Xb⊤Xb is singular exactly when the columns of Xb are linearly dependent. Including the same distance in kilometers and meters creates this problem: one column is 1,000 times the other. A full set of one-hot category indicators plus an intercept is also dependent because the indicators add up to the ones column.

There must also be dependence when there are fewer examples than parameters, m<n+1. The intercept counts as a parameter. Enough rows are necessary for uniqueness, but not sufficient: duplicated columns remain dependent even in a huge dataset.

Redundancy leaves infinitely many minimizing parameter vectors. For equal duplicate columns, transferring weight between the columns leaves their combined contribution unchanged. The best training predictions are still well defined, but the data cannot identify the individual weights uniquely.

Recover a least-squares solution

Remove redundant inputs when their separate roles are unnecessary. Alternatively, use np.linalg.lstsq(Xb, y, rcond=None)[0] or np.linalg.pinv(Xb) @ y. They select the shortest Euclidean parameter vector in the chosen coordinates among tied least-squares fits. Adding a weight penalty is another remedy, with a changed objective.

For duplicated delivery distance, a solver can distribute the slope across columns and keep predictions 9.9, 13.3, 16.7, and 20.1 minutes. Another method can distribute it differently. Compare predictions and cost when checking equivalent fits with redundant inputs.

Distinguish near redundancy

Two sensors measuring almost the same quantity can create nearly dependent columns. A unique solution may exist, yet small data changes can produce large, opposing coefficient changes. Predictions within the observed region may stay similar while individual coefficients become hard to interpret. Scaling helps numerical units but does not remove the shared information.

A direct result is accurate up to numerical rounding, not a guarantee of stable interpretation. A converged iterative result should match it within a suitable tolerance when the optimum is unique. If they differ, inspect stopping accuracy and conditioning as well as possible code errors.

Key Takeaways

  • Direct methods become costly as the number of features grows.
  • Exact dependence among columns, including the intercept column, prevents a unique parameter vector.
  • Fewer examples than parameters guarantees dependence.
  • lstsq and the pseudoinverse can return a minimum-norm least-squares solution.
  • Near dependence can make individual weights unstable despite similar predictions.

5.3 Fit and predict with scikit-learn

A library estimator handles fitting and prediction through a small interface. You still choose the features, control preprocessing, and evaluate the result on data kept out of fitting. Keep the same objective and transformed data when comparing a library fit with your own implementation.

Fit a dense linear model
import numpy as np
from sklearn.linear_model import LinearRegression

X_train = np.array([[1.0], [2.0], [3.0], [4.0]])
y_train = np.array([10.0, 14.0, 15.0, 21.0])
model = LinearRegression()
model.fit(X_train, y_train)
y_new = model.predict(np.array([[2.5]]))

Inputs are two-dimensional: four rows and one feature column. For a one-dimensional vector x, use x.reshape(-1, 1) to make that column. Keep a one-target response vector one-dimensional. Reshaping to (1, m) instead would describe one example with many features.

After fitting, model.coef_ is about [3.4] and model.intercept_ is about 6.5. The new prediction is 15 minutes. coef_ follows the input-column order; inspect that order before attaching a meaning to each number.

For ordinary dense inputs, LinearRegression uses a direct least-squares solver. It needs no gradient-descent learning rate or training-iteration setting and can handle redundant columns. Sparse inputs use a different solver path, so the direct-solver description applies to the dense examples here. Scaling can help numerical conditioning, but is not a required training step for this dense direct fit.

Fit with stochastic updates
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDRegressor

sgd_model = make_pipeline(
    StandardScaler(),
    SGDRegressor(penalty=None, max_iter=10000,
                 tol=1e-6, eta0=0.01, random_state=0)
)
sgd_model.fit(X_train, y_train)

max_iter limits epochs, tol controls stopping, and eta0 controls the starting rate for the chosen schedule. random_state makes shuffled runs reproducible. The default estimator includes an L2 penalty; penalty=None aligns this model with plain least squares. These settings still need a convergence check on the data being used.

Put polynomial transformations in a pipeline
from sklearn.preprocessing import PolynomialFeatures

poly_model = make_pipeline(
    PolynomialFeatures(degree=3, include_bias=False),
    StandardScaler(),
    LinearRegression()
)
poly_model.fit(X_train, y_train)

Fitting creates polynomial columns, learns their scaling from training data, and fits the coefficients. Prediction repeats the stored transformation. Choose degree with validation data before final testing. Keep a fitted model by calling predict on test inputs; fit(X_test, y_test) replaces its trained state.

Compare implementations fairly

Fit NumPy and library models on the same training rows, feature columns, scaling, and objective. With a unique converged fit, their coefficients should agree within tolerance in the same coordinate system. With redundant inputs, compare cost and training predictions. A successful final comparison checks the optimum reached. Use finite differences at a nonoptimal point to check the gradient formula itself: a missing factor of the example count can be hidden by a smaller learning rate.

Key Takeaways

  • Use two-dimensional features and a one-dimensional single-target vector.
  • fit trains; predict applies the trained model.
  • coef_ and intercept_ store fitted weights and bias.
  • Use a scaler and penalty=None for an SGD comparison with plain least squares.
  • Pipelines apply the same fitted transformations during prediction.
  • Compare fits in the same feature coordinates and with the same objective.

5.4 Evaluate predictions and read the remaining errors

A model is useful when it predicts new examples well. Evaluate the finished workflow on held-out data, compare it with a simple baseline, and inspect the errors. One good score can hide a systematic pattern that a residual plot makes visible.

Report the size of errors

For m evaluated examples,

MSE=1m∑i(y^(i)−y(i))2,RMSE=MSE.

The delivery model’s training squared errors sum to 4.2, so MSE is 1.05 min² and RMSE is about 1.02 minutes. These describe its training fit; use held-out targets and predictions to report test error. RMSE is sensitive to large misses because it comes from squared errors.

Compare with variation around the mean

For nonconstant evaluated targets, the coefficient of determination is

R2=1−SSresSStot,SStot=∑i(y(i)−yˉ)2.

The residual sum of squares is SSres=∑i(y(i)−y^(i))2. For the deliveries, the target mean is 15 minutes and the total squared variation is 25+1+0+36=62. Thus R2=1−4.2/62≈0.932: the fitted predictions account for about 93% of this variation around the mean.

A perfect fit has R2=1. Predicting the evaluated targets’ mean gives zero. Worse predictions can give a negative value; predicting 20 minutes for every delivery gives about −1.61. This score is not a percentage of individually correct predictions. For constant evaluated targets the displayed ratio has a zero denominator and needs special handling.

In scikit-learn, mean_squared_error(y_test, y_pred) computes MSE, and r2_score(y_test, y_pred) or model.score(X_test, y_test) computes R² for a regression estimator.

Evaluate against a usable baseline

Fit a DummyRegressor(strategy="mean") on the training targets. It predicts their mean for every test row. Compare its test RMSE with the trained model’s test RMSE on the same rows. The model needs a clear error improvement to justify its added complexity.

The mean used by this fitted baseline is the training mean. The mean in the R² denominator belongs to the evaluated targets. They can differ, so beating a training-mean baseline and having positive test R² are related checks, not identical statements.

Inspect residuals and weights

Plot residuals, target minus prediction, against the prediction or an input. A curve suggests a missing nonlinear feature. A fan shape shows that error spread grows with the predicted target. A large isolated residual deserves a data check; an unusual point can be real as well as erroneous.

A straight line fitted to y=x2+1 at inputs 0 through 4 has R² about 0.92, yet its residuals form a clear curve. High R² alone cannot establish that the model captures the relationship well. Adding input columns cannot lower optimal training R² in unpenalized least squares, even when those columns are noise.

Read each weight as a change in prediction per feature unit, holding other features fixed. Its value depends on the included features and can be unstable when they are strongly correlated. It summarizes a fitted association; causal claims require a design and evidence that separate other explanations.

Key Takeaways

  • Evaluate the finished model on held-out examples.
  • RMSE reports error magnitude in target units.
  • R² compares squared error with variation around the evaluated target mean and can be negative.
  • Compare test RMSE with a baseline trained on the training targets.
  • Residual patterns reveal curvature, changing spread, and unusual points.
  • High training R² and large coefficients are insufficient evidence of a useful or causal model.

Linear Regression examples

5 Walkthroughs

1

From a delivery record to a fitted line

10 steps
Build a numeric prediction, read its parameters, and compare lines using squared errors.
  1. 1
    IntroductionTurn observations into predictions

    A delivery record pairs a distance with an observed time. A regression model turns that distance into a predicted time. You will read the model’s weight and bias, calculate its misses, and compare two lines. Keep the observed time separate from the prediction: their difference supplies the evidence used to train the model.

  2. 2
    ExplanationName one training example

    The four deliveries are (1 km, 10 min), (2 km, 14 min), (3 km, 15 min), and (4 km, 21 min). Distance is the feature; time is the target. There are m=4 examples. The third pair is (x(3),y(3))=(3,15). The superscript in parentheses selects the third row; it does not square or cube the distance.

  3. 3
    ExampleMake a prediction

    Use y^=3.4x+6.5. At 2.5 km, the distance contribution is 3.4(2.5)=8.5 minutes. Adding the bias gives 8.5+6.5=15 minutes. The weight is 3.4 minutes per kilometer. The bias is the predicted time at zero distance, which lies beyond the observed range and needs process knowledge for a practical interpretation.

  4. 4
    ChallengeRead a different model

    A cooling model predicts temperature in °C as y^=−2x+24, where x is elapsed time in minutes. How does the prediction change over one extra minute?

    ---reveal---

    It decreases by 2 °C. The slope is −2 °C per minute; the intercept 24 °C is the prediction at time zero. The weight describes a change in the prediction, not the value of every observed temperature.

  5. 5
    ExampleCalculate each miss

    Try the delivery line y^=3x+7. Predictions at distances 1, 2, 3, and 4 km are 10, 13, 16, and 19 minutes. Subtract targets 10, 14, 15, and 21 to get errors 0, −1, 1, and −2. Squaring gives 0, 1, 1, and 4. Their sum is 6 min²; adding the unsquared errors would let misses on opposite sides cancel.

  6. 6
    ExampleTurn the misses into cost

    The cost divides the squared-error sum by twice the example count: J=6/(2⋅4)=0.75. MSE divides by the count without the extra half, giving 1.5 min². For the fitted line with weight 3.4 and bias 6.5, the squared-error sum is 4.2, so cost is 0.525. The smaller cost identifies a better fit on these training deliveries.

  7. 7
    AnalogyPicture the bowl

    Think of each parameter pair as a position on a bowl, with cost as its height. Moving the weight and bias moves you around this surface; it does not move a delivery along the distance axis. A contour joins positions at the same height. The squared-error bowl is convex, so a local bottom is also a global bottom. Nonconstant one-feature inputs give a unique bottom.

  8. 8
    ChallengeCompare errors in target units

    Three predictions have errors −3, 0, and 3 kg. What are J and RMSE?

    ---reveal---

    The squared sum is 9+0+9=18 kg². Thus J=18/6=3 kg² and RMSE=18/3=6≈2.45 kg. Cost is half the MSE; taking the square root of cost instead would miss that factor of two.

  9. 9
    ChallengeCheck where the line is being used

    A model has low training cost on distances from 2 to 7 km. Does that establish accurate predictions at 30 km, and why?

    ---reveal---

    No. Thirty kilometers lies outside the observed range, so the output is an extrapolation. A small cost measures the misses on the evaluated examples; it does not check an unobserved range. Longer journeys may follow a different relationship even when the line fits nearby journeys well.

  10. 10
    RecapUse the model and its evidence together

    For a new regression task, identify the feature and numeric target before reading the parameters. Then compare squared misses on a common set of observations and report errors in useful units. Keep the input range beside the fitted result: it tells you where the examples actually tested the relationship.

2

Take and inspect gradient steps

12 steps
Calculate a batch update, diagnose its learning curve, and choose how many examples each update uses.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLearn through repeated adjustments
  2. 2
    ExplanationRead the two derivatives
  3. 3
    ExampleFind the first gradients
  4. 4
    ExampleApply the stored changes
  5. 5
    ChallengeChoose the update direction
  6. 6
    ExplanationCompare cost curves
  7. 7
    ChallengeDistinguish a flat curve from a good fit
  8. 8
    ExplanationCount passes and updates
  9. 9
    Key InsightExpect noise from subsets
  10. 10
    ChallengeCalculate a mini-batch workload
  11. 11
    ChallengeChoose the right progress check
  12. 12
    RecapMatch monitoring to the update method
3

Build and check a vectorized trainer

13 steps
Follow matrix shapes from several features to a complete gradient update and an independent check.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionLet rows and columns do the repeated work
  2. 2
    ExampleGive each input a role
  3. 3
    ChallengeKeep units beside coefficients
  4. 4
    ExplanationMake one prediction per row
  5. 5
    ExampleCompute the three-row cost
  6. 6
    ChallengeCatch an accepted but wrong subtraction
  7. 7
    ExplanationTranspose to collect feature effects
  8. 8
    ExampleWork a zero-start gradient
  9. 9
    ExampleApply and record the update
  10. 10
    ChallengeRepair a transposed product
  11. 11
    TipCheck a derivative locally
  12. 12
    ChallengeInterpret matching fits correctly
  13. 13
    RecapUse two complementary checks
4

Transform features without changing their meaning

14 steps
Scale training inputs consistently, then add and validate polynomial feature columns.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChange coordinates and available shapes
  2. 2
    AnalogyRecognize a narrow optimization valley
  3. 3
    ExampleCompare centering choices
  4. 4
    ExampleMeasure distance in standard deviations
  5. 5
    ChallengeCalculate a standardized value
  6. 6
    ExampleTransform a genuinely new row
  7. 7
    TipKeep the workflow together
  8. 8
    ChallengeDetect a preprocessing leak
  9. 9
    ExampleLet a squared input explain curvature
  10. 10
    ExplanationBuild the final feature columns first
  11. 11
    ChallengeChoose among candidate curves
  12. 12
    Key InsightInspect the price of flexibility
  13. 13
    ChallengeRecover an original-unit effect
  14. 14
    RecapValidate the complete transformation
5

Solve a fit and judge its predictions

16 steps
Connect direct least squares with library estimators, redundant inputs, and held-out evaluation.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionInspect both the solution and its usefulness
  2. 2
    ExplanationInclude the bias as a column
  3. 3
    ExampleSolve the two delivery equations
  4. 4
    ChallengeCheck the mean point
  5. 5
    ConnectionChoose a computational route
  6. 6
    ExampleUnderstand a redundant measurement
  7. 7
    TipHandle the missing inverse
  8. 8
    ChallengeCount the intercept parameter
  9. 9
    ExplanationFit the library model once
  10. 10
    ChallengeAlign a stochastic comparison
  11. 11
    ExampleCalculate an error in useful units
  12. 12
    ExplanationRead R² against its reference
  13. 13
    ChallengeEvaluate a held-out result
  14. 14
    Key InsightLook beyond a high score
  15. 15
    ChallengeDecide what the evidence supports
  16. 16
    RecapKeep fitting and evaluation connected

Linear Regression practice questions

40 Practice Questions in 4 sets

Set 1: Models, errors, and first updates10 Practice Questions

Question 1 of 10

A pump model predicts processing time from volume in liters. Its fitted weight is 0.8 min/L. How does the prediction change when volume increases by 1 L?
  1. It increases by 0.8 L.
  2. It increases by 0.8 min.
  3. It increases by 1.8 min.
  4. It increases by 1 min.
Show answerHide answer
Answer: B
The weight gives the change in the predicted target per unit of the input. Increasing volume by 1 L therefore adds 0.8 minutes to the prediction. Reporting 0.8 L confuses the feature unit with the target unit; the model predicts time, so its change is measured in minutes.

Question 2 of 10

For two samples, a model predicts masses of 8 and 11 kg while the observed masses are 6 and 12 kg. What is the cost J with the factor 1/(2m)?
  1. 2.5 kg²
  2. 0.25 kg²
  3. 5 kg²
  4. 1.25 kg²
Show answerHide answer
Answer: D
The errors are 2 and −1 kg, whose squares sum to 5 kg². There are two examples, so J=5/(2⋅2)=1.25 kg². Dividing only by the example count gives 2.5 kg², which is the MSE and is twice this cost.

Question 3 of 10

At a current weight of 2 and bias of 1, the cost derivatives are gw=−6 and gb=3. With learning rate 0.05, what are the updated parameters?
  1. w=2.30, b=0.85
  2. w=1.70, b=1.15
  3. w=2.30, b=1.15
  4. w=1.70, b=0.85
Show answerHide answer
Answer: A
Subtract 0.05 times each derivative from its current parameter: w=2−0.05(−6)=2.30 and b=1−0.05(3)=0.85. The negative weight derivative increases the weight. Adding both derivatives would move the weight to 1.70 and the bias to 1.15, reversing the downhill rule.

Question 4 of 10

A full-batch training run has costs 9, 14, 23, and 40 after successive updates. What is a useful first adjustment?
  1. Increase the learning rate.
  2. Reduce the batch to one row.
  3. Decrease the learning rate.
  4. Stop at the latest parameters.
Show answerHide answer
Answer: C
A steadily increasing full-batch cost suggests an oversized learning rate or an update error. Lowering the rate is a useful first check because it reduces overshooting. Increasing it can make that instability worse; if a much smaller rate still fails, inspect the gradient and array shapes.

Question 5 of 10

A dataset has 2,400 examples, each used once per epoch. With mini-batches of 80, how many parameter updates occur in three epochs?
  1. 30 updates
  2. 90 updates
  3. 240 updates
  4. 7,200 updates
Show answerHide answer
Answer: B
Each epoch has 2,400/80 = 30 batches, and each batch produces one update. Three epochs therefore produce 90 updates. Counting 30 stops after one epoch; counting one update per example would instead describe stochastic training, not the stated mini-batches.

Question 6 of 10

A machine predicts energy in kWh as y^=1.5x1+0.4x2+2, where inputs are operating hours and load in kg. What is the prediction for 4 hours and a 5 kg load?
  1. 10 kWh
  2. 8 kWh
  3. 9.5 kWh
  4. 12 kWh
Show answerHide answer
Answer: A
The two feature contributions are 1.5(4)=6 and 0.4(5)=2 kWh. Adding the 2 kWh bias gives 10 kWh. The value 8 kWh omits the bias, which contributes once to every prediction in this model.

Question 7 of 10

X has shape (60, 4) and w has shape (4,). What is the shape of X @ w + b when b is a scalar?
  1. (4,)
  2. (60, 4)
  3. (4, 60)
  4. (60,)
Show answerHide answer
Answer: D
The matrix product combines four feature contributions within each of the 60 rows. It therefore returns a length-60 prediction vector, and adding a scalar bias preserves that shape. An array of shape (60, 4) would retain a separate weighted entry for every feature instead of one prediction per row.

Question 8 of 10

A programmer calculates grad_w, updates w, then calculates grad_b using the updated w. What change makes the step a simultaneous gradient update?
  1. Recalculate the target after each update.
  2. Calculate both gradients before assigning parameters.
  3. Update the bias first and the weight second.
  4. Divide the new bias gradient by two.
Show answerHide answer
Answer: B
A simultaneous step uses one shared set of current predictions to calculate both derivatives. Compute the two gradients before changing either parameter, then apply both updates. Reversing the assignment order still mixes old and new parameter states if the second derivative is calculated after the first assignment.

Question 9 of 10

Two models have prediction errors [−4, 4] and [−1, 1] kg on the same observations. How does squared-error cost compare?
  1. Both have zero cost.
  2. The first has four times the cost.
  3. The first has sixteen times the cost.
  4. Both have the same nonzero cost.
Show answerHide answer
Answer: C
The squared-error sums are 32 and 2 kg². Since both costs divide by the same number, the first cost is sixteen times the second. Adding raw errors would give zero for both models, hiding the much larger misses in the first model.

Question 10 of 10

A batch linear model starts with weight and bias zero. The two training pairs are (0, 1) and (2, 5). With learning rate 0.1, what cost J results after one update?
  1. 3.545
  2. 7.090
  3. 4.250
  4. 10.345
Show answerHide answer
Answer: A
Initial errors are −1 and −5, giving weight gradient −5 and bias gradient −3. The updated weight 0.5 and bias 0.3 give errors −0.7 and −3.7, so J=(0.49+13.69)/4=3.545. A cost of 4.250 omits the bias update; 7.090 reports MSE instead of J.
Set 2: Scaling, curves, and direct fitting10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A training feature has minimum 20 and maximum 100. What is the min-max transformed value of 60?
  1. 0.75
  2. 0.6
  3. 0.5
  4. 0.4
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A model was trained with feature mean 50 kg and standard deviation 10 kg. A new observation is 75 kg. What transformed input should it receive?
  1. 2.5
  2. 7.5
  3. 0
  4. 25
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A straight-line model has positive residuals at both ends of an input range and negative residuals in the middle. What feature addition is a useful first candidate?
  1. A second copy of x.
  2. A column of ones beside the intercept.
  3. A rescaled copy of x.
  4. A new column containing x2.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For one feature, the centered-product sum is 24, the centered squared-input sum is 12, and the input and target means are 4 and 13. What least-squares parameters result?
  1. w=0.5, b=11
  2. w=2, b=5
  3. w=2, b=13
  4. w=3, b=1
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A feature matrix contains a distance in meters and the same distance in centimeters, alongside a fitted intercept. Why is the normal-equation matrix singular?
  1. The feature values require standardization.
  2. One distance column is a multiple of the other.
  3. The target must also be expressed in centimeters.
  4. The number of rows must equal the column count.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An array x stores 25 values of one input feature. What shape should it have for LinearRegression.fit?
  1. (1, 25)
  2. (25,)
  3. (25, 1)
  4. (25, 25)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

On held-out targets with total squared variation 80 kg², a model has squared-error sum 100 kg² across five observations. What are its RMSE and R²?
  1. About 4.47 kg and −0.25
  2. About 4.47 kg and 0.25
  3. About 2.00 kg and −0.25
  4. About 10.00 kg and −0.25
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two inputs are expanded to all polynomial features through degree two, without a bias column. How many feature columns result?
  1. 3
  2. 4
  3. 6
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A standardized one-feature model is prediction = 6*z + 9. The training mean is 8 m and standard deviation is 2 m. What original-input model gives the same predictions?
  1. y^=3x+9
  2. y^=12x−39
  3. y^=3x−15
  4. y^=3x−24
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A model has an intercept and two identical input columns. The fitted weights are 1 and 3 with bias 2. Another solver returns different weights with identical training predictions. What weight pair is consistent with the same combined effect and minimum Euclidean norm?
  1. (1, 1)
  2. (2, 2)
  3. (0, 4)
  4. (−1, 5)
Show answerHide answer

Save this lesson to see this answer.

Set 3: Debugging training and comparing models10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Predictions have shape (7,), but targets have shape (7, 1). What does predictions - targets produce?
  1. An incorrect array of shape (7, 7).
  2. A correct error vector of shape (7,).
  3. An incorrect array of shape (1, 7).
  4. A shape exception before subtraction.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

For X=(1231) and current errors (−2,4), what are the weight and bias gradients for cost J?
  1. gw=(10,0), gb=2
  2. gw=(3,−1), gb=1
  3. gw=(5,0), gb=1
  4. gw=(−5,0), gb=−1
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A shuffled SGD run occasionally increases full training cost after a single example update, while epoch-level costs trend down. How should this be interpreted?
  1. The learning rate must be zero.
  2. Subset gradients can give this expected fluctuation.
  3. The error sign must have been reversed.
  4. The model must already be overfitting.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

After fitting a regression pipeline on training data, what call evaluates its existing predictions on test inputs?
  1. model.fit(X_test, y_test)
  2. model.fit_transform(X_test)
  3. model.fit(X_test, y_train)
  4. model.predict(X_test)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A custom batch optimizer and a direct solver reach the same unique coefficients. Away from the minimum, each custom gradient is consistently twelve times the finite-difference slope on twelve training rows. What diagnosis fits both findings?
  1. The custom gradient likely omits division by the row count.
  2. The direct solver likely uses an extra intercept column.
  3. The custom gradient likely uses the residual sign backward.
  4. The finite-difference test likely checks a different minimum.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A model’s test targets have mean 30 minutes and total squared variation 40 min². Its squared-error sum is 45 min², and a training-mean baseline has test squared-error sum 65 min². How does the model compare?
  1. It has positive R² and beats the fitted baseline.
  2. It has negative R² and loses to the fitted baseline.
  3. It has positive R² and loses to the fitted baseline.
  4. It has negative R² and beats the fitted baseline.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Degrees 1, 2, and 5 have training RMSE values 4, 2, and 0.2, and validation RMSE values 4.5, 2.7, and 6.1. What is the best next choice before final testing?
  1. Choose degree 5 because its training RMSE is lowest.
  2. Choose degree 1 because it has the fewest parameters.
  3. Choose degree 2 because its validation RMSE is lowest.
  4. Choose degree 5 and fit it on the test targets.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A design matrix has 14 examples and 3 feature columns. With an intercept included, what is the shape of the normal-equation parameter matrix?
  1. (14, 14)
  2. (4, 4)
  3. (3, 3)
  4. (14, 4)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two nearly identical sensors yield weights 80 and −77. After a small data correction, weights become 105 and −102 while in-range predictions barely change. What is the most useful interpretation?
  1. Both sensor effects are reliably large and opposite.
  2. The unchanged predictions establish independent inputs.
  3. The correction eliminated the need for scaling.
  4. Near dependence makes individual weights unstable.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A water-use model was trained on households with 1–6 occupants. It predicts use for a building with 40 occupants. How should that prediction be described?
  1. An extrapolation requiring evidence at that scale.
  2. An interpolation with measured prediction error.
  3. A causal effect of increasing household occupancy.
  4. A direct observation from the training dataset.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Decisions across a regression workflow10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A strongly right-skewed feature is standardized using its training mean and standard deviation. What happens to its shape?
  1. It becomes symmetric with mean one.
  2. It becomes normally distributed around zero.
  3. Its right tail disappears after rescaling.
  4. It stays right-skewed in the new coordinates.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A temperature model includes both altitude and distance from the coast. What does its altitude weight describe?
  1. The effect of altitude with coast distance changing freely.
  2. The predicted change per altitude unit at fixed coast distance.
  3. The causal change produced by changing a place’s altitude.
  4. The share of target variance caused by altitude alone.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Eight training rows include distance in meters, the same distance in kilometers, and exhaustive weekday/weekend indicators. Distance varies within each day category, and the model fits an intercept. How many separate column dependencies are present, and can scaling remove them?
  1. One; scaling leaves it redundant.
  2. Two; scaling removes both relations.
  3. Two; scaling leaves them redundant.
  4. One; scaling removes that relation.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A pipeline correctly scales training data. During deployment a developer pre-scales a new row with the stored scaler and then passes it to the full pipeline’s predict. What should change?
  1. Pass the raw row to the full pipeline.
  2. Refit the pipeline on the scaled row.
  3. Pass raw training data to the final regressor only.
  4. Refit the scaler separately for every new row.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Held-out targets are 2, 4, and 8 kg. Model P predicts 3, 3, and 8 kg; model Q predicts 2, 6, and 6 kg. Which model has lower RMSE, and what are its RMSE and R² to three significant figures?
  1. Q: RMSE 1.63 kg; R² 0.893.
  2. P: RMSE 0.816 kg; R² 0.571.
  3. P: RMSE 0.816 kg; R² 0.893.
  4. Q: RMSE 2.67 kg; R² 0.571.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A plain least-squares comparison uses LinearRegression and a scaled SGDRegressor. What SGD setting removes a default difference in their objectives?
  1. alpha=0.1
  2. penalty=None
  3. shuffle=False
  4. eta0=0.1
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A two-feature model has X=(1002), targets (2, 6), weights (1, 1), bias 0, and rate 0.1. What parameters result from one batch update?
  1. 𝐰=(1.05,1.40), b=0.25
  2. 𝐰=(1.10,1.80), b=0.50
  3. 𝐰=(0.95,0.60), b=−0.25
  4. 𝐰=(1.05,1.20), b=0.25
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A NumPy fit gives the raw-input model y^=2x+7. An equivalent library model uses z=(x−5)/3. What slope and intercept should that model have, and what should it predict at raw input x=8?
  1. Slope 2; intercept 7; prediction 23.
  2. Slope 6; intercept 7; prediction 13.
  3. Slope 2; intercept 17; prediction 19.
  4. Slope 6; intercept 17; prediction 23.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A new observation has a prediction error of 8 minutes. How many observations with error 2 minutes contribute the same total squared error?
  1. 4 observations
  2. 16 observations
  3. 8 observations
  4. 32 observations
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A pipeline applies PolynomialFeatures(degree=2, include_bias=False) to input columns x1 and x2, with no scaler. Its fitted regressor has coefficients [1, 2, 0.5, -1, 1] and intercept 4. What does it predict at x1=2 and x2=3?
  1. 23
  2. 13
  3. 17
  4. 29
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

69 Key Terms, each with its definition

A

Augmented design matrix
An augmented design matrix adds a column of ones to the feature matrix so its parameter vector can include a fitted intercept.
“The augmented matrix for one distance feature has two columns: ones first and distances second.”

B

Baseline
A baseline is a simple reference predictor used to judge whether a more complex model gives a useful improvement on new observations.
“A mean baseline learns the training-target mean and predicts that fixed number for each test row.”
Batch gradient descent
Batch gradient descent calculates each parameter update using the gradient over every example in the training dataset.
“One batch update on a million-row dataset must process all million rows before the parameters change.”
Broadcasting
Broadcasting lets compatible NumPy arrays of different shapes participate in an operation by logically expanding singleton dimensions.
“A scalar bias broadcasts correctly, but a target column can expand against a prediction vector incorrectly.”

C

Closed-form solution
A closed-form solution expresses fitted parameters directly through a finite mathematical expression instead of repeated training updates.
“The one-feature slope can be calculated from centered products and squared input deviations.”
Coefficient of determination
The coefficient of determination, R², compares prediction squared error with target variation around the evaluated mean; it can be negative.
“A negative test R² means the fit misses more than a constant prediction of the test targets’ mean.”
Constant feature
A constant feature has the same value in every training row, supplies no varying information, and has zero training standard deviation.
“A centered scaler turns a constant training column into zeros while avoiding division by its zero deviation.”
Contour
A contour is a curve joining parameter combinations with the same cost, used to show the shape of an optimization surface.
“Long, narrow cost contours help explain why differently scaled features can make training zigzag.”
Convergence
Convergence is the approach of an iterative method toward a stable solution, judged using its progress and a suitable stopping rule.
“A tiny cost change suggests convergence only after checking that an extremely small rate is not hiding slow progress.”
Convexity
Convexity is a property of a cost surface for which every local minimum is global, so there are no worse isolated local minima.
“Linear regression’s convex squared-error bowl allows suitable gradient steps to approach a global minimum.”
Cost function
A cost function assigns a number to a parameter choice by combining the model’s prediction errors across the training data.
“The squared-error cost selects the line with the smallest sum of squared misses on the training rows.”

D

Data leakage
Data leakage occurs when information unavailable during legitimate training influences fitting or choices used to assess new predictions.
“Learning scaling statistics from test rows leaks their distribution into a workflow meant to treat them as unseen.”
Design matrix
A design matrix is a two-dimensional array whose rows are examples and whose columns hold the feature values used by a model.
“A table of 80 deliveries with distance and stop count gives a design matrix with shape (80, 2).”
Divergence
Divergence is the movement of training parameters away from a solution, often seen as costs that grow under oversized updates.
“Costs that rise from 8 to 20 to 70 suggest divergence instead of a useful approach to the minimum.”

E

Elementwise multiplication
Elementwise multiplication multiplies corresponding array entries, using compatible broadcasting, without adding feature contributions across a row.
“Multiplying a feature matrix elementwise by its weight vector still leaves one entry per feature.”
Epoch
An epoch is one full pass through the training examples, containing a number of parameter updates determined by the batch size.
“Three epochs visit each training observation three times when every pass uses each row once.”
Estimator
An estimator is an object that learns a model or transformation from data through a fitting interface such as scikit-learn’s fit method.
“The regression estimator stores fitted coefficients that can later be applied to unseen input rows.”

F

Feature
A feature is an input measurement or encoded attribute that a model uses to calculate a prediction for an example.
“Distance in kilometers is one feature used to predict how long a delivery will take.”
Feature engineering
Feature engineering creates useful model inputs from existing measurements, using transformations that reflect the prediction problem.
“Multiplying a plot’s width by its depth adds area as an engineered feature measured in square meters.”
Feature scaling
Feature scaling shifts or rescales input columns to comparable numerical ranges, reducing optimization problems caused by uneven units.
“Scaling an area column and a count column can let gradient descent use a faster stable learning rate.”
Finite difference
A finite difference estimates a derivative from nearby function values while holding the function’s other inputs unchanged.
“Comparing costs at a weight just above and below its current value checks the coded weight derivative.”
Fitting
Fitting is the process of learning model parameters or transformation statistics from the supplied training observations.
“Fitting a complete pipeline learns scaling statistics before learning the regressor’s coefficients.”

G

Gradient
A gradient is the vector of partial derivatives of a function, giving its local uphill direction in parameter space.
“The optimizer moves opposite to the gradient when it updates all the regression parameters.”
Gradient descent
Gradient descent is an iterative training method that subtracts a positive learning rate times the cost gradient from the parameters.
“A negative weight derivative makes the next gradient-descent step increase that weight.”

H

Hyperparameter
A hyperparameter is a setting chosen to control model construction or training, such as a polynomial degree or learning rate.
“The learner tries several learning-rate hyperparameters before selecting a stable training run.”

I

Interaction
An interaction is a feature contribution that makes the predicted effect of one input depend on the value of another input.
“A width-times-depth term changes the effect of increasing width according to the plot’s depth.”
Intercept
An intercept is the constant part of a linear model, giving its prediction when all feature values are zero; it is also called the bias.
“After centering distance, the intercept describes the predicted time at the training mean distance.”

L

Learning curve
A learning curve for optimization plots training cost against iterations, revealing the speed and stability of parameter updates.
“The batch learning curve falls rapidly and then flattens as the gradient becomes small.”
Learning rate
A learning rate is a positive multiplier that turns a cost gradient into the step used to change model parameters.
“Raising the learning rate lowers cost faster until overshooting makes the updates unstable.”
Learning schedule
A learning schedule changes the learning rate during training, often making later stochastic updates smaller than early updates.
“An inverse-scaling schedule reduces the rate as the update count increases near the minimum.”
Linear dependence
Linear dependence means that at least one column can be expressed as a combination of other columns, leaving redundant information.
“All category indicators sum to the ones column, creating linear dependence when the model has an intercept.”

M

Matrix inverse
A matrix inverse reverses a nonsingular square matrix product; a square matrix with dependent columns has no inverse.
“The inverse expression describes the normal-equation solution, although code should solve without forming it.”
Matrix product
A matrix product combines matching row and column entries by multiplication and addition, with dimensions determining the output shape.
“Multiplying an m-by-n matrix by a length-n weight vector gives one weighted sum for each of m rows.”
Mean normalization
Mean normalization subtracts a training feature’s mean and divides by its range, centering the transformed training values on zero.
“For areas with mean 110 m² and range 120 m², area 170 m² becomes 0.5 after mean normalization.”
Mean squared error
Mean squared error is the average squared difference between predictions and targets, measured in squared target units.
“An MSE of 9 min² corresponds to an RMSE of 3 minutes on the same evaluated examples.”
Min-max scaling
Min-max scaling subtracts a training feature’s minimum and divides by its range, mapping nonconstant training values into zero to one.
“A future value above the training maximum can legitimately have a min-max scaled value greater than one.”
Mini-batch gradient descent
Mini-batch gradient descent updates parameters using a small group of examples, combining frequent updates with vectorized computation.
“Processing 3,200 examples in groups of 64 gives 50 mini-batch updates during one complete pass.”
Minimum-norm solution
A minimum-norm solution has the smallest Euclidean parameter-vector length among solutions that achieve the same least-squares minimum.
“Equal duplicate columns share their combined weight equally in the minimum-norm parameter vector.”
Multicollinearity
Multicollinearity is strong linear dependence or near dependence among input columns, which can make individual coefficients nonunique or unstable.
“Nearly identical sensor readings can give large opposing weights that change sharply after small data corrections.”
Multiple linear regression
Multiple linear regression predicts one numeric target as a weighted sum of several input features plus a single intercept.
“Distance and stop count both contribute to the predicted delivery time in a multiple linear regression.”

N

Normal equation
The normal equation is the linear system obtained by setting the least-squares gradient to zero, with one equation per fitted parameter.
“A ones column includes the intercept in the same normal-equation system as the feature weights.”
Numerical tolerance
A numerical tolerance is a chosen allowance for small discrepancies caused by rounding, solver precision, or an iterative stopping rule.
“Two unique least-squares fits should agree within tolerance when trained in the same coordinates.”

O

One-hot encoding
One-hot encoding represents a category with numeric indicator columns, marking which category applies to each example.
“Vehicle-type indicators need a redundancy check when every category and an intercept are included.”
Outlier
An outlier is an observation unusually far from the main pattern; its large squared error can strongly influence a least-squares fit.
“An unusually long recorded delivery time deserves inspection before its large error pulls the fitted line.”
Overfitting
Overfitting occurs when a model captures training-specific patterns that do not predict new examples well, often through excess flexibility.
“A high-degree polynomial with tiny training error and much larger validation error shows signs of overfitting.”

P

Parameter
A parameter is a value learned during fitting that determines how the model converts its input features into predictions.
“Training a one-feature linear model learns a slope and an intercept as its two parameters.”
Partial derivative
A partial derivative is the slope of a function in one parameter direction while the other parameters are held fixed.
“The bias partial derivative averages prediction errors without multiplying them by feature values.”
Pipeline
A pipeline chains transformations and an estimator so fitting learns each stage in order and prediction reuses their fitted state.
“A polynomial pipeline creates powers, scales the resulting columns, and then applies the regressor.”
Polynomial degree
A polynomial degree is the highest total power included in a polynomial feature expansion, controlling its available flexibility.
“Degree two with two inputs permits squares and their product, while degree three adds cubic terms.”
Polynomial regression
Polynomial regression fits a linear model to powers and products of inputs, producing curved input-output relationships with linear coefficients.
“Adding a squared-time feature lets an ordinary least-squares model fit a quadratic temperature curve.”
Prediction
Prediction applies a fitted model and its stored preprocessing to inputs to calculate target estimates without learning from their targets.
“Predicting on test inputs preserves the model fitted on training data instead of replacing its parameters.”
Prediction error
A prediction error is the model prediction minus the observed target for one example, retaining the direction of the miss.
“A predicted mass of 9 kg against a target of 7 kg produces a positive prediction error of 2 kg.”

R

Regression
Regression is supervised learning that predicts a numeric quantity from input features using examples with observed target values.
“A regression model predicts the mass of a harvested crop from measurements of its growing conditions.”
Regularization penalty
A regularization penalty adds a cost for coefficient size, changing the optimization objective from plain least squares.
“The default L2 penalty in SGDRegressor must be disabled for a comparison with unpenalized least squares.”
Residual
A residual is an observed target minus its fitted prediction, so a positive residual indicates that the model underpredicts.
“Positive residuals at both ends of the input range suggest that a straight line misses curvature.”
Residual plot
A residual plot shows prediction misses against an input or fitted value, exposing patterns that an aggregate error score can hide.
“A fan-shaped residual plot reveals that errors spread more widely at larger predicted values.”
Root mean squared error
Root mean squared error is the square root of mean squared error, reporting an error magnitude in the target’s original units.
“A test RMSE of 2 kg can be compared directly with the baseline’s RMSE of 5 kg on the same rows.”

S

Scaler
A scaler is a fitted transformation that stores training-derived statistics and reuses them to change the coordinates of later inputs.
“The stored scaler transforms a new area before it reaches the regressor trained on standardized areas.”
Shuffling
Shuffling changes the order of training examples to reduce correlated update sequences and dependence on sorted input order.
“Shuffling mixes short and long deliveries instead of presenting them in distance order each epoch.”
Simultaneous update
A simultaneous update changes all parameters using derivatives calculated from the same current parameter values.
“Both gradients are stored before either the weight or the bias is assigned its new value.”
Singular matrix
A singular matrix is a square matrix with no inverse, occurring in the normal equation when the augmented feature columns are dependent.
“Recording the same distance in meters and centimeters makes the normal-equation matrix singular.”
Standardization
Standardization subtracts a training feature’s mean and divides by its standard deviation, giving a nonconstant training column unit variance.
“A standardized distance of two lies two training standard deviations above the training mean.”
Stochastic gradient descent
Stochastic gradient descent estimates a gradient from one training example at a time and updates the parameters after that example.
“A stochastic step can raise the full-data cost even while the epoch-level cost trends downward.”

T

Target
A target is the observed output that a supervised model learns to predict, recorded alongside the inputs for each example.
“The measured delivery time is the target, while the predicted time is the model’s output.”
Transpose
A transpose swaps the row and column roles of a matrix, allowing each original feature column to be paired with an error vector.
“The transposed design matrix turns one error per example into a separate weighted sum for each feature.”

V

Vectorization
Vectorization expresses repeated computations as whole-array operations, allowing compiled numerical routines to carry them out efficiently.
“A single matrix product computes the weighted feature sums for every delivery in the design matrix.”
Vectorized gradient
A vectorized gradient calculates every weight derivative together using matrix operations on the design matrix and prediction errors.
“The product of the transposed design matrix and the error vector is divided by the example count.”

W

Weight
A weight is a fitted coefficient that multiplies a feature; its units express target change per unit of that feature.
“A weight of 2 min/km adds two predicted minutes for each extra kilometer with other features fixed.”
Weight vector
A weight vector stores one coefficient per feature, in the same order as the columns used to calculate a model’s predictions.
“Swapping feature columns without swapping their weights changes the meaning of the prediction.”

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started