- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Linear Regression
Linear Regression and Gradient Descent
IntermediateLesson 2 of 9 in Machine Learning Course
What you will learn
- Describe a regression task with a training set, write the one-feature model , and measure how well a choice of parameters fits the data with the squared-error cost.
- Set up the linear model for one featureUse 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 functionCompute 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.
- Set up the linear model for one feature
- 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 ruleCompute 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 convergenceRecognize 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 descentExplain 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.
- Apply the gradient descent update rule
- 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 modelWrite 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 arraysReplace 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 featuresUpdate all weights and the bias together with a vectorized gradient, write the full training loop, and check the result against an independent solution.
- Write and interpret the multiple linear regression model
- 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 standardizationExplain 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 workflowFit 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 featuresCreate 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.
- Rescale features with min-max, mean normalization or standardization
- 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 equationSet 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 descentCompare 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-learnTrain, 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 modelMeasure 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.
- Solve for the parameters with the normal equation
Linear Regression study guide
1Build 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 . Example is : its feature and its observed target. The superscript in parentheses is an index. Thus means the second input, while 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 and the third example has and . Each row connects an input with the target measured for that same delivery.
The one-feature model is
The hat marks a prediction. The target comes from the observations; the prediction comes from the model. Statistics texts often write this as , with and .
Read the weight and bias
The weight is the slope. It gives the change in predicted target for one extra unit of input. The bias 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 . 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: . Then add the bias: 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 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 , 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 . A positive error means an overprediction. A residual plot commonly uses the opposite sign, . Squaring either gives the same result.
The squared-error cost is
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 averages across examples. The additional factor of one half simplifies the derivatives used for training. Mean squared error, or MSE, omits that half, so . Both select the same parameters.
Compare two lines
For the four deliveries, try and .
| Distance (km) | Target (min) | Prediction (min) | Error (min) | Squared error (min²) |
|---|---|---|---|---|
| 1 | 10 | 10 | 0 | 0 |
| 2 | 14 | 13 | −1 | 1 |
| 3 | 15 | 16 | 1 | 1 |
| 4 | 21 | 19 | −2 | 4 |
The squared errors sum to 6. Divide by twice the four examples: . The MSE is min².
For and , 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 . 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, , 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 , 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, min² and 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.
- ; 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.
2Train 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 ,
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:
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 and use . Every prediction is zero, so the errors are −10, −14, −15, and −21 minutes.
For the weight, multiply the errors by the distances:
Divide by four: . For the bias, the error sum is −60, so . Now apply both updates:
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 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 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 behavior | Likely interpretation | Next check |
|---|---|---|
| Falls steadily but very slowly | Rate may be too small | Try a larger rate |
| Rises or oscillates | Rate may be too large | Reduce it and inspect the code |
| Falls quickly, then flattens | Near convergence | Check 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 . 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.
| Method | Examples per update | Updates in an epoch of 10,000 examples |
|---|---|---|
| Batch | All 10,000 | 1 |
| Stochastic | 1 | 10,000 |
| Mini-batch of 100 | 100 | 100 |
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 , with initial setting eta0=0.01. The update count 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,eta0andalphacontrol different settings.
3Predict 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 features, one example is the vector . The subscript selects a feature; the superscript in parentheses selects an example. Place examples in rows of the design matrix and features in columns. Its shape is . The target vector has length , the weight vector has length , 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
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,
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 minutes. The other predictions are 27 and 28. Subtract the targets to get errors 2, 3, and 1. Their squares sum to , so .
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 and stores . Then predictions are . 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 + bgives one prediction per row.X * wstill needs a row sum to produce predictions.np.mean(err ** 2) / 2computes 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,
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 ; its mean is −94. For stops, the sum is ; its mean is −46. The bias gradient is .
Subtract 0.01 times each gradient. The new weights are 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:
Try 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 / mgives 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.
4Scale 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.
| Method | Transformation | What it sets |
|---|---|---|
| Min-max | Training range from 0 to 1 | |
| Mean normalization | Training mean 0; values within −1 to 1 | |
| Standardization | Training mean 0 and standard deviation 1 |
For areas from 30 to 200 m², min-max scaling sends 120 m² to . 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 . 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:
The standardized value for 170 m² is ; 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 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 . 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, 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 and , use slope and intercept .
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
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 . The best straight line is . 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 , , and 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 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.
5Solve, 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 . Put the bias first in . Predictions are then , and the zero-gradient equations are
This is the normal equation. The matrix on the left has shape , one row and column per parameter. The right side has length . Multiplying in the other order, , gives an matrix with a different role.
When the parameter matrix is invertible, the solution can be written
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 is a one followed by the distance. Summing products of columns gives
The two equations are and . Multiply the first by 2.5 and subtract it from the second: . Thus , then .
The determinant is , so the inverse exists. Multiplying its numerator matrix by the right side gives entries and . Dividing by 20 gives the same bias and weight.
Use the one-feature formula
For a nonconstant input, the slope also has the form
Here the means are 2.5 km and 15 minutes, the numerator is 17, and the denominator is 5. The fitted line passes through 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
lstsqor 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
| Method | Main work | Settings and data access |
|---|---|---|
| Normal-equation system | Forming the matrix costs about ; solving it about | No learning rate; all needed cross-products |
| Batch gradient descent | Each update costs about | Rate, stopping rule, repeated full passes |
| SGD or mini-batch | Each update processes one example or a small group | Rate 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 is singular exactly when the columns of 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, . 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.
lstsqand 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.
fittrains;predictapplies the trained model.coef_andintercept_store fitted weights and bias.- Use a scaler and
penalty=Nonefor 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 evaluated examples,
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
The residual sum of squares is . For the deliveries, the target mean is 15 minutes and the total squared variation is . Thus : the fitted predictions account for about 93% of this variation around the mean.
A perfect fit has . 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 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
1From a delivery record to a fitted line
10 steps
- 1IntroductionTurn 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.
- 2ExplanationName 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 examples. The third pair is . The superscript in parentheses selects the third row; it does not square or cube the distance.
- 3ExampleMake a prediction
Use . At 2.5 km, the distance contribution is minutes. Adding the bias gives 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.
- 4ChallengeRead a different model
A cooling model predicts temperature in °C as , 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.
- 5ExampleCalculate each miss
Try the delivery line . 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.
- 6ExampleTurn the misses into cost
The cost divides the squared-error sum by twice the example count: . 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.
- 7AnalogyPicture 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.
- 8ChallengeCompare errors in target units
Three predictions have errors −3, 0, and 3 kg. What are J and RMSE?
---reveal---
The squared sum is kg². Thus kg² and kg. Cost is half the MSE; taking the square root of cost instead would miss that factor of two.
- 9ChallengeCheck 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.
- 10RecapUse 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.
2Take and inspect gradient steps
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLearn through repeated adjustments
- 2ExplanationRead the two derivatives
- 3ExampleFind the first gradients
- 4ExampleApply the stored changes
- 5ChallengeChoose the update direction
- 6ExplanationCompare cost curves
- 7ChallengeDistinguish a flat curve from a good fit
- 8ExplanationCount passes and updates
- 9Key InsightExpect noise from subsets
- 10ChallengeCalculate a mini-batch workload
- 11ChallengeChoose the right progress check
- 12RecapMatch monitoring to the update method
3Build and check a vectorized trainer
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionLet rows and columns do the repeated work
- 2ExampleGive each input a role
- 3ChallengeKeep units beside coefficients
- 4ExplanationMake one prediction per row
- 5ExampleCompute the three-row cost
- 6ChallengeCatch an accepted but wrong subtraction
- 7ExplanationTranspose to collect feature effects
- 8ExampleWork a zero-start gradient
- 9ExampleApply and record the update
- 10ChallengeRepair a transposed product
- 11TipCheck a derivative locally
- 12ChallengeInterpret matching fits correctly
- 13RecapUse two complementary checks
4Transform features without changing their meaning
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChange coordinates and available shapes
- 2AnalogyRecognize a narrow optimization valley
- 3ExampleCompare centering choices
- 4ExampleMeasure distance in standard deviations
- 5ChallengeCalculate a standardized value
- 6ExampleTransform a genuinely new row
- 7TipKeep the workflow together
- 8ChallengeDetect a preprocessing leak
- 9ExampleLet a squared input explain curvature
- 10ExplanationBuild the final feature columns first
- 11ChallengeChoose among candidate curves
- 12Key InsightInspect the price of flexibility
- 13ChallengeRecover an original-unit effect
- 14RecapValidate the complete transformation
5Solve a fit and judge its predictions
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionInspect both the solution and its usefulness
- 2ExplanationInclude the bias as a column
- 3ExampleSolve the two delivery equations
- 4ChallengeCheck the mean point
- 5ConnectionChoose a computational route
- 6ExampleUnderstand a redundant measurement
- 7TipHandle the missing inverse
- 8ChallengeCount the intercept parameter
- 9ExplanationFit the library model once
- 10ChallengeAlign a stochastic comparison
- 11ExampleCalculate an error in useful units
- 12ExplanationRead R² against its reference
- 13ChallengeEvaluate a held-out result
- 14Key InsightLook beyond a high score
- 15ChallengeDecide what the evidence supports
- 16RecapKeep fitting and evaluation connected
Linear Regression practice questions
Set 1: Models, errors, and first updates10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
X @ w + b when b is a scalar?Show answerHide answer
Question 8 of 10
grad_w, updates w, then calculates grad_b using the updated w. What change makes the step a simultaneous gradient update?Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Scaling, curves, and direct fitting10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
x stores 25 values of one input feature. What shape should it have for LinearRegression.fit?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
prediction = 6*z + 9. The training mean is 8 m and standard deviation is 2 m. What original-input model gives the same predictions?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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 - targets produce?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
predict. What should change?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
LinearRegression and a scaled SGDRegressor. What SGD setting removes a default difference in their objectives?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
PolynomialFeatures(degree=2, include_bias=False) to input columns and , with no scaler. Its fitted regressor has coefficients [1, 2, 0.5, -1, 1] and intercept 4. What does it predict at and ?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Augmented design matrix
B
Baseline
Batch gradient descent
Broadcasting
C
Closed-form solution
Coefficient of determination
Constant feature
Contour
Convergence
Convexity
Cost function
D
Data leakage
Design matrix
Divergence
E
Elementwise multiplication
Epoch
Estimator
F
Feature
Feature engineering
Feature scaling
Finite difference
Fitting
G
Gradient
Gradient descent
H
Hyperparameter
I
Interaction
Intercept
L
Learning curve
Learning rate
Learning schedule
Linear dependence
M
Matrix inverse
Matrix product
Mean normalization
Mean squared error
Min-max scaling
Mini-batch gradient descent
Minimum-norm solution
Multicollinearity
Multiple linear regression
N
Normal equation
Numerical tolerance
O
One-hot encoding
Outlier
Overfitting
P
Parameter
Partial derivative
Pipeline
Polynomial degree
Polynomial regression
Prediction
Prediction error
R
Regression
Regularization penalty
Residual
Residual plot
Root mean squared error
S
Scaler
Shuffling
Simultaneous update
Singular matrix
Standardization
Stochastic gradient descent
T
Target
Transpose
V
Vectorization
Vectorized gradient
W
Weight
Weight vector
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.