Linear Regression in Python

Python's Scikit-learn library makes it straightforward to fit a Linear Regression model, make predictions, and evaluate how well it performs - all in just a few lines of code.

Preparing the Data

import pandas as pd
from sklearn.model_selection import train_test_split

df = pd.DataFrame({
    "HoursStudied": [1, 2, 3, 4, 5, 6, 7, 8],
    "Score": [35, 45, 50, 60, 65, 75, 80, 90]
})

X = df[["HoursStudied"]]   # features (must be 2D)
y = df["Score"]            # target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

Fitting the Model

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X_train, y_train)

print("Slope:", model.coef_)
print("Intercept:", model.intercept_)

Making Predictions

predictions = model.predict(X_test)
print(predictions)

# Predicting for a new value
new_score = model.predict([[6.5]])
print(new_score)

Evaluating the Model

from sklearn.metrics import mean_squared_error, r2_score

print("MSE:", mean_squared_error(y_test, predictions))
print("R-squared:", r2_score(y_test, predictions))
R-squared tells you what proportion of the variation in the target is explained by the model - a value close to 1 means the line fits the data very well, while a value close to 0 means the feature barely explains the target at all.

Coming Up Next

Next, you'll extend this idea to Multiple Linear Regression, where more than one feature is used to predict the target.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course