Last active
April 10, 2022 13:05
-
-
Save nguyenhaidang94/0fd64f44488b978bf95e6ba303309592 to your computer and use it in GitHub Desktop.
Implement linear regression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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