Skip to main content

How to Train a Linear Regression Model with scikit-learn

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
from sklearn.linear_model import LinearRegression

<model> = LinearRegression()
<model>.fit(<X_train>, <y_train>)
<model>.score(<X_test>, <y_test>)
PartWhat 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​

linear_demo.py
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())))

The linear_demo.py script in a macOS-style code window: load_diabetes as a DataFrame, train_test_split, LinearRegression fitted on the training data, then print of the R2 on test data, the intercept and the first three coefficients by column name.

Step 2: Run It​

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

The script's output in a terminal: R2 on test data: 0.359, Intercept: 153.1, and the coefficients age -43.3, sex -208.7 and bmi 593.4.

  • R² of 0.359: the model explains about a third of the variation in disease progression on the test patients.
  • bmi has the largest of these three coefficients, 593.4: in this model, body mass index moves the prediction most.

Common Mistakes​

MistakeWhat happensDo this instead
Fitting on a single list of valuesValueError: Expected 2D array, got 1D array instead: with the advice to reshapeGive 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 scalesA large coefficient may just mean a small-valued featureCompare them only when the features share a scale, as the diabetes features do

Troubleshooting​

SymptomLikely causeFix
Expected 2D array, got 1D array insteadX is one flat list or a 1-D arrayUse 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​