Skip to content

Instantly share code, notes, and snippets.

@nguyenhaidang94
Last active April 10, 2022 13:05
Show Gist options
  • Save nguyenhaidang94/0fd64f44488b978bf95e6ba303309592 to your computer and use it in GitHub Desktop.
Save nguyenhaidang94/0fd64f44488b978bf95e6ba303309592 to your computer and use it in GitHub Desktop.
Implement linear regression
import numpy as np
from .base import BaseModel
from .helper import pinv
class LinearRegression(BaseModel):
def __init__(self):
self._beta = None
def train(self, X: np.ndarray, y: np.ndarray):
# account for the bias
X = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
# use Moore-Penrose inverse to make sure that matrix always has inverse
self._beta = pinv(X.T @ X) @ X.T @ y
def predict(self, X: np.ndarray):
X = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1)
return np.dot(X, self._beta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment