LLM_Dataset / Linear.py
Yinxing's picture
Upload Linear.py
e7c5e73 verified
raw
history blame
1.66 kB
#sk-learn風の線形回帰分析クラス
#SE, t-val,p-val, R2を出力
#x, yをpandas DataFrameで入力、self.olsは(coef, SE, t値, p値)のDataFrame
from scipy.stats import t
class linear_regression():
def __init__(self, fit_intercept = True):
self.const = fit_intercept
def fit(self, x, y):
if self.const ==1:
z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
self.index = x.columns.insert(0,'const')
else:
z = x
self.index = x.columns
self.phi = np.linalg.inv(z.T @ z) @ (z.T @ y)
if self.const == 1:
self.intercept_ = self.phi[0]
self.coef_ = self.phi[1:]
else:
self.intercept_ = 'NA'
self.coef_ = self.phi
u = y - z @ self.phi
RSS = np.sum(u**2)
TSS = np.sum((y - np.mean(y))**2)
self.R2 = 1 - RSS/TSS
self.s2 = RSS/(z.shape[0] - z.shape[1])
self.SE = np.sqrt(self.s2 * np.diagonal(np.linalg.inv(z.T @ z)))
self.t = self.phi/self.SE
self.p = (1 - t.cdf(abs(self.t), df = z.shape[0] - z.shape[1]))*2
def predict(self, x):
if self.const ==1:
z = np.concatenate([np.ones((x.shape[0],1)), x], axis=1)
else:
z = x
fcst = z @ self.phi
return fcst.squeeze()
def summary(self):
"""
summaryの出力
:return: summary dataframe
"""
col_names = ["coef", "se", "t", "両側p値"]
output = pd.DataFrame(np.c_[self.phi, self.SE, self.t, self.p],
index=self.index,
columns=col_names)
return output