Course contentsShow
← Machine Learning and Deep Learning
Lesson 198 of 3,5383. Linear RegressionFree lesson

Simple Linear Regression with Scikit-learn

Using LinearRegression from sklearn to fit models, make predictions, and extract coefficients efficiently.

Simple Linear Regression with Scikit-learn

What You'll Learn

You'll learn how to use Scikit-learn's LinearRegression class to fit simple linear models efficiently, make predictions, and extract model parameters—all with just a few lines of code.

Why Use Scikit-learn for Linear Regression?

While you've already implemented linear regression from scratch and understand the math, Scikit-learn provides a battle-tested, optimized implementation. Think of it like building a car engine yourself to understand how it works, then switching to a reliable manufactured engine for actual driving.

Using LinearRegression from sklearn

The LinearRegression class follows Scikit-learn's consistent API pattern you've already seen:

from sklearn.linear_model import LinearRegression
import numpy as np

# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])

# Create and fit the model
model = LinearRegression()
model.fit(X, y)

# Make predictions
predictions = model.predict(X)

# Extract the learned parameters
slope = model.coef_[0]        # The 'm' in y = mx + b
intercept = model.intercept_   # The 'b' in y = mx + b

print(f"Slope: {slope:.2f}")
print(f"Intercept: {intercept:.2f}")

The fit() method solves the least squares problem using the normal equation under the hood. The predict() method applies your fitted line to new data points. The coef_ and intercept_ attributes give you direct access to the learned parameters—exactly what you calculated manually before.

When to Use It

Use LinearRegression whenever you need simple linear regression in practice. It handles edge cases, optimizes computation, and integrates seamlessly with the rest of Scikit-learn's ecosystem (pipelines, cross-validation, etc.).

Key Takeaway: Scikit-learn's LinearRegression encapsulates the math you've learned into a simple fit-predict interface, letting you build models in three lines while accessing coefficients and intercepts as attributes.