This repository has been archived on 2020-04-25. You can view files and clone it, but cannot push or open issues or pull requests.
ml/regression/SimpleLinearRegression.py

38 lines
611 B
Python
Raw Normal View History

2020-02-23 14:14:06 +00:00
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import numpy as np
def fitslr(x, y):
n = len(x)
din = 0
num = 0
avgX = np.mean(x)
avgY = np.mean(y)
for i in range(0, n):
num += (x[i] - avgX) * (y[i] - avgY)
din += (x[i] - avgX) ** 2
print "din:", din
print "num:", num
b1 = num / float(din)
b0 = avgY / float(avgX)
return b0, b1
def predict(x, b0, b1):
return b0 + x * b1
x = [1, 3, 2, 1, 3]
y = [14, 24, 18, 17, 27]
b0, b1 = fitslr(x, y)
print "intercept:", b0, "slope:", b1
x_test = 6
y_test = predict(6, b0, b1)
print "y_test", y_test