Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train_reg.py 11 KB

You have to be logged in to leave a comment. Sign In
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
  1. import os
  2. import pickle as pkl
  3. from os.path import join as oj
  4. import numpy as np
  5. import pandas as pd
  6. from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
  7. from sklearn.linear_model import LinearRegression, RidgeCV
  8. from sklearn.metrics import r2_score
  9. from sklearn.model_selection import KFold
  10. from sklearn.neural_network import MLPRegressor
  11. from sklearn.svm import SVR
  12. from sklearn.tree import DecisionTreeRegressor
  13. from statsmodels import robust
  14. import features
  15. import data
  16. import config
  17. from tqdm import tqdm
  18. from scipy.stats import pearsonr, kendalltau
  19. from neural_networks import neural_net_sklearn
  20. #cell_nums_train = np.array([1, 2, 3, 4, 5])
  21. #cell_nums_test = np.array([6])
  22. def add_robust_features(df):
  23. df['X_95_quantile'] = np.array([np.quantile(df.iloc[i].X, 0.95) for i in range(len(df))])
  24. df['X_mad'] = np.array([robust.mad(df.iloc[i].X) for i in range(len(df))])
  25. return df
  26. def log_transforms(df):
  27. df = add_robust_features(df)
  28. df['X_max_log'] = np.log(df['X_max'])
  29. df['X_95_quantile_log'] = np.log(df['X_95_quantile'] + 1)
  30. df['Y_max_log'] = np.log(df['Y_max'])
  31. df['X_mad_log'] = np.log(df['X_mad'])
  32. def calc_rise_log(x):
  33. idx_max = np.argmax(x)
  34. val_max = x[idx_max]
  35. rise = np.log(val_max) - np.log(abs(np.min(x[:idx_max + 1])) + 1) # max change before peak
  36. return rise
  37. def calc_fall_log(x):
  38. idx_max = np.argmax(x)
  39. val_max = x[idx_max]
  40. fall = np.log(val_max) - np.log(abs(np.min(x[idx_max:])) + 1) # drop after peak
  41. return fall
  42. df['rise_log'] = np.array([calc_rise_log(df.iloc[i].X) for i in range(len(df))])
  43. df['fall_log'] = np.array([calc_fall_log(df.iloc[i].X) for i in range(len(df))])
  44. num = 3
  45. df['rise_local_3_log'] = df.apply(lambda row:
  46. calc_rise_log(np.array(row['X'][max(0, row['X_peak_idx'] - num):
  47. row['X_peak_idx'] + num + 1])),
  48. axis=1)
  49. df['fall_local_3_log'] = df.apply(lambda row:
  50. calc_fall_log(np.array(row['X'][max(0, row['X_peak_idx'] - num):
  51. row['X_peak_idx'] + num + 1])),
  52. axis=1)
  53. num2 = 11
  54. df['rise_local_11_log'] = df.apply(lambda row:
  55. calc_rise_log(np.array(row['X'][max(0, row['X_peak_idx'] - num2):
  56. row['X_peak_idx'] + num2 + 1])),
  57. axis=1)
  58. df['fall_local_11_log'] = df.apply(lambda row:
  59. calc_fall_log(np.array(row['X'][max(0, row['X_peak_idx'] - num2):
  60. row['X_peak_idx'] + num2 + 1])),
  61. axis=1)
  62. return df
  63. def train_reg(df,
  64. feat_names,
  65. model_type='rf',
  66. outcome_def='Y_max_log',
  67. out_name='results/regression/test.pkl',
  68. seed=42,
  69. **kwargs):
  70. '''
  71. train regression model
  72. hyperparameters of model can be specified using **kwargs
  73. '''
  74. np.random.seed(seed)
  75. X = df[feat_names]
  76. # X = (X - X.mean()) / X.std() # normalize the data
  77. y = df[outcome_def].values
  78. if model_type == 'rf':
  79. m = RandomForestRegressor(n_estimators=100)
  80. elif model_type == 'dt':
  81. m = DecisionTreeRegressor()
  82. elif model_type == 'linear':
  83. m = LinearRegression()
  84. elif model_type == 'ridge':
  85. m = RidgeCV()
  86. elif model_type == 'svm':
  87. m = SVR(gamma='scale')
  88. elif model_type == 'gb':
  89. m = GradientBoostingRegressor()
  90. elif model_type == 'irf':
  91. m = irf.ensemble.wrf()
  92. elif 'nn' in model_type: # neural nets
  93. """
  94. train fully connected neural network
  95. """
  96. H = kwargs['fcnn_hidden_neurons'] if 'fcnn_hidden_neurons' in kwargs else 40
  97. epochs = kwargs['fcnn_epochs'] if 'fcnn_epochs' in kwargs else 1000
  98. batch_size = kwargs['fcnn_batch_size'] if 'fcnn_batch_size' in kwargs else 1000
  99. track_name = kwargs['track_name'] if 'track_name' in kwargs else 'X_same_length'
  100. D_in = len(df[track_name].iloc[0])
  101. m = neural_net_sklearn(D_in=D_in,
  102. H=H,
  103. p=len(feat_names)-1,
  104. epochs=epochs,
  105. batch_size=batch_size,
  106. track_name=track_name,
  107. arch=model_type)
  108. # scores_cv = {s: [] for s in scorers.keys()}
  109. # scores_test = {s: [] for s in scorers.keys()}
  110. imps = {'model': [], 'imps': []}
  111. cell_nums_train = np.array(list(set(df.cell_num.values)))
  112. kf = KFold(n_splits=len(cell_nums_train))
  113. # split testing data based on cell num
  114. #idxs_test = df.cell_num.isin(cell_nums_test)
  115. #idxs_train = df.cell_num.isin(cell_nums_train)
  116. #X_test, Y_test = X[idxs_test], y[idxs_test]
  117. num_pts_by_fold_cv = []
  118. y_preds = {}
  119. cv_score = []
  120. cv_pearsonr = []
  121. print("Looping over cv...")
  122. # loops over cv, where test set order is cell_nums_train[0], ..., cell_nums_train[-1]
  123. for cv_idx, cv_val_idx in tqdm(kf.split(cell_nums_train)):
  124. # get sample indices
  125. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  126. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  127. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  128. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  129. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  130. # resample training data
  131. # fit
  132. m.fit(X_train_cv, Y_train_cv)
  133. # get preds
  134. preds = m.predict(X_val_cv)
  135. y_preds[cell_nums_train[np.array(cv_val_idx)][0]] = preds
  136. if 'log' in outcome_def:
  137. cv_score.append(r2_score(np.exp(Y_val_cv), np.exp(preds)))
  138. cv_pearsonr.append(pearsonr(np.exp(Y_val_cv), np.exp(preds))[0])
  139. else:
  140. print(r2_score(Y_val_cv, preds))
  141. cv_score.append(r2_score(Y_val_cv, preds))
  142. cv_pearsonr.append(pearsonr(Y_val_cv, preds)[0])
  143. print("Training with full data...")
  144. # cv_score = cv_score/len(cell_nums_train)
  145. m.fit(X, y)
  146. #print(cv_score)
  147. #test_preds = m.predict(X_test)
  148. results = {'y_preds': y_preds,
  149. 'y': y,
  150. 'model_state_dict': m.model.state_dict(),
  151. #'test_preds': test_preds,
  152. 'cv': {'r2': cv_score, 'pearsonr': cv_pearsonr},
  153. 'model_type': model_type,
  154. #'model': m,
  155. 'num_pts_by_fold_cv': np.array(num_pts_by_fold_cv),
  156. }
  157. if model_type in ['rf', 'linear', 'ridge', 'gb', 'svm', 'irf']:
  158. results['model'] = m
  159. # save results
  160. # os.makedirs(out_dir, exist_ok=True)
  161. pkl.dump(results, open(out_name, 'wb'))
  162. def load_results(out_dir, by_cell=True):
  163. r = []
  164. for fname in os.listdir(out_dir):
  165. if os.path.isdir(oj(out_dir, fname)):
  166. continue
  167. d = pkl.load(open(oj(out_dir, fname), 'rb'))
  168. metrics = {k: d['cv'][k] for k in d['cv'].keys() if not 'curve' in k}
  169. num_pts_by_fold_cv = d['num_pts_by_fold_cv']
  170. print(metrics)
  171. out = {k: np.average(metrics[k], weights=num_pts_by_fold_cv) for k in metrics}
  172. if by_cell:
  173. out.update({'cv_accuracy_by_cell': metrics['r2']})
  174. out.update({k + '_std': np.std(metrics[k]) for k in metrics})
  175. out['model_type'] = fname.replace('.pkl', '') # d['model_type']
  176. print(d['cv'].keys())
  177. # imp_mat = np.array(d['imps']['imps'])
  178. # imp_mu = imp_mat.mean(axis=0)
  179. # imp_sd = imp_mat.std(axis=0)
  180. # feat_names = d['feat_names_selected']
  181. # out.update({feat_names[i] + '_f': imp_mu[i] for i in range(len(feat_names))})
  182. # out.update({feat_names[i]+'_std_f': imp_sd[i] for i in range(len(feat_names))})
  183. r.append(pd.Series(out))
  184. r = pd.concat(r, axis=1, sort=False).T.infer_objects()
  185. r = r.reindex(sorted(r.columns), axis=1) # sort the column names
  186. r = r.round(3)
  187. r = r.set_index('model_type')
  188. return r
  189. def load_and_train(dset, outcome_def, out_dir, feat_names=None, use_processed=True):
  190. df = pd.read_pickle(f'../data/tracks/tracks_{dset}.pkl')
  191. if dset == 'clath_aux_dynamin':
  192. df = df[df.catIdx.isin([1, 2])]
  193. df = df[df.lifetime > 15]
  194. else:
  195. df = df[df['valid'] == 1]
  196. df = features.add_basic_features(df)
  197. df = log_transforms(df)
  198. df = add_sig_mean(df)
  199. df_train = df[df.cell_num.isin(config.DSETS[dset]['train'])]
  200. df_test = df[df.cell_num.isin(config.DSETS[dset]['test'])]
  201. df_train = df_train.dropna()
  202. #outcome_def = 'Z_sig_mean'
  203. #out_dir = 'results/regression/Sep15'
  204. os.makedirs(out_dir, exist_ok=True)
  205. if not feat_names:
  206. feat_names = data.get_feature_names(df_train)
  207. feat_names = [x for x in feat_names
  208. if not x.startswith('sc_')
  209. and not x.startswith('nmf_')
  210. and not x in ['center_max', 'left_max', 'right_max', 'up_max', 'down_max',
  211. 'X_max_around_Y_peak', 'X_max_after_Y_peak']
  212. and not x.startswith('pc_')
  213. and not 'log' in x
  214. and not 'binary' in x
  215. # and not 'slope' in x
  216. ]
  217. for model_type in tqdm(['linear', 'gb', 'rf', 'svm', 'ridge']):
  218. out_name = f'{model_type}'
  219. #print(out_name)
  220. if use_processed and os.path.exists(f'{out_dir}/{out_name}.pkl'):
  221. continue
  222. train_reg(df_train, feat_names=feat_names, model_type=model_type,
  223. outcome_def=outcome_def,
  224. out_name=f'{out_dir}/{out_name}.pkl')
  225. def test_reg(df,
  226. model,
  227. feat_names=None,
  228. outcome_def='Y_max_log',
  229. out_name='results/regression/test.pkl',
  230. seed=42):
  231. np.random.seed(seed)
  232. if not feat_names:
  233. feat_names = data.get_feature_names(df)
  234. feat_names = [x for x in feat_names
  235. if not x.startswith('sc_')
  236. and not x.startswith('nmf_')
  237. and not x in ['center_max', 'left_max', 'right_max', 'up_max', 'down_max',
  238. 'X_max_around_Y_peak', 'X_max_after_Y_peak']
  239. and not x.startswith('pc_')
  240. and not 'log' in x
  241. and not 'binary' in x
  242. # and not 'slope' in x
  243. ]
  244. X = df[feat_names]
  245. # X = (X - X.mean()) / X.std() # normalize the data
  246. test_preds = model.predict(X)
  247. results = {'preds': test_preds}
  248. if outcome_def in df.keys():
  249. y = df[outcome_def].values
  250. results['r2'] = r2_score(y, test_preds)
  251. results['pearsonr'] = pearsonr(y, test_preds)
  252. results['kendalltau'] = kendalltau(y, test_preds)
  253. return results
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...