-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleLinearRegression.py
84 lines (63 loc) · 2.99 KB
/
SimpleLinearRegression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import numpy as np
from .metrics import r2_score
class SimpleLinearRegression1():
def __init__(self):
"""初始化 Single Linear Regression 的方法"""
self.a_ = None
self.b_ = None
def fit(self, x_train, y_train):
"""根据训练集x_train y_train训练得到SimpleLinearRegression1的模型"""
assert x_train.ndim == 1, "the Simple Linear Regression can only solve single feature training data"
assert len(x_train) == len(y_train), "the size of x_train must be equal to the size of y_train"
x_mean = np.mean(x_train)
y_mean = np.mean(y_train)
up = 0.0
down = 0.0
for x_i, y_i in zip(x_train, y_train):
up += (x_i - x_mean) * (y_i - y_mean)
down += (x_i - x_mean) ** 2
self.a_ = up / down
self.b_ = y_mean - self.a_ * x_mean
return self
def predict(self, x_test):
"""通过训练好的SimpleLinearRegression1模型计算得到x_test的预测值"""
assert x_test.ndim == 1, "the Simple Linear Regression can only solve single feature test data"
assert self.a_ is not None and self.b_ is not None, "must fit before predict"
y_predict = [self._predict(x) for x in x_test]
return np.array(y_predict)
def _predict(self, x):
"""对给定的单个待预测数据x,返回预测结果值"""
return self.a_ * x + self.b_
def __repr__(self):
return "SimpleLinearRegression1()"
class SimpleLinearRegression2():
def __init__(self):
"""初始化 Single Linear Regression 的方法"""
self.a_ = None
self.b_ = None
def fit(self, x_train, y_train):
"""根据训练集x_train y_train训练得到SimpleLinearRegression1的模型"""
assert x_train.ndim == 1, "the Simple Linear Regression can only solve single feature training data"
assert len(x_train) == len(y_train), "the size of x_train must be equal to the size of y_train"
x_mean = np.mean(x_train)
y_mean = np.mean(y_train)
up = (x_train - x_mean).dot(y_train - y_mean)
down = (x_train - x_mean).dot(x_train - x_mean)
self.a_ = up / down
self.b_ = y_mean - self.a_ * x_mean
return self
def predict(self, x_test):
"""通过训练好的SimpleLinearRegression1模型计算得到x_test的预测值"""
assert x_test.ndim == 1, "the Simple Linear Regression can only solve single feature test data"
assert self.a_ is not None and self.b_ is not None, "must fit before predict"
y_predict = [self._predict(x) for x in x_test]
return np.array(y_predict)
def score(self, x_test, y_test):
"""根据y_test和y_predict计算R2值"""
y_predict = self.predict(x_test)
return r2_score(y_test, y_predict)
def _predict(self, x):
"""对给定的单个待预测数据x,返回预测结果值"""
return self.a_ * x + self.b_
def __repr__(self):
return "SimpleLinearRegression2()"