GNGiseldo Neo and Alana NeoBooks
Linear Regression with Python12 / 19

Advanced Applications

Linear regression can be applied in a variety of complex contexts, going beyond its basic applications. This chapter explores some of these advanced applications, including polynomial regression, a comparison between linear and logistic regression, and applications to time series.

11.1 Polynomial Regression

Polynomial regression is an extension of linear regression that allows modeling nonlinear relationships by including polynomial terms of the independent variables.

11.1.1 Definition and Use

The polynomial regression equation of degree nn is given by:

y=β0+β1x+β2x2+⋯+βnxn+ϵy = \beta_0 + \beta_1x + \beta_2x^2 + \cdots + \beta_nx^n + \epsilon

where the polynomial terms (x2,x3,…,xnx^2, x^3, \ldots, x^n) capture the curvature in the relationships between variables.

11.1.2 Implementation in Python

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

# Sample data
x = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([1, 4, 9, 16, 25])

# Degree-2 polynomial model
poly_model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
poly_model.fit(x, y)

# Predictions
y_pred = poly_model.predict(x)

11.1.3 Visualization

import matplotlib.pyplot as plt

plt.scatter(x, y, color='gray')
plt.plot(x, y_pred, color='red', linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Polynomial Regression of Degree 2')
plt.show()

11.2 Comparison Between Linear and Logistic Regression

While linear regression is used to predict continuous values, logistic regression is employed to predict categories.

11.2.1 Key Differences

  • Linear Regression: Predicts continuous values; the relationship between variables is modeled as a straight line.

  • Logistic Regression: Predicts binary outcomes (0 or 1); uses the sigmoid function to map predictions to the interval [0, 1].

11.2.2 Implementing Logistic Regression in Python

from sklearn.linear_model import LogisticRegression

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

# Logistic model
logistic_model = LogisticRegression()
logistic_model.fit(x, y)

# Predictions
y_prob = logistic_model.predict_proba(x)
y_pred = logistic_model.predict(x)

11.2.3 Visualization

plt.scatter(x, y, color='gray')
plt.plot(x, y_prob[:, 1], color='red', linewidth=2)
plt.xlabel('x')
plt.ylabel('Probability of Class 1')
plt.title('Logistic Regression')
plt.show()

11.3 Use in Time Series

Linear regression can be applied to time series to model trends and forecast future values.

11.3.1 Common Techniques

  • Simple Linear Regression: Models linear trends in time series.

  • Autoregressive (AR) Models: Use past values of the series to predict future values.

11.3.2 Implementing Linear Regression for Time Series

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Create sample data
dates = pd.date_range('2024-01-01', periods=100)
data = pd.DataFrame({'Date': dates, 'Value': np.random.randn(100).cumsum()})

# Split into training and test sets
train = data[:80]
test = data[80:]

# Train the model
linear_model = LinearRegression()
linear_model.fit(np.arange(len(train)).reshape(-1, 1), train['Value'])

# Make predictions
predictions = linear_model.predict(np.arange(len(train), len(train) + len(test)).reshape(-1, 1))

# Visualization
plt.plot(train['Date'], train['Value'], label='Training')
plt.plot(test['Date'], test['Value'], label='Test')
plt.plot(test['Date'], predictions, label='Prediction', linestyle='--')
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Forecasting with Linear Regression')
plt.legend()
plt.show()

11.3.3 Practical Considerations

  • Seasonal Trends: Adjust models to include variables that capture seasonality.

  • Autocorrelation: Check for the presence of autocorrelation, which can affect the validity of the model.