Sub topic 1
What Regression Predicts and Why We Use It
Prerequisites
This chapter assumes basic Python, NumPy arrays, pandas DataFrames, and high-school algebra. You should know that a feature is an input variable and a target is the value a model tries to predict.
What Regression Predicts and Why We Use It
Regression predicts a continuous numeric value, such as house price, delivery time, or temperature. In supervised learning, a model learns from examples that contain both features and known target values.
The goal is to learn a relationship that also works for new examples. For example, a house-price model can use area and location to estimate the price of a house not in the training data.
The Linear Model and Least Squares
A linear model predicts a target using a weighted sum of features:
ŷ = Xw + bHere, ŷ is the prediction, X contains the features, w contains learned coefficients, and b is the intercept. With one feature, this is the familiar equation of a line.
Ordinary least squares chooses w and b by minimizing the sum of squared residuals. A residual is the actual target minus the prediction. Squaring makes large errors count more and prevents positive and negative errors from canceling.
The Estimator API: fit, predict, score
Scikit-learn estimators usually follow the same interface:
fit(X, y)learns from features and targets.predict(X)returns predicted target values.score(X, y)returns a built-in evaluation score. ForLinearRegression, this is R-squared, orR².
An R² value of 1 means perfect predictions. A value near 0 means the model is no better than predicting the target mean on that data.
Fitting Your First `LinearRegression`
LinearRegression implements ordinary least squares.
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([3, 5, 7, 9, 11])
model = LinearRegression()
model.fit(X, y)
print("coefficient:", model.coef_[0])
print("intercept:", model.intercept_)
print("prediction:", model.predict([[6]])[0])The coefficient is the predicted change in y for a one-unit increase in the feature. The intercept is the prediction when the feature is zero.
Holding Out Data with `train_test_split`
Testing on the same rows used for fitting gives an overly optimistic result. train_test_split separates examples into training and test sets. Fit on the training set, then evaluate once on the held-out test set.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
model.fit(X_train, y_train)
print("test R2:", model.score(X_test, y_test))Exercise
Why should the test set remain separate while the model is being fitted?
Show answer
It estimates performance on unseen data instead of measuring how well the model remembers its training examples.