Skip to content

Instantly share code, notes, and snippets.

@Chiraagkv
Last active January 11, 2022 13:51
Show Gist options
  • Save Chiraagkv/4f6001371cb7d921717b9d3521de50ce to your computer and use it in GitHub Desktop.
Save Chiraagkv/4f6001371cb7d921717b9d3521de50ce to your computer and use it in GitHub Desktop.
import numpy as np
class LinearRegressor():
def __init__(self):
self.θ0 = np.random.random((1,))[0]
self.θ1 = np.random.random((1,))[0]
def predict(self, x):
return self.θ0 + self.θ1 * np.array(x)
def compute_loss(self, y_preds, y_true):
return (sum((y_preds - y_true) ** 2)) / len(y_preds)
def fit(self, x, y, epochs, learning_rate=0.001, seed=42):
np.random.seed(seed)
θ0, θ1 = np.random.random((2,))
for i in range(1, epochs+1):
y_preds = self.predict(x)
self.θ0 = θ0 - learning_rate * (2 / len(y)) * sum(y_preds - y)
self.θ1 = θ1 - learning_rate * sum((y_preds - y) * x)
print(f"Epoch {i}:\nLoss: {round(self.compute_loss(y_preds, y), 4)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment