Sub topic 4
Fitting your first LinearRegression
This chapter fits a LinearRegression model on synthetic data and checks that it recovers the line that generated the data. It assumes you know basic Python, NumPy array shapes, and the equation of a line. It also assumes you have seen the fit and predict pattern from the previous chapter.
What LinearRegression does
LinearRegression finds the coefficients w and intercept b that minimize the sum of squared differences between the predictions Xw + b and the true targets. This is ordinary least squares (OLS). scikit-learn solves it directly with a linear algebra routine, so there is no learning rate and no iteration to tune.
Build data with a known answer
Synthetic data lets you check the result. The code below generates the target from y = 3x + 2 and adds Gaussian noise with standard deviation 1. The true slope is 3 and the true intercept is 2.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)
print("coef:", model.coef_, "intercept:", model.intercept_)
print("RMSE:", np.sqrt(mean_squared_error(y_test, pred)))
print("MAE:", mean_absolute_error(y_test, pred))
print("R2:", r2_score(y_test, pred))Reading the code
Xhas shape(200, 1). scikit-learn expects a 2D feature array with shape(n_samples, n_features), even with one feature.yhas shape(200,). It is a 1D array of targets.train_test_splitholds out 25% of the rows. The model never sees them duringfit, so the test metrics estimate performance on new data.fitlearns the parameters. They are stored in attributes that end with an underscore:coef_andintercept_.coef_is an array with one entry per feature. Here it has one entry.intercept_is a single number.
What to expect
The learned slope should land close to 3 and the intercept close to 2. They will not match exactly, because the noise shifts the estimates a little. The exact digits depend on your library versions, so check them by running the code.
The noise has standard deviation 1. That sets a floor on the error. Even a perfect model cannot predict the noise, so the test RMSE should be close to 1. The R-squared value should be high, because the line explains most of the variation in y. The next chapters cover the metrics in detail.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: Expected 2D array, got 1D array` | Passed a 1D array as `X` | Use `X.reshape(-1, 1)` or select columns with `df[["col"]]` |
| Coefficients are far from the truth | Too little data, heavy noise, or the wrong model form | Check the sample size and plot the data |
| Great training score, poor test score | Overfitting | Evaluate on held-out data and consider regularization |
Exercise
In the code above, X has shape (200, 1) and y has shape (200,). What shape does model.coef_ have after fitting, and why?
Show answer
It has shape (1,). coef_ holds one weight per feature, and X has one feature. With 5 features it would have shape (5,).