Yinxing commited on
Commit
e7c5e73
·
verified ·
1 Parent(s): 8de51b0

Upload Linear.py

Browse files
Files changed (1) hide show
  1. Linear.py +50 -0
Linear.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #sk-learn風の線形回帰分析クラス
2
+ #SE, t-val,p-val, R2を出力
3
+ #x, yをpandas DataFrameで入力、self.olsは(coef, SE, t値, p値)のDataFrame
4
+ from scipy.stats import t
5
+
6
+ class linear_regression():
7
+ def __init__(self, fit_intercept = True):
8
+ self.const = fit_intercept
9
+
10
+ def fit(self, x, y):
11
+ if self.const ==1:
12
+ z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
13
+ self.index = x.columns.insert(0,'const')
14
+ else:
15
+ z = x
16
+ self.index = x.columns
17
+ self.phi = np.linalg.inv(z.T @ z) @ (z.T @ y)
18
+ if self.const == 1:
19
+ self.intercept_ = self.phi[0]
20
+ self.coef_ = self.phi[1:]
21
+ else:
22
+ self.intercept_ = 'NA'
23
+ self.coef_ = self.phi
24
+ u = y - z @ self.phi
25
+ RSS = np.sum(u**2)
26
+ TSS = np.sum((y - np.mean(y))**2)
27
+ self.R2 = 1 - RSS/TSS
28
+ self.s2 = RSS/(z.shape[0] - z.shape[1])
29
+ self.SE = np.sqrt(self.s2 * np.diagonal(np.linalg.inv(z.T @ z)))
30
+ self.t = self.phi/self.SE
31
+ self.p = (1 - t.cdf(abs(self.t), df = z.shape[0] - z.shape[1]))*2
32
+
33
+ def predict(self, x):
34
+ if self.const ==1:
35
+ z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
36
+ else:
37
+ z = x
38
+ fcst = z @ self.phi
39
+ return fcst.squeeze()
40
+
41
+ def summary(self):
42
+ """
43
+ summaryの出力
44
+ :return: summary dataframe
45
+ """
46
+ col_names = ["coef", "se", "t", "両側p値"]
47
+ output = pd.DataFrame(np.c_[self.phi, self.SE, self.t, self.p],
48
+ index=self.index,
49
+ columns=col_names)
50
+ return output