bhylu.com

Advertisements

Linear Regression

Linear regression fits a numeric target with a linear combination of features. Begin with a single-feature example whose relationship you can verify by hand.

Understand the idea

fit estimates coefficients from training data; predict applies the fitted rule to new rows with the same feature shape. scikit-learn expects a two-dimensional feature matrix even for one feature. Perfectly linear toy data demonstrates the API, not realistic accuracy. Evaluate on untouched data before using a fitted line for decisions.

Where to try it

Run locally with scikit-learn and NumPy installed in your virtual environment (py -m pip install scikit-learn numpy). These examples are executed during course review, but the online runner does not currently preload scikit-learn. The small data is for learning the API, not evidence of production model quality.

A worked example

Python

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit([[1], [2], [3], [4]], [3, 5, 7, 9])
print(model.predict([[5]]).round(2).tolist())

Read the result

The prediction is approximately [11.0], matching the constructed rule y = 2x + 1.

Try one change

Add noise to the training targets and evaluate a held-out observation rather than judging only training fit.

For package options, see the scikit-learn documentation.