Building a Polynomial Regression model from scratch in Python without using external libraries like numpy or scikit-learn is a great way to understand the underlying mechanics of regression algorithms. Below, I'll provide a step-by-step implementation that:
- Takes inputs: Degree of the polynomial and multiple features (
x1, x2, ..., xn).
- Fits the polynomial regression model.
- Predicts output
y.
Step 1: Understand Polynomial Regression
Polynomial Regression is an extension of Linear Regression where the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial. For multiple features, the model becomes:
[ y = \beta_0 + \beta_1x_1 + \beta_2x_2 + \dots + \beta_nx_n + \beta_{11}x_1^2 + \beta_{12}x_1x_2 + \dots + \beta_{nn}x_n^2 + \dots + \epsilon ]
Step 2: Implementation Without External Libraries
We'll implement the following steps:
- Data Preprocessing: Generate polynomial features based on the specified degree.
- Model Training: Use the Normal Equation to solve for the coefficients.
- Prediction: Use the learned coefficients to predict new data points.
Here's the complete Python implementation:
# Polynomial Regression from scratch without using external libraries
# Function to generate polynomial features
def generate_polynomial_features(X, degree):
from itertools import combinations_with_replacement
import math
n_samples = len(X)
n_features = len(X[0])
# Start with bias term
features = [[1] for _ in range(n_samples)]
for deg in range(1, degree + 1):
for item in combinations_with_replacement(range(n_features), deg):
new_feature = []
for sample in X:
val = 1
for index in item:
val *= sample[index]
new_feature.append(val)
features[0].append(new_feature[0])
for i in range(n_samples):
if deg ==1 and len(features) ==1:
features[i].append(new_feature[i])
elif deg >1:
features[i].append(new_feature[i])
return features
# Function to perform matrix multiplication
def mat_mult(A, B):
result = [[0 for _ in range(len(B[0]))] for __ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
return result
# Function to transpose a matrix
def transpose(A):
return list(map(list, zip(*A)))
# Function to calculate inverse of a matrix
def inverse_matrix(matrix):
n = len(matrix)
AM = [row[:] for row in matrix]
I = [[float(i == j) for i in range(n)] for j in range(n)]
for fd in range(n):
fdScalar = AM[fd][fd]
if fdScalar == 0:
# Find a row to swap
for i in range(fd+1, n):
if AM[i][fd] != 0:
AM[fd], AM[i] = AM[i], AM[fd]
I[fd], I[i] = I[i], I[fd]
fdScalar = AM[fd][fd]
break
else:
raise ValueError("Matrix is singular and cannot be inverted.")
# Scale fd row
for j in range(n):
AM[fd][j] /= fdScalar
I[fd][j] /= fdScalar
# Zero out the other rows
for i in list(range(n)):
if i != fd:
factor = AM[i][fd]
for j in range(n):
AM[i][j] -= factor * AM[fd][j]
I[i][j] -= factor * I[fd][j]
return I
# Function to fit the model
def fit_polynomial_regression(X, y, degree):
# Generate polynomial features
features = generate_polynomial_features(X, degree)
# Convert y to a column vector
y_column = [[val] for val in y]
# Transpose of X
X_transpose = transpose(features)
# X_transpose * X
XtX = mat_mult(X_transpose, features)
# Invert XtX
XtX_inv = inverse_matrix(XtX)
# X_transpose * y
Xty = mat_mult(X_transpose, y_column)
# Calculate coefficients: (X^T X)^-1 X^T y
coefficients_matrix = mat_mult(XtX_inv, Xty)
# Flatten coefficients
coefficients = [row[0] for row in coefficients_matrix]
return coefficients
# Function to predict using the fitted model
def predict_polynomial_regression(X, coefficients, degree):
from itertools import combinations_with_replacement
n_samples = len(X)
n_features = len(X[0])
predictions = []
for sample in X:
pred = coefficients[0] # bias term
feature_idx = 1
for deg in range(1, degree+1):
for item in combinations_with_replacement(range(n_features), deg):
val = 1
for index in item:
val *= sample[index]
pred += coefficients[feature_idx] * val
feature_idx +=1
predictions.append(pred)
return predictions
# Example usage
if __name__ == "__main__":
# Sample data
# Let's consider a simple dataset with two features
X = [
[1, 2],
[2, 3],
[4, 5],
[3, 6],
[5, 7]
]
y = [5, 7, 15, 13, 19]
degree = 2 # Quadratic
# Fit the model
coefficients = fit_polynomial_regression(X, y, degree)
print("Coefficients:")
print(coefficients)
# Predict
X_new = [
[2, 4],
[3, 5],
[5, 8]
]
predictions = predict_polynomial_regression(X_new, coefficients, degree)
print("Predictions:")
for inp, pred in zip(X_new, predictions):
print(f"Input: {inp} => Predicted y: {pred}")
Explanation of the Implementation
-
Generating Polynomial Features (generate_polynomial_features):
- Uses combinations with replacement to generate all polynomial terms up to the specified degree.
- For example, for degree 2 and two features
x1, x2, it generates: 1, x1, x2, x1^2, x1x2, x2^2.
-
Matrix Operations:
- Matrix Multiplication (
mat_mult): Multiplies two matrices.
- Transpose (
transpose): Transposes a given matrix.
- Inverse (
inverse_matrix): Calculates the inverse of a square matrix using Gaussian elimination. Note that this is not optimized for large matrices and might be inefficient for high-degree polynomials or many features.
-
Fitting the Model (fit_polynomial_regression):
- Generates polynomial features for the input data.
- Computes the Normal Equation: (\beta = (X^T X)^{-1} X^T y) to find the coefficients.
-
Prediction (predict_polynomial_regression):
- Generates the same polynomial features for new input data.
- Computes the dot product with the learned coefficients to make predictions.
-
Example Usage:
- A sample dataset with two features is used.
- The model is fitted with a quadratic polynomial.
- Predictions are made on new data points.
Points to Consider
-
Scalability: This implementation uses pure Python and is not optimized for large datasets or high-degree polynomials. For practical purposes, using libraries like numpy for optimized matrix operations is recommended.
-
Numerical Stability: Implementing matrix inversion from scratch can lead to numerical instability, especially with ill-conditioned matrices. In production scenarios, more robust methods like Singular Value Decomposition (SVD) are preferred.
-
Feature Scaling: Depending on the data, you might need to scale features to improve numerical stability and performance.
Additional Resources
While you've requested an implementation without external libraries, here are some resources that showcase similar implementations and can provide further insights:
-
GitHub Repositories:
-
Blog Posts:
(Note: As an AI developed by OpenAI, I don't have direct access to browse current GitHub repositories or blogs. The above links are illustrative. Please search GitHub or your preferred search engine with keywords like "polynomial regression from scratch Python" to find relevant resources.)
Conclusion
Building a Polynomial Regression model from scratch helps in understanding the foundational concepts of machine learning algorithms. While using optimized libraries is recommended for real-world applications, implementing such algorithms manually is an excellent educational exercise.
If you have any questions or need further assistance with specific parts of the implementation, feel free to ask!