Created
June 24, 2024 00:35
-
-
Save GaryLee/6f9de7586997d90f7ad18e6555343380 to your computer and use it in GitHub Desktop.
Simple linear regression example using least square root for solution.
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 | |
def linear_regression(x, y): | |
"""The input are x and y for 2D""" | |
assert isinstance(x, np.ndarray) | |
assert isinstance(y, np.ndarray) | |
w = np.sum((y - np.average(y)) * x) / np.sum((x - np.average(x))**2) | |
b = np.average(y) - w * np.average(x) | |
return w, b | |
if __name__ == '__main__': | |
w0 = 23.5 | |
b0 = 12.5 | |
print(f'{w0=}, {b0=}') | |
x = np.linspace(1, 100, 50) | |
y = x * w0 + b0 | |
w1, b1 = linear_regression(x, y) | |
print(f'{w1=}, {b1=}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment