Linear Regression
Predict from Fitted Line
Apply a fitted slope and intercept to predict y for new x values:
y=slope·x+intercept. A loop computes one prediction per new x. Library:
LinearRegression().fit(X, y).predict(X_new) — same formula vectorized.
RESULT: list of predictions (rounded).
By hand
With scikit-learn
model.predict(X_new) applies the fitted parameters to new inputs.
X_new must be 2D (one column), matching the shape used in .fit.
slope = 0.8
intercept = 1.6
x_new = [3, 6, 10]
preds = []
for x in x_new:
y = slope * x + intercept
preds.append(y)
print('RESULT:', [round(v, 4) for v in preds])
from sklearn.linear_model import LinearRegression
from dalib.display import set_display
set_display()
x = [1, 2, 3, 4, 5]
y = [2, 4, 4, 4, 6]
X = [[v] for v in x]
model = LinearRegression()
model.fit(X, y)
x_new = [3, 6, 10]
X_new = [[v] for v in x_new]
preds = [round(float(p), 4) for p in model.predict(X_new)]
print('x_new:', x_new)
print('RESULT:', preds)
x_new: [3, 6, 10]
RESULT: [4.0, 6.4, 9.6]
Honesty
This lesson shows the computation of a prediction from a fitted line exactly, on a tiny pinned sample. The arithmetic is correct and reproducible, but the line was fit to a handful of points, so predicting a new point is a mechanism demo, not a valid forecast. Predicting outside the observed x-range is an extrapolation the data cannot support, and no confidence claim is warranted at this sample size; a trustworthy prediction needs an adequate sample and a held-out check.
Implementation notes
- slope and intercept are hardcoded from
normal-equation-1d(this chapter) — prediction requires only the fitted parameters and new x values. model.predictrequires 2D input;[[v] for v in x_new]reshapes to match the one-column X used at fit time.- Cross-reference:
predict-from-line(python-stats ch08) uses the same arithmetic by hand; this lesson applies it via the sklearn.predictAPI. - x=6 and x=10 are outside the training range [1,5] — the model extrapolates linearly; whether extrapolation is valid depends on the domain.