Sub topic 4
Fitting your first LinearRegression
This chapter assumes you can write basic Python, create NumPy arrays and read their shapes, and recall the equation of a line. You will fit a LinearRegression model, inspect what it learned, and avoid the errors that most often trip up a first fit.
What fit actually does
LinearRegression implements ordinary least squares (OLS). Given a feature matrix X with shape (n_samples, n_features) and a target y, it finds the weights w and intercept b that minimize the sum of squared differences between y and X @ w + b.
Unlike many scikit-learn models, it does not iterate. It solves the problem directly with a linear algebra routine (a least-squares solver from SciPy), so there is no learning rate, no number of epochs and no random seed. Fitting the same data twice gives the same answer.
Centering is how scikit-learn handles the intercept. After solving for w on the centered data, it computes b = mean(y) - mean(X) @ w.
A first fit
The data below follows y = 3x + 2 plus noise. Because you know the true slope and intercept, you can check that the model recovers them.
import numpy as np
from sklearn.linear_model import LinearRegression
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)
model = LinearRegression()
model.fit(X, y)
print("coef_:", model.coef_)
print("intercept_:", model.intercept_)
print("n_features_in_:", model.n_features_in_)
print("prediction at x=5:", model.predict([[5.0]]))Expect coef_ close to 3, intercept_ close to 2, and a prediction near 17. They will not match exactly, because the noise shifts the best-fitting line slightly.
Three things to notice:
fitreturns the estimator itself, soLinearRegression().fit(X, y)works as a one-liner.- Learned values end in an underscore (
coef_,intercept_,n_features_in_). This is a scikit-learn convention: attributes with a trailing underscore exist only after fitting. predicttakes a 2D input even for one sample.[[5.0]]is one row with one feature.
Verifying against plain NumPy
To see that nothing mysterious happens, solve the same problem by hand. Append a column of ones to X so the intercept becomes one more weight, then call np.linalg.lstsq.
import numpy as np
from sklearn.linear_model import LinearRegression
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)
model = LinearRegression().fit(X, y)
Xb = np.column_stack([X, np.ones(len(X))])
w, *_ = np.linalg.lstsq(Xb, y, rcond=None)
print("manual slope, intercept:", w)
print("slope matches:", np.allclose(w[:1], model.coef_))
print("intercept matches:", np.isclose(w[1], model.intercept_))Both checks print True. The scikit-learn version adds input validation, the estimator API and support for multiple targets, not a different algorithm.
Shapes and attributes
Most first-time errors come from shapes. This table summarizes what to pass in and what you get back.
| Object | Shape | Notes |
|---|---|---|
| `X` | `(n_samples, n_features)` | Always 2D, even with one feature |
| `y` | `(n_samples,)` | A 2D `y` of shape `(n_samples, n_targets)` fits several targets at once |
| `coef_` | `(n_features,)` | With a 2D `y`, shape is `(n_targets, n_features)` |
| `intercept_` | scalar | With a 2D `y`, shape is `(n_targets,)` |
| `predict(X_new)` | `(n_new_samples,)` | `X_new` needs the same number of columns as the training `X` |
With several features, coef_ has one weight per column, in the same order as the columns you passed.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(1)
X = rng.normal(size=(300, 3))
y = 4.0 * X[:, 0] - 2.0 * X[:, 1] + 0.0 * X[:, 2] + 5.0 + rng.normal(0, 0.5, size=300)
model = LinearRegression().fit(X, y)
for i, w in enumerate(model.coef_):
print(f"feature {i}: {w:.2f}")
print(f"intercept: {model.intercept_:.2f}")The weights come out near 4, -2 and 0, with an intercept near 5. The third feature has no true effect, and the model assigns it a weight close to zero.
Common errors
Passing a 1D feature array
The most frequent error is passing a 1D array as X:
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.arange(10.0)
y = 2.0 * x + 1.0
try:
LinearRegression().fit(x, y)
except ValueError as e:
print("Error:", str(e).splitlines()[0])
model = LinearRegression().fit(x.reshape(-1, 1), y)
print(model.coef_, model.intercept_)scikit-learn raises a ValueError saying it expected a 2D array. The fix is x.reshape(-1, 1), which turns the array into a single column. With a pandas DataFrame, select with double brackets (df[["area"]]) to keep two dimensions.
Mismatched columns at prediction time
If you train on three columns and predict with two, you get a ValueError. When X is a DataFrame, scikit-learn also remembers the column names in feature_names_in_ and warns if you predict with different names or a different order. Treat that warning as a bug, because the weights are matched by position.
Missing values
LinearRegression raises an error on NaN values. Drop those rows or fill them in before fitting. A later chapter on pipelines shows how to do this safely.
Options worth knowing
LinearRegression has few parameters.
fit_intercept=Trueis the default. Set it toFalseonly when you know the line must pass through the origin. If the data is not centered, the fit will be worse.positive=Trueforces all coefficients to be non-negative. It switches to a different solver, and it is useful when negative weights make no sense in your problem.n_jobsonly matters for multi-target problems or sparse input. It rarely changes anything.
Getting a quick score
Every regressor has a score method. For LinearRegression it returns R-squared, the fraction of the target's variance explained by the model. A value of 1.0 is perfect, and 0.0 is no better than always predicting the mean of y.
import numpy as np
from sklearn.linear_model import LinearRegression
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)
model = LinearRegression().fit(X, y)
print("R2 on the training data:", model.score(X, y))This number is computed on the same data the model was fit on. It tells you how well the line matches data it has already seen, not how it will do on new data. Evaluating honestly requires held-out data, which is the topic of the next chapter.
Exercise
You run LinearRegression().fit(df["area"], df["price"]) on a DataFrame and get a ValueError about a 2D array. What is the cause, and how do you fix it? After the fix, what shape does coef_ have?
Show answer
df["area"] is a 1D Series, but X must be 2D with shape (n_samples, n_features). Use df[["area"]] (double brackets) to keep a one-column DataFrame, or .to_numpy().reshape(-1, 1). With one feature, coef_ has shape (1,), and intercept_ is a single number.
Exercise
You fit a model on training data with three feature columns. Later you call predict on an array with four columns. What happens, and why is passing the right columns in the right order important?
Show answer
scikit-learn raises a ValueError because the number of features differs from n_features_in_. Even when the column count matches, the weights in coef_ are applied by position, so a reordered set of columns silently produces wrong predictions. DataFrame inputs give a warning about mismatched feature names, which you should not ignore.