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.py 7.4 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
  1. import sys
  2. from sklearn.linear_model import LogisticRegression, Lasso
  3. from sklearn.neural_network import MLPClassifier
  4. from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier
  5. from sklearn.tree import DecisionTreeClassifier
  6. from sklearn.svm import SVC
  7. from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
  8. import eli5
  9. import numpy as np
  10. from copy import deepcopy
  11. from sklearn import metrics
  12. from sklearn.feature_selection import SelectFromModel
  13. from sklearn.calibration import CalibratedClassifierCV
  14. from imblearn.over_sampling import RandomOverSampler, SMOTE
  15. from sklearn.model_selection import KFold
  16. import pickle as pkl
  17. sys.path.append('lib')
  18. from sklearn.neighbors import KNeighborsClassifier as KNN
  19. scorers = {'balanced_accuracy': metrics.balanced_accuracy_score, 'accuracy': metrics.accuracy_score,
  20. 'precision': metrics.precision_score, 'recall': metrics.recall_score, 'f1': metrics.f1_score,
  21. 'roc_auc': metrics.roc_auc_score,
  22. 'precision_recall_curve': metrics.precision_recall_curve, 'roc_curve': metrics.roc_curve}
  23. def get_feature_importance(model, model_type, X_val, Y_val):
  24. if 'Calibrated' in str(type(model)):
  25. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  26. imps = perm.feature_importances_
  27. elif model_type in ['dt']:
  28. imps = model.feature_importances_
  29. elif model_type in ['rf', 'irf']:
  30. # imps, _ = feature_importance(model, np.array(X_val), np.transpose(np.vstack((Y_val, 1-Y_val))))
  31. imps = model.feature_importances_
  32. elif model_type == 'logistic':
  33. imps = model.coef_
  34. else:
  35. perm = eli5.sklearn.permutation_importance.PermutationImportance(model).fit(X_val, Y_val)
  36. imps = perm.feature_importances_
  37. return imps.squeeze()
  38. def balance(X, y, balancing='ros', balancing_ratio=1):
  39. '''Balance classes in y using strategy specified by balancing
  40. Params
  41. -----
  42. balancing_ratio: float
  43. ratio of pos: neg samples
  44. '''
  45. class0 = np.sum(y == 0)
  46. class1 = np.sum(y == 1)
  47. class_max = max(class0, class1)
  48. if balancing_ratio >= 1:
  49. sample_nums = {0: int(class_max), 1: int(class_max * balancing_ratio)}
  50. else:
  51. sample_nums = {0: int(class_max / balancing_ratio), 1: int(class_max)}
  52. if balancing == 'none':
  53. return X, y
  54. if balancing == 'ros':
  55. sampler = RandomOverSampler(sampling_strategy=sample_nums, random_state=42)
  56. elif balancing == 'smote':
  57. sampler = SMOTE(sampling_strategy=sample_nums, random_state=42)
  58. X_r, Y_r = sampler.fit_resample(X, y)
  59. return X_r, Y_r
  60. def train(df, feat_names,
  61. cell_nums_feature_selection, cell_nums_train,
  62. model_type='rf', outcome_def='y_thresh',
  63. balancing='ros', balancing_ratio=1, out_name='results/classify/test.pkl',
  64. calibrated=False, feature_selection=None,
  65. feature_selection_num=3, hyperparam=0, seed=42):
  66. '''Run training and fit models
  67. This will balance the data
  68. This will normalize the features before fitting
  69. Params
  70. ------
  71. normalize: bool
  72. if True, will normalize features before fitting
  73. cell_nums_feature_selection: list[str]
  74. cell names to use for feature selection
  75. '''
  76. np.random.seed(seed)
  77. X = df[feat_names]
  78. X = (X - X.mean()) / X.std() # normalize the data
  79. y = df[outcome_def].values
  80. if model_type == 'rf':
  81. m = RandomForestClassifier(n_estimators=100)
  82. elif model_type == 'dt':
  83. m = DecisionTreeClassifier()
  84. elif model_type == 'logistic':
  85. m = LogisticRegression(solver='lbfgs')
  86. elif model_type == 'svm':
  87. h = {
  88. -1: 0.5,
  89. 0: 1,
  90. 1: 5
  91. }[hyperparam]
  92. m = SVC(C=h, gamma='scale')
  93. elif model_type == 'mlp2':
  94. h = {
  95. -1: (50,),
  96. 0: (100,),
  97. 1: (50, 50,)
  98. }[hyperparam]
  99. m = MLPClassifier(hidden_layer_sizes=h)
  100. elif model_type == 'gb':
  101. m = GradientBoostingClassifier()
  102. elif model_type == 'qda':
  103. m = QDA()
  104. elif model_type == 'KNN':
  105. m = KNN()
  106. elif model_type == 'irf':
  107. import irf
  108. m = irf.ensemble.wrf()
  109. elif model_type == 'voting_mlp+svm+rf':
  110. models_list = [('mlp', MLPClassifier()),
  111. ('svm', SVC(gamma='scale')),
  112. ('rf', RandomForestClassifier(n_estimators=100))]
  113. m = VotingClassifier(estimators=models_list, voting='hard')
  114. if calibrated:
  115. m = CalibratedClassifierCV(m)
  116. scores_cv = {s: [] for s in scorers.keys()}
  117. imps = {'model': [], 'imps': []}
  118. kf = KFold(n_splits=len(cell_nums_train))
  119. # feature selection on cell num 1
  120. feature_selector = None
  121. if feature_selection is not None:
  122. if feature_selection == 'select_lasso':
  123. feature_selector_model = Lasso()
  124. elif feature_selection == 'select_rf':
  125. feature_selector_model = RandomForestClassifier()
  126. # select only feature_selection_num features
  127. feature_selector = SelectFromModel(feature_selector_model, threshold=-np.inf,
  128. max_features=feature_selection_num)
  129. idxs = df.cell_num.isin(cell_nums_feature_selection)
  130. feature_selector.fit(X[idxs], y[idxs].reshape(-1, 1))
  131. X = feature_selector.transform(X)
  132. support = np.array(feature_selector.get_support())
  133. else:
  134. support = np.ones(len(feat_names)).astype(np.bool)
  135. num_pts_by_fold_cv = []
  136. # loops over cv, where validation set order is cell_nums_train[0], ..., cell_nums_train[-1]
  137. for cv_idx, cv_val_idx in kf.split(cell_nums_train):
  138. # get sample indices
  139. idxs_cv = df.cell_num.isin(cell_nums_train[np.array(cv_idx)])
  140. idxs_val_cv = df.cell_num.isin(cell_nums_train[np.array(cv_val_idx)])
  141. X_train_cv, Y_train_cv = X[idxs_cv], y[idxs_cv]
  142. X_val_cv, Y_val_cv = X[idxs_val_cv], y[idxs_val_cv]
  143. num_pts_by_fold_cv.append(X_val_cv.shape[0])
  144. # resample training data
  145. X_train_r_cv, Y_train_r_cv = balance(X_train_cv, Y_train_cv, balancing, balancing_ratio)
  146. # fit
  147. m.fit(X_train_r_cv, Y_train_r_cv)
  148. # get preds
  149. preds = m.predict(X_val_cv)
  150. if 'svm' in model_type:
  151. preds_proba = preds
  152. else:
  153. preds_proba = m.predict_proba(X_val_cv)[:, 1]
  154. # add scores
  155. for s in scorers.keys():
  156. scorer = scorers[s]
  157. if 'roc' in s or 'curve' in s:
  158. scores_cv[s].append(scorer(Y_val_cv, preds_proba))
  159. else:
  160. scores_cv[s].append(scorer(Y_val_cv, preds))
  161. imps['model'].append(deepcopy(m))
  162. imps['imps'].append(get_feature_importance(m, model_type, X_val_cv, Y_val_cv))
  163. # save results
  164. # os.makedirs(out_dir, exist_ok=True)
  165. results = {'metrics': list(scorers.keys()),
  166. 'num_pts_by_fold_cv': np.array(num_pts_by_fold_cv),
  167. 'cv': scores_cv,
  168. 'imps': imps, # note this contains the model
  169. 'feat_names': feat_names,
  170. 'feature_selector': feature_selector,
  171. 'feature_selection_num': feature_selection_num,
  172. 'model_type': model_type,
  173. 'balancing': balancing,
  174. 'feat_names_selected': np.array(feat_names)[support],
  175. 'calibrated': calibrated
  176. }
  177. pkl.dump(results, open(out_name, 'wb'))
Tip!

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

Comments

Loading...