Update Linear.py
Browse files
Linear.py
CHANGED
|
@@ -1,50 +1,51 @@
|
|
| 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 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
self.
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
self.
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
self.
|
| 29 |
-
self.
|
| 30 |
-
self.
|
| 31 |
-
self.
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
return output
|
|
|
|
| 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 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
class linear_regression():
|
| 8 |
+
def __init__(self, fit_intercept = True):
|
| 9 |
+
self.const = fit_intercept
|
| 10 |
+
|
| 11 |
+
def fit(self, x, y):
|
| 12 |
+
if self.const ==1:
|
| 13 |
+
z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
|
| 14 |
+
self.index = x.columns.insert(0,'const')
|
| 15 |
+
else:
|
| 16 |
+
z = x
|
| 17 |
+
self.index = x.columns
|
| 18 |
+
self.phi = np.linalg.inv(z.T @ z) @ (z.T @ y)
|
| 19 |
+
if self.const == 1:
|
| 20 |
+
self.intercept_ = self.phi[0]
|
| 21 |
+
self.coef_ = self.phi[1:]
|
| 22 |
+
else:
|
| 23 |
+
self.intercept_ = 'NA'
|
| 24 |
+
self.coef_ = self.phi
|
| 25 |
+
u = y - z @ self.phi
|
| 26 |
+
RSS = np.sum(u**2)
|
| 27 |
+
TSS = np.sum((y - np.mean(y))**2)
|
| 28 |
+
self.R2 = 1 - RSS/TSS
|
| 29 |
+
self.s2 = RSS/(z.shape[0] - z.shape[1])
|
| 30 |
+
self.SE = np.sqrt(self.s2 * np.diagonal(np.linalg.inv(z.T @ z)))
|
| 31 |
+
self.t = self.phi/self.SE
|
| 32 |
+
self.p = (1 - t.cdf(abs(self.t), df = z.shape[0] - z.shape[1]))*2
|
| 33 |
+
|
| 34 |
+
def predict(self, x):
|
| 35 |
+
if self.const ==1:
|
| 36 |
+
z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
|
| 37 |
+
else:
|
| 38 |
+
z = x
|
| 39 |
+
fcst = z @ self.phi
|
| 40 |
+
return fcst.squeeze()
|
| 41 |
+
|
| 42 |
+
def summary(self):
|
| 43 |
+
"""
|
| 44 |
+
summaryの出力
|
| 45 |
+
:return: summary dataframe
|
| 46 |
+
"""
|
| 47 |
+
col_names = ["coef", "se", "t", "両側p値"]
|
| 48 |
+
output = pd.DataFrame(np.c_[self.phi, self.SE, self.t, self.p],
|
| 49 |
+
index=self.index,
|
| 50 |
+
columns=col_names)
|
| 51 |
return output
|