This repository has been archived by the owner on Jun 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_reg.py
211 lines (202 loc) · 6.96 KB
/
linear_reg.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import scipy
import matplotlib.pyplot as plt
import base64
from io import BytesIO
from sourceCode.func import create_t_figure
from sourceCode.func import create_p_figure
from sourceCode.func import create_b_figure
import platform
def getAns(dependent: str, independent: list, session: dict) -> dict:
"""get p-value, f-value, R-square etc."""
reg = LinearRegression()
filename = session["filename"]
data = pd.read_csv(filename)
ans = {}
try:
ys = data[dependent].values
xs = data[independent].values
reg.fit(xs, ys)
ans["var"] = [dependent, "Constant"] + independent
n = len(ys)
k = len(independent) + 1
tmp = np.append(reg.intercept_, reg.coef_).tolist()
ans["coefficient"] = [np.round(i, 4) for i in tmp]
ans["R-squared"] = np.round(reg.score(xs, ys), 4)
ans["Adjusted R-squared"] = np.round(
1 - (1 - ans["R-squared"]) * (n - 1) / (n - k), 4)
try:
ans["F-value"] = np.round(
ans["R-squared"] / (1 - ans["R-squared"]) * (n - k) / (k - 1),
4)
except ZeroDivisionError:
ans["F-value"] = 999999
ans["SS"] = {}
tmp = sum((ys - ys.mean())**2)
ans["observation"] = n
ans["df"] = k
ans["SS"]["ESS"] = np.round(tmp * ans["R-squared"], 4)
ans["SS"]["RSS"] = np.round(tmp - ans["SS"]["ESS"], 4)
ans["Prob>F"] = np.round(
scipy.stats.f.sf(ans["F-value"], k - 1, n - k), 4)
ans["Root MSE"] = np.round((ans["SS"]["RSS"] / (n - k))**0.5, 4)
sigma_square = ans["SS"]["RSS"] / (n - k)
one = np.ones(n)
xs = np.insert(xs, 0, values=one, axis=1)
tmp = np.dot(xs.T, xs)
var_cov_beta = sigma_square * np.linalg.inv(tmp)
tmp = np.sqrt(var_cov_beta.diagonal()).tolist()
ans["stderr"] = [np.round(i, 4) for i in tmp]
try:
ans["t"] = [
np.round(ans["coefficient"][i] / ans["stderr"][i], 4)
for i in range(k)
]
except ZeroDivisionError:
ans["t"] = 9999999
ans["P>|t|"] = [
np.round(scipy.stats.t.sf(i, n - k), 4) for i in ans["t"]
]
ans["flag"] = 1
return ans
except:
ans["flag"] = 0
session["error"] = "please check your data"
return ans
def format_(x):
return str(x).rjust(10, ' ')
def showAns(dependent: str, ans: dict, session: dict) -> str:
"""turn to html pages"""
if ans["flag"] == 1:
username = session["username"]
if platform.system() == "windows":
csvfile = open(".\\static\\{}\\downloads\\ans.csv".format(username),
"w",
encoding="utf-8")
else:
csvfile = open("./static/{}/downloads/ans.csv".format(username),
"w",
encoding="utf-8")
print("dependent variable: ", dependent, file=csvfile)
print("variables,Coefficients,Standard Errors,t values,Probabilities",
file=csvfile)
for i in range(ans["df"]):
print(ans["var"][i + 1],
ans["coefficient"][i],
ans["stderr"][i],
ans["t"][i],
ans["P>|t|"][i],
sep=',',
file=csvfile)
csvfile.close()
html = """
<table border="1" style="width: 600px;">
<tr align="middle">
<td>
Source
</td>
<td>SS</td>
<td>df</td>
<td>MS</td>
</tr>
<tr align="right">
<td>Model</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
<tr align="right">
<td>Residual</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
<tr align="right">
<td>Total</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
</table>
""".format(
format_(ans["SS"]["ESS"]), format_(ans["df"] - 1),
format_(np.round(ans["SS"]["ESS"] / (ans["df"] - 1), 4)),
format_(ans["SS"]["RSS"]), format_(ans["observation"] - ans["df"]),
format_(
np.round(ans["SS"]["RSS"] / (ans["observation"] - ans["df"]),
4)), format_(ans["SS"]["ESS"] + ans["SS"]["RSS"]),
format_(ans["observation"] - 1),
format_(
np.round((ans["SS"]["ESS"] + ans["SS"]["RSS"]) /
(ans["observation"] - 1), 4)))
html += """
<table style="width: 600px;">
<tr>
<td align="left">
Number of obs
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
<tr>
<td align="left">
F({},{})
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
<tr>
<td align="left">
Prob>F
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
<tr>
<td align="left">
R-square
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
<tr>
<td align="left">
Adj R-square
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
<tr>
<td align="left">
Root MSE
</td>
<td align="middle">=</td>
<td align="right">{}</td>
</tr>
</table><table style="width:600px;" border="1">
""".format(str(ans["observation"]), str(ans["df"] - 1),
str(ans["observation"] - ans["df"]), str(ans["F-value"]),
str(ans["Prob>F"]), str(ans["R-squared"]),
str(ans["Adjusted R-squared"]), str(ans["Root MSE"]))
for i in range(len(ans["var"])):
if i == 0:
html += """<tr><td>{}</td><td>Coef.</td><td>Std. Err.</td><td>t</td><td> P>|t| </td></tr>""".format(
ans["var"][0])
else:
html += """<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>""".format(
ans["var"][i], ans["coefficient"][i - 1],
ans["stderr"][i - 1], ans["t"][i - 1], ans["P>|t|"][i - 1])
return html + "</table>"
return """linear_reg may not suit"""
def showFigure(ans: dict) -> dict:
if ans["flag"] == 1:
tmp = {}
tmp["tvalue"] = create_t_figure(ans)
tmp["bvalue"] = create_b_figure(ans)
tmp["pvalue"] = create_p_figure(ans)
return tmp
return {}
if __name__ == "__main__":
pass