Linear regression is a fundamental machine learning algorithm used for predicting a quantitative response. In this tutorial, we'll walk through a step-by-step process of implementing linear regression using Python's scikit-learn library. We'll start with a simple example involving one independent variable and then expand to multiple variables. By the end of this tutorial, you'll understand how to prepare data, build a regression model, visualize results, and evaluate model performance.
We'll use a synthetic dataset called advertising.csv, which contains data about advertising budgets and sales figures. The dataset includes the following features:
For the initial part, we'll use the TV budget to predict Sales.
Let's start by importing the necessary Python libraries.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metricsExplanation:
We'll load the dataset into a pandas DataFrame and explore it.
# Assuming the CSV is available in the same directory
df = pd.read_csv('advertising.csv')Explanation:
Now, let's look at the first few rows of the data.
df.head()Explanation:
Let's get more information about the dataset.
df.info()Explanation:
Let's check some statistical details.
df.describe()Explanation:
Suppose our dataset has an unnecessary column called 'Unnamed: 0'.
if 'Unnamed: 0' in df.columns:
df = df.drop('Unnamed: 0', axis=1)Explanation:
Check for missing values.
df.isnull().sum()Explanation:
Fill missing values if any.
df = df.fillna(df.mean())Explanation:
For linear regression, normalization isn't strictly necessary, but it's good practice.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df[['TV', 'Radio', 'Newspaper']] = scaler.fit_transform(df[['TV', 'Radio', 'Newspaper']])Explanation:
Plotting boxplots to identify outliers.
sns.boxplot(data=df[['TV', 'Radio', 'Newspaper']])
plt.show()Explanation:
For simplicity, we'll skip outlier removal in this tutorial.
Plotting a correlation heatmap.
corr = df.corr()
sns.heatmap(corr, annot=True)
plt.show()Explanation:
We'll use TV advertising budget to predict Sales.
X = df[['TV']] # Independent variable
y = df['Sales'] # Dependent variable
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)Explanation:
lr = LinearRegression()
lr.fit(X_train, y_train)Explanation:
print('Intercept:', lr.intercept_)
print('Coefficient:', lr.coef_)Explanation:
y_pred = lr.predict(X_test)Explanation:
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted')
plt.title('TV Advertising Budget vs Sales')
plt.xlabel('TV Advertising Budget (Standardized)')
plt.ylabel('Sales')
plt.legend()
plt.show()Explanation:
Calculating error metrics.
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print('Mean Squared Error:', mse)
print('R^2 Score:', r2)Explanation:
Now, we'll include Radio and Newspaper budgets as additional features.
X = df[['TV', 'Radio', 'Newspaper']] # Multiple features
y = df['Sales']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)lr_multi = LinearRegression()
lr_multi.fit(X_train, y_train)Interpreting coefficients.
print('Intercept:', lr_multi.intercept_)
print('Coefficients:', lr_multi.coef_)
print('Feature Names:', X.columns)Explanation:
y_pred_multi = lr_multi.predict(X_test)mse_multi = mean_squared_error(y_test, y_pred_multi)
r2_multi = r2_score(y_test, y_pred_multi)
print('Mean Squared Error (Multiple Features):', mse_multi)
print('R^2 Score (Multiple Features):', r2_multi)In this tutorial, we've:
Note: Remember to replace 'advertising.csv' with the actual path to your dataset in Google Colab.