How to Train a Linear Regression Model with scikit-learn
Linear regression predicts a number from other numbers by fitting the best straight-line relationship between them. In scikit-learn it's LinearRegression: fit it on examples, score it on new ones, and read what it learned from its coefficients. This guide trains one on the diabetes dataset, with real output from scikit-learn 1.9.1.
Syntax
from sklearn.linear_model import LinearRegression
<model> = LinearRegression()
<model>.fit(<X_train>, <y_train>)
<model>.score(<X_test>, <y_test>)
| Part | What it means |
|---|---|
fit(X_train, y_train) | Learns one coefficient per feature, plus an intercept |
score(X_test, y_test) | R², the share of the target's variation the model explains on new data. 1.0 is perfect |
<model>.coef_, <model>.intercept_ | What it learned: the weight of each feature, and the value when every feature is 0 |
The scikit-learn reference: "Ordinary least squares Linear Regression. LinearRegression fits a linear model with coefficients w = (w1, …, wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation."
Prerequisites
- scikit-learn and pandas in your project, for example with
uv add scikit-learn pandas. This guide uses scikit-learn 1.9.1 and pandas 3.1.1 on Python 3.15.2.
Step 1: Write the Script
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = LinearRegression()
model.fit(X_train, y_train)
print(f"R2 on test data: {model.score(X_test, y_test):.3f}")
print(f"Intercept: {model.intercept_:.1f}")
print(dict(zip(X.columns[:3], model.coef_[:3].round(1).tolist())))

Step 2: Run It
uv run python linear_demo.py
R2 on test data: 0.359
Intercept: 153.1
{'age': -43.3, 'sex': -208.7, 'bmi': 593.4}

- R² of 0.359: the model explains about a third of the variation in disease progression on the test patients.
bmihas the largest of these three coefficients, 593.4: in this model, body mass index moves the prediction most.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Fitting on a single list of values | ValueError: Expected 2D array, got 1D array instead: with the advice to reshape | Give every row its own list: [[1], [2], [3]] fitted y = 2x, with coef_ [2.] and a prediction of [8.] for [[4]] |
| Comparing coefficients of features on different scales | A large coefficient may just mean a small-valued feature | Compare them only when the features share a scale, as the diabetes features do |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected 2D array, got 1D array instead | X is one flat list or a 1-D array | Use a list of rows, a DataFrame, or array.reshape(-1, 1) as the message suggests |
FAQ
Is an R² of 0.359 bad?
It depends on the problem. For this small medical dataset it's a starting point; the same split is used in the Ridge and Lasso guides to compare models fairly.
How do I predict for a new patient?
model.predict(rows) with a DataFrame of the same 10 columns.
Conclusion
LinearRegression().fit(X_train, y_train) learned an intercept of 153.1 and one coefficient per feature, and scored an R² of 0.359 on the test patients.
Additional Resources
- LinearRegression — the class and its attributes.
- Ordinary least squares — the user guide's section.
