Linear Regression in Python with scikit-learn
Fit the best straight line through your data, read its slope and intercept, and predict new values.
- LinearRegression fit and predict
- coef_ and intercept_
- Measuring the fit with R^2 and MAE
- 1
hours = 9New input - 2
4.48 x 9 + 46.86Slope times input plus intercept - 3
87.1Predicted score
The best straight line
The problem
You have pairs of measurements (hours studied and exam score, size and price) and want to know how one changes with the other, and to predict values you did not measure.
Think of it like this
Linear regression is like laying a ruler across a scatter of points so it passes as close as possible to all of them. The ruler's tilt is the slope, where it crosses zero is the intercept, and reading off the ruler gives a prediction.
model.fit(hours, scores)📏 Lay the ruler through the pointsmodel.coef_↗️ The tilt: 4.48 points per hourmodel.intercept_📍 Where the ruler starts: 46.86model.predict([[9]])🔮 Read a new value off the rulerLinear regression models the target as a weighted sum of the features plus a constant, choosing the weights that make the squared errors as small as possible.
Key points
hoursmust be 2D (one row per sample, one column per feature);scoresis 1D.- The fitted line is score = 4.48 x hours + 46.86.
r2_scoreof 0.992 means the line explains almost all of the variation.mean_absolute_errorsays predictions are 0.82 points off on average.
When should you use it?
- Predicting a number: price, score, temperature, sales.
- Measuring how strongly one variable changes with another.
- A simple baseline before trying more complex models.
When not to use it
- Clearly curved relationships: add polynomial features or use another model.
- Yes/no targets: use logistic regression.
Example code
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
# Hours studied and exam score for 8 students
hours = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
scores = np.array([52, 55, 61, 64, 70, 72, 79, 83])
model = LinearRegression()
model.fit(hours, scores)
print(f"Slope (coef_): {model.coef_[0]:.2f} points per hour")
print(f"Intercept: {model.intercept_:.2f}")
predicted = model.predict(hours)
print(f"R^2: {r2_score(scores, predicted):.3f}")
print(f"MAE: {mean_absolute_error(scores, predicted):.2f} points")
new_students = np.array([[2.5], [9]])
for h, p in zip(new_students.ravel(), model.predict(new_students)):
print(f"{h} hours -> predicted score {p:.1f}")
Result of running the code
Slope (coef_): 4.48 points per hour
Intercept: 46.86
R^2: 0.992
MAE: 0.82 points
2.5 hours -> predicted score 58.0
9.0 hours -> predicted score 87.1
Code explanation
hours is a 2D array with one column because scikit-learn always expects rows and columns of features, and scores holds the targets. fit finds the line score = 4.48 x hours + 46.86, stored in coef_ and intercept_. r2_score of 0.992 means the line explains almost all of the variation, and mean_absolute_error says predictions are off by 0.82 points on average. predict then gives 58.0 for 2.5 hours and 87.1 for 9 hours, which is outside the measured range, so treat it with care.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Passing a 1D array as the features
scikit-learn expects a 2D array of features and raises an error for a flat list.
model.fit([1, 2, 3], [52, 55, 61])
model.fit([[1], [2], [3]], [52, 55, 61])
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Simple Linear Regression (Least Squares) Fit the best straight line through data points with the least squares formulas. Medium
- Linear Regression with Gradient Descent Learn the slope and intercept of a line by repeatedly stepping down the mean squared error. Medium
Tools for this lesson
- Linear and Logistic Regression in PythonFit a straight line with least squares, then turn a score into a probability with logistic regression.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.