Yinxing commited on
Commit
99591c6
·
verified ·
1 Parent(s): 1b07538

Update Linear.py

Browse files
Files changed (1) hide show
  1. Linear.py +56 -36
Linear.py CHANGED
@@ -6,47 +6,67 @@ import numpy as np
6
  import pandas as pd
7
 
8
  class linear_regression():
9
- def __init__(self, fit_intercept = True):
10
- self.const = fit_intercept
11
 
12
  def fit(self, x, y):
13
- if self.const ==1:
14
- z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
15
- self.index = x.columns.insert(0,'const')
16
- else:
17
- z = x
18
- self.index = x.columns
19
- self.phi = np.linalg.inv(z.T @ z) @ (z.T @ y)
20
- if self.const == 1:
21
- self.intercept_ = self.phi[0]
22
- self.coef_ = self.phi[1:]
23
- else:
24
- self.intercept_ = 'NA'
25
- self.coef_ = self.phi
26
- u = y - z @ self.phi
27
- RSS = np.sum(u**2)
28
- TSS = np.sum((y - np.mean(y))**2)
29
- self.R2 = 1 - RSS/TSS
30
- self.s2 = RSS/(z.shape[0] - z.shape[1])
31
- self.SE = np.sqrt(self.s2 * np.diagonal(np.linalg.inv(z.T @ z)))
32
- self.t = self.phi/self.SE
33
- self.p = (1 - t.cdf(abs(self.t), df = z.shape[0] - z.shape[1]))*2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  def predict(self, x):
36
- if self.const ==1:
37
- z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
38
- else:
39
- z = x
40
- fcst = z @ self.phi
41
- return fcst.squeeze()
 
 
 
 
 
 
42
 
43
  def summary(self):
44
- """
45
- summaryの出力
46
- :return: summary dataframe
47
- """
48
- col_names = ["coef", "se", "t", "両側p値"]
49
- output = pd.DataFrame(np.c_[self.phi, self.SE, self.t, self.p],
50
  index=self.index,
51
  columns=col_names)
52
- return output
 
 
6
  import pandas as pd
7
 
8
  class linear_regression():
9
+ def __init__(self, fit_intercept=True):
10
+ self.const = fit_intercept
11
 
12
  def fit(self, x, y):
13
+ # pandas DataFrame → numpy配列に変換
14
+ if isinstance(x, pd.DataFrame):
15
+ x_np = x.values
16
+ x_cols = x.columns
17
+ else:
18
+ x_np = x
19
+ x_cols = [f"x{i}" for i in range(x.shape[1])]
20
+
21
+ # yがSeriesかDataFrameかに関係なく1列の配列にする
22
+ if isinstance(y, (pd.Series, pd.DataFrame)):
23
+ y_np = np.asarray(y).reshape(-1, 1)
24
+ else:
25
+ y_np = y.reshape(-1, 1)
26
+
27
+ if self.const:
28
+ ones = np.ones((x_np.shape[0], 1))
29
+ z = np.concatenate([ones, x_np], axis=1)
30
+ self.index = ['const'] + list(x_cols)
31
+ else:
32
+ z = x_np
33
+ self.index = list(x_cols)
34
+
35
+ self.phi = np.linalg.inv(z.T @ z) @ (z.T @ y_np)
36
+ if self.const:
37
+ self.intercept_ = self.phi[0, 0]
38
+ self.coef_ = self.phi[1:].flatten()
39
+ else:
40
+ self.intercept_ = 'NA'
41
+ self.coef_ = self.phi.flatten()
42
+
43
+ u = y_np - z @ self.phi
44
+ RSS = np.sum(u**2)
45
+ TSS = np.sum((y_np - np.mean(y_np))**2)
46
+ self.R2 = 1 - RSS / TSS
47
+ self.s2 = RSS / (z.shape[0] - z.shape[1])
48
+ self.SE = np.sqrt(self.s2 * np.diagonal(np.linalg.inv(z.T @ z)))
49
+ self.t = self.phi.flatten() / self.SE
50
+ self.p = (1 - t.cdf(np.abs(self.t), df=z.shape[0] - z.shape[1])) * 2
51
 
52
  def predict(self, x):
53
+ if isinstance(x, pd.DataFrame):
54
+ x_np = x.values
55
+ else:
56
+ x_np = x
57
+
58
+ if self.const:
59
+ z = np.concatenate([np.ones((x_np.shape[0], 1)), x_np], axis=1)
60
+ else:
61
+ z = x_np
62
+
63
+ fcst = z @ self.phi
64
+ return fcst.squeeze()
65
 
66
  def summary(self):
67
+ col_names = ["coef", "se", "t", "両側p値"]
68
+ output = pd.DataFrame(np.c_[self.phi.flatten(), self.SE, self.t, self.p],
 
 
 
 
69
  index=self.index,
70
  columns=col_names)
71
+ print(f'決定係数R^2: {self.R2}')
72
+ return output