How to write (with python) a realisation of linear regression from the scratch without using libraries (using numpy only for math or matplotlib/seaborn for visualisation is ok)?
Assistant
Creating a simple implementation of linear regression from scratch in Python can be broken down into a few key steps. Below, I'll outline how to implement the Ordinary Least Squares (OLS) method for linear regression. This includes the steps for fitting the model to the data and making predictions. We'll then visualize the results using Matplotlib.
Step-by-Step Implementation
Generate Sample Data: Create some synthetic data.
Implement the Linear Regression Class: This class will encapsulate the methods for fitting the model and making predictions.
Visualize the Results: Plot the original data points and the fitted line.
Here's the complete code:
python
import numpy as np
import matplotlib.pyplot as plt
# Step 1: Generate Sample Data
np.random.seed(0) # For reproducibility
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1) # Linear relationship with noise
# Step 2: Implementing Linear Regression from Scratch
class LinearRegression:
def __init__(self):
self.theta = None
def fit(self, X, y):
# Add intercept term (bias) to X
X_b = np.c_[np.ones((X.shape[0], 1)), X] # Add bias term (X0 = 1)
# Calculate theta using Normal Equation
self.theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
def predict(self, X):
# Add intercept term to X
X_b = np.c_[np.ones((X.shape[0], 1)), X]
return X_b.dot(self.theta)
# Create an instance of the model
model = LinearRegression()
model.fit(X, y)
# Making predictions
X_new = np.array([[0], [2]]) # For prediction range
y_predict = model.predict(X_new)
# Step 3: Visualize the results
plt.scatter(X, y, color="blue", label="Data points")
plt.plot(X_new, y_predict, color="red", label="Regression line")
plt.xlabel("X")
plt.ylabel("y")
plt.title("Linear Regression from Scratch")
plt.legend()
plt.show()
Explanation of the Code:
Data Generation:
We generate random data with a linear relationship, where (y = 4 + 3X + \text{noise}).
np.random.seed(0) ensures that we get the same random numbers each time the code is run.
Linear Regression Class:
The LinearRegression class has two main methods: fit() to train the model and predict() to make predictions.
In fit(), we first add a bias term (intercept) to the input features X. Then, we compute the optimal values for the parameters (coefficients) using the Normal Equation: ( \theta = (X^TX)^{-1}X^Ty ).
The predict() method also adds a bias term to the input features and then computes the predictions using the learned parameters.
Visualization:
We visualize the original data points and the fitted line using Matplotlib. plt.scatter() plots the data points, and plt.plot() draws the regression line.
Conclusion:
This is a basic implementation of linear regression using Python without relying on libraries other than numpy for mathematical computations. You can improve upon this implementation by adding methods for metrics calculation (like Mean Squared Error), support for multiple features, and other forms of regression.