Regression is a type of supervised learning method used to predict a continuous outcome variable (often referred to as the dependent variable) based on one or more predictor variables (independent variables). The goal of regression analysis is to model the relationship between the dependent variable and the independent variables.

Key Concepts in Regression

1. Types of Regression

2. Model Representation

The basic idea of regression is to find the best-fitting line (or hyperplane in multiple dimensions) that predicts the dependent variable based on the independent variables.

Simple Linear Regression Equation: $$ y = \beta_0 + \beta_1 x + \epsilon $$

Multiple Linear Regression Equation: $$ y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n + \epsilon $$

3. Key Metrics

4. Assumptions of Linear Regression

5. Evaluating Model Performance

Practical Example of Linear Regression in Python

Here’s how you can implement a simple linear regression model using Python and the scikit-learn library:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

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

# Fit the linear regression model
model = LinearRegression()
model.fit(X, y)

# Make predictions
y_pred = model.predict(X)

# Print coefficients
print(f"Intercept:{model.intercept_}")
print(f"Coefficient:{model.coef_[0]}")

# Calculate metricsmse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y, y_pred)
print(f"MSE:{mse}")
print(f"RMSE:{rmse}")
print(f"R-squared:{r2}")

# Plot resultsplt.scatter(X, y, color='blue')
plt.plot(X, y_pred, color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Simple Linear Regression Example')
plt.show()
  1. Data Preparation:

    • We define our independent variable (\( X \)) and dependent variable (\( y \)) using numpy arrays.
  2. Model Fitting:

    • We create an instance of the LinearRegression model and fit it to our data.
  3. Making Predictions:

    • We use the predict method to predict (\( y \)) values based on our fitted model.
  4. Coefficients:

    • We print out the intercept and the coefficient of the model.
  5. Model Evaluation:

    • We calculate and print the Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and R-squared value to evaluate the model's performance.
  6. Plotting:

    • We visualize the original data points and the fitted line to understand the model fit.