-
Notifications
You must be signed in to change notification settings - Fork 1
/
linear_regression.py
executable file
·194 lines (168 loc) · 6.12 KB
/
linear_regression.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
import argparse
import pickle
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from sklearn import preprocessing, svm
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.linear_model import Lasso, LinearRegression
from sklearn.model_selection import train_test_split
def parse_arguments():
"""
Get command line arguments
"""
parser = argparse.ArgumentParser(
description='Analyze a fiwGAN on a given latent code c')
parser.add_argument(
'--latent_v_dir',
type=str,
help='Path to directory where latent variable is stored')
parser.add_argument('--s_dir',
type=str,
help='path to directory where s data is stored')
parser.add_argument('--job_id', type=str)
parser.add_argument('--output_dir', type=str)
args = parser.parse_args()
return vars(args)
if __name__ == '__main__':
args = parse_arguments()
latent_v_dir = args['latent_v_dir']
latent_v_dir = Path(latent_v_dir)
s_dir = args['s_dir']
s_dir = Path(s_dir)
output_dir = args['output_dir']
output_dir = Path(output_dir)
job_id = args['job_id']
vlist = []
for files in latent_v_dir.iterdir():
with open(latent_v_dir / files, 'rb') as out_data:
latent_v = pickle.load(out_data)
vlist.append(latent_v)
vlist = np.concatenate(vlist)
s_data = pd.read_csv(s_dir)
tf = np.array(s_data['nasal_coda'])
tf[tf > 0] = 1
slope = []
p_value = []
for i in range(vlist.shape[1]):
z = vlist[:, i]
z = z.reshape((*z.shape, 1))
#tf = tf.reshape((*tf.shape, 1))
#print(tf.shape)
X_train, X_test, y_train, y_test = train_test_split(
z,
tf,
test_size=0.5,
)
linreg = LinearRegression()
linreg.fit(X_train, y_train)
y_pred = linreg.predict(X_test)
# fig, ax = plt.subplots()
# plt.scatter(X_test, y_test, color='b')
# plt.plot(X_test, y_pred, color='k')
# plt.savefig(output_dir / job_id / f"{i}.png")
# plt.close()
#calculate the p value in linear regression & print out the table
newX = pd.DataFrame({
"Constant": np.ones(len(X_train))
}).join(pd.DataFrame(X_train))
MSE = (sum((y_train - y_pred)**2)) / (len(newX) - len(newX.columns))
params = np.append(linreg.intercept_, linreg.coef_)
var_b = MSE * (np.linalg.inv(np.dot(newX.T, newX)).diagonal())
sd_b = np.sqrt(var_b)
ts_b = params / sd_b
p_values = [
2 * (1 - stats.t.cdf(np.abs(i), (len(newX) - len(newX.columns))))
for i in ts_b
]
#print(f"p_values {p_values}")
#exit()
p_value.append(p_values)
sd_b = np.round(sd_b, 3)
ts_b = np.round(ts_b, 3)
p_values = np.round(p_values, 3)
params = np.round(params, 4)
#myDF3 = pd.DataFrame()
#myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilities"] = [params,sd_b,ts_b,p_values]
#print(myDF3)
#calculate the slope value
slopes = linreg.coef_[0]
absolute_slope = abs(slopes)
slope.append(absolute_slope)
#draw firguer for slope
slope = np.array(slope)
p_value = np.array(p_value)
p_value = p_value[:, 1]
ind_slope_pvalue = np.array([[i, slope[i], p_value[i]]
for i in range(len(slope))],
dtype=object)
ind_slope_pvalue = ind_slope_pvalue[np.argsort(ind_slope_pvalue[:, 1])]
plt.figure(figsize=(20, 4))
#plt.subplot(2, 1, 1)
plt.plot(ind_slope_pvalue[:, 1], label="slope", marker="o")
plt.xticks([i for i in range(len(slope))],
ind_slope_pvalue[:, 0].astype(int),
rotation=90)
plt.xlabel("latent variable")
plt.ylabel("slopes in absolute values (|β|)")
plt.legend()
# plt.subplot(2, 1, 2)
# plt.plot(ind_slope_pvalue[:, 2], label="p_value", marker="o")
# plt.xticks([i for i in range(len(slope))],
# ind_slope_pvalue[:, 0].astype(int),
# rotation=90)
# plt.xlabel("latent variable")
# plt.ylabel("p value")
# plt.legend()
plt.savefig(output_dir / job_id / f"slope.eps")
##draw figure for chi squre
chi_model = SelectKBest(chi2, k=2)
res_feaetures = chi_model.fit_transform(vlist - np.min(vlist), tf)
scores = chi_model.scores_
pvalues = chi_model.pvalues_
#indices = np.arange(len(scores))
ind_chi_p = np.array([[i, scores[i], pvalues[i]]
for i in range(len(scores))])
ind_chi_p = ind_chi_p[np.argsort(ind_chi_p[:, 1])]
plt.figure()
# fig=plt.figure(figsize=(20,8))
# plt.subplot(2, 1, 1)
# ax = fig.add_subplot(111)
# ax.yaxis.tick_right()
# ax.yaxis.set_label_position("right")
top_n = 7
mean_rest = np.mean(ind_chi_p[:-top_n, 1])
plt.plot([mean_rest] + [x for x in ind_chi_p[-top_n:, 1]],
label="scores",
marker="o")
plt.xticks(
[i for i in range(top_n + 1)],
["others"] + [x for x in ind_chi_p[-top_n:, 0].astype(int)],
rotation=90,
)
plt.errorbar(0,
np.mean(ind_chi_p[:-top_n, 1]),
yerr=np.std(ind_chi_p[:-top_n, 1]),
elinewidth=2,
capsize=3,
label=f"std_error_{np.std(ind_chi_p[:-top_n, 1]):0.2f}")
plt.xlabel("Latent Variable")
plt.ylabel("χ2")
plt.text(0, np.mean(ind_chi_p[:-top_n, 1]),
str(np.mean(ind_chi_p[:-top_n, 1])))
plt.legend()
plt.tight_layout()
# plt.subplot(2, 1, 2)
# plt.plot(ind_chi_p[:, 2], label="pvalues", marker="o")
# plt.xticks([i for i in range(len(scores))],
# ind_chi_p[:, 0].astype(int),
# rotation=90)
# plt.xlabel("latent variable")
# plt.ylabel("p value")
# plt.legend()
plt.savefig(output_dir / job_id / f"_05_linear_corr.eps")
plt.savefig(output_dir / job_id / f"_05_linear_corr.png")
#plt.show()
plt.close()