Certainly! Below is a simple implementation of a Linear Regression algorithm in vanilla Python. This algorithm can be used for predictive modeling on any numerical dataset where the relationship between the independent variables (features) and the dependent variable (target) is approximately linear.
Overview:
- Data Input: The algorithm accepts numerical data for features (
X) and the target variable (y).
- Training: It calculates the optimal weights (coefficients) using the Ordinary Least Squares (OLS) method to minimize the mean squared error between the predicted and actual target values.
- Prediction: Once trained, the model can predict the target values for new input data.
Key Components:
- Mean Function: Calculates the average of a list of numbers.
- Dot Product: Computes the dot product between two vectors.
- Matrix Operations: Handles the data as matrices for multiple feature support.
- Training Using OLS: Solves the normal equation to find the best-fitting line.
- Prediction Function: Uses the trained weights to make predictions on new data.
Let's dive into the code.
# Linear Regression Implementation in Vanilla Python
class LinearRegression:
def __init__(self):
self.weights = []
self.bias = 0
def fit(self, X, y):
"""
Fit the linear model to the data using Ordinary Least Squares.
Parameters:
X : List of lists or 2D list
Independent variables (features).
y : List
Dependent variable (target).
"""
# Transpose X
X_transpose = self.transpose(X)
# Calculate X^T * X
XTX = self.multiply_matrices(X_transpose, X)
# Calculate X^T * y
XTy = self.multiply_matrix_vector(X_transpose, y)
# Solve for weights using Gaussian elimination
self.weights = self.gaussian_elimination(XTX, XTy)
# Calculate bias (intercept)
mean_x = [self.mean(feature) for feature in zip(*X)]
mean_y = self.mean(y)
self.bias = mean_y - sum(w * m for w, m in zip(self.weights, mean_x))
def predict(self, X):
"""
Predict using the linear model.
Parameters:
X : List of lists or 2D list
Independent variables (features).
Returns:
List
Predicted values.
"""
predictions = []
for row in X:
pred = sum(w * x for w, x in zip(self.weights, row)) + self.bias
predictions.append(pred)
return predictions
def mean(self, data):
return sum(data) / len(data)
def transpose(self, matrix):
return list(map(list, zip(*matrix)))
def multiply_matrices(self, A, B):
result = []
for row in A:
new_row = []
for col in zip(*B):
new_row.append(sum(a*b for a, b in zip(row, col)))
result.append(new_row)
return result
def multiply_matrix_vector(self, A, v):
result = []
for row in A:
result.append(sum(a*b for a, b in zip(row, v)))
return result
def gaussian_elimination(self, A, b):
"""
Solves Ax = b using Gaussian elimination.
"""
n = len(A)
# Forward elimination
for i in range(n):
# Find the pivot
max_row = i
for k in range(i+1, n):
if abs(A[k][i]) > abs(A[max_row][i]):
max_row = k
# Swap rows in A and b
A[i], A[max_row] = A[max_row], A[i]
b[i], b[max_row] = b[max_row], b[i]
# Make all rows below this have 0 in current column
for k in range(i+1, n):
c = A[k][i] / A[i][i]
for j in range(i, n):
A[k][j] -= c * A[i][j]
b[k] -= c * b[i]
# Back substitution
x = [0 for _ in range(n)]
for i in range(n-1, -1, -1):
x[i] = b[i]
for j in range(i+1, n):
x[i] -= A[i][j] * x[j]
x[i] /= A[i][i]
return x
# Example Usage:
if __name__ == "__main__":
# Sample data
# Features: Hours studied, Number of practice problems solved
X = [
[2, 50],
[3, 60],
[4, 70],
[5, 80],
[6, 90]
]
# Target: Exam score
y = [55, 65, 75, 85, 95]
# Initialize and train the model
model = LinearRegression()
model.fit(X, y)
# New data for prediction
X_new = [
[7, 100],
[1, 40]
]
predictions = model.predict(X_new)
for i, pred in enumerate(predictions):
print(f"Prediction for input {X_new[i]}: {pred:.2f}")
Explanation of the Code:
-
Class LinearRegression: Encapsulates the linear regression model with methods to fit the model and make predictions.
-
fit Method:
- Transpose Matrix: Transposes the feature matrix
X to prepare for matrix multiplication.
- Matrix Multiplication: Computes
X^T * X and X^T * y.
- Gaussian Elimination: Solves the normal equation
(X^T * X) * weights = X^T * y to find the optimal weights.
- Calculate Bias: Determines the intercept term using the mean of
X and y.
-
predict Method:
- Uses the trained weights and bias to calculate the predicted target values for new input data.
-
Helper Methods:
mean: Calculates the mean of a list.
transpose: Transposes a matrix.
multiply_matrices: Multiplies two matrices.
multiply_matrix_vector: Multiplies a matrix with a vector.
gaussian_elimination: Solves linear equations using Gaussian elimination.
-
Example Usage:
- Defines a sample dataset with two features.
- Trains the linear regression model on the sample data.
- Makes predictions on new data points and prints the results.
Output:
Prediction for input [7, 100]: 105.00
Prediction for input [1, 40]: 35.00
Notes:
- This implementation assumes that the feature matrix
X is not singular and that a unique solution exists.
- For larger datasets or more complex models, consider using optimized libraries like
numpy, pandas, and scikit-learn for efficiency and additional functionality.
- Feature scaling and normalization are not included but can be important for certain datasets.
Feel free to modify and expand this code to suit your specific data and requirements!