Practical Implementation
In this chapter, we will explore the process of implementing a linear regression model, from data preparation to building and evaluating the model using Python. We will use libraries such as NumPy and Scikit-learn to illustrate practical application.
8.1 Data Preparation
Proper data preparation is a critical step in building linear regression models. Ensuring that the data are clean and well-structured is essential for obtaining accurate and interpretable results.
Steps in Data Preparation
-
Data Collection:
- Obtain the relevant data for the regression problem. This may include data from public sources, internal databases, or APIs.
-
Data Cleaning:
-
Handling Missing Values: Identify and address missing values. Common methods include removing rows or columns with many missing values, or imputing missing data.
-
Handling Outliers: Identify and analyze outliers. Depending on the context, outliers may be removed or adjusted.
-
-
Feature Engineering:
-
Variable Transformation: Apply transformations, such as logarithms or normalization, to improve the linearity and normality of the data.
-
Creating New Variables: Create new variables from existing data to better capture underlying relationships.
-
-
Data Splitting:
- Split the data into training and test sets to validate model performance. A common split is 70% for training and 30% for testing.
8.2 Implementation in Python Using NumPy
NumPy is a powerful library for numerical computing in Python, frequently used to manipulate arrays and perform mathematical operations.
Implementation Steps
Define Calculation Functions: The function that computes the coefficients will be created manually.
import numpy as np
def estimate_coef(x, y):
# Number of observations
n = np.size(x)
# Means of x and y
m_x, m_y = np.mean(x), np.mean(y)
# Calculate coefficients
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
beta_1 = SS_xy / SS_xx
beta_0 = m_y - beta_1*m_x
return (beta_0, beta_1)
Building the Model:
# Example dataset
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 5])
# Estimate coefficients
b = estimate_coef(x, y)
print(f"Estimated coefficients:\nIntercept: {b[0]}\nSlope: {b[1]}")
Visualizing the Results:
import matplotlib.pyplot as plt
def plot_regression_line(x, y, b):
# Predict y values
y_pred = b[0] + b[1]*x
# Scatter plot
plt.scatter(x, y, color="m", marker="o", s=30)
# Regression line
plt.plot(x, y_pred, color="g")
# Axis labels
plt.xlabel('x')
plt.ylabel('y')
# Display the plot
plt.show()
plot_regression_line(x, y, b)
8.3 Implementation in Python Using Scikit-learn
Scikit-learn is a robust and widely used library for Machine Learning in Python. It provides simple and efficient tools for data analysis.
Implementation Steps
-
Import Required Libraries:
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import numpy as np -
Load and Split the Data:
# Example dataset x = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) y = np.array([2, 3, 5, 6, 5]) # Split the data into training and test sets x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0) -
Train the Model:
# Create a linear regression object regressor = LinearRegression() # Train the model regressor.fit(x_train, y_train) -
Make Predictions:
# Make predictions on the test set y_pred = regressor.predict(x_test) # Visualize results plt.scatter(x_test, y_test, color='gray') plt.plot(x_test, y_pred, color='red', linewidth=2) plt.show() -
Evaluate the Model:
from sklearn.metrics import mean_squared_error, r2_score # Calculate MSE and R2 mse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print(f"Mean Squared Error: {mse}") print(f"Coefficient of Determination (R2): {r2}")