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

partition.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
  1. import random
  2. from dataclasses import *
  3. from functools import cached_property
  4. from sklearn.base import TransformerMixin
  5. from sklearn.model_selection._split import _BaseKFold
  6. from sklearn.preprocessing import LabelEncoder
  7. import itertools
  8. from yspecies.dataset import ExpressionDataset
  9. from yspecies.utils import *
  10. @dataclass
  11. class FeatureSelection:
  12. '''
  13. Class that contains parameters for feature selection
  14. '''
  15. samples: List[str] = field(default_factory=lambda: ["tissue","species"])
  16. species: List[str] = field(default_factory=lambda: [])
  17. genes: List[str] = None #if None = takes all genes
  18. to_predict: str = "lifespan"
  19. categorical: List[str] = field(default_factory=lambda: ["tissue"])
  20. exclude_from_training: List[str] = field(default_factory=lambda: ["species"])#columns that should note be used for training
  21. genes_meta: pd.DataFrame = None #metada for genes, TODO: check if still needed
  22. @property
  23. def has_categorical(self):
  24. return self.categorical is not None and len(self.categorical) > 0
  25. def prepare_for_training(self, df: pd.DataFrame):
  26. return df if self.exclude_from_training is None else df.drop(columns=self.exclude_from_training, errors="ignore")
  27. @property
  28. def y_name(self):
  29. '''
  30. Just for nice display in jupyter
  31. :return:
  32. '''
  33. return f"Y_{self.to_predict}"
  34. def _repr_html_(self):
  35. return f"<table border='2'>" \
  36. f"<caption> Selected feature columns <caption>" \
  37. f"<tr><th>Samples metadata</th><th>Species metadata</th><th>Genes</th><th>Predict label</th></tr>" \
  38. f"<tr><td>{str(self.samples)}</td><td>{str(self.species)}</td><td>{'all' if self.genes is None else str(self.genes)}</td><td>{str(self.to_predict)}</td></tr>" \
  39. f"</table>"
  40. class EncodedFeatures:
  41. def __init__(self, features: FeatureSelection, samples: pd.DataFrame, genes_meta: pd.DataFrame = None):
  42. self.genes_meta = genes_meta
  43. self.features = features
  44. self.samples = samples
  45. if len(features.categorical) < 1:
  46. self.encoders = []
  47. else:
  48. self.encoders: Dict[str, LabelEncoder] = {f: LabelEncoder() for f in features.categorical}
  49. for col, encoder in self.encoders.items():
  50. col_encoded = col+"encoded"
  51. self.samples[col_encoded] = encoder.fit_transform(samples[col].values)
  52. @cached_property
  53. def y(self) -> pd.Series:
  54. return self.samples[self.features.to_predict].rename(self.features.to_predict)
  55. @cached_property
  56. def X(self):
  57. return self.samples.drop(columns=[self.features.to_predict])
  58. def __repr__(self):
  59. #to fix jupyter freeze (see https://github.com/ipython/ipython/issues/9771 )
  60. return self._repr_html_()
  61. def _repr_html_(self):
  62. return f"<table><caption>top 10 * 100 features/samples</caption><tr><td>{self.features._repr_html_()}</td><tr><td>{show(self.samples,100,10)._repr_html_()}</td></tr>"
  63. @dataclass
  64. class DataExtractor(TransformerMixin):
  65. '''
  66. Workflow stage which extracts Data from ExpressionDataset
  67. '''
  68. features: FeatureSelection
  69. def fit(self, X, y=None) -> 'DataExtractor':
  70. return self
  71. def transform(self, data: ExpressionDataset) -> EncodedFeatures:
  72. samples = data.extended_samples(self.features.samples, self.features.species)
  73. exp = data.expressions if self.features.genes is None else data.expressions[self.features.genes]
  74. X: pd.dataFrame = samples.join(exp, how="inner")
  75. samples = data.get_label(self.features.to_predict).join(X)
  76. return EncodedFeatures(self.features, samples, data.genes_meta)
  77. @dataclass
  78. class ExpressionPartitions:
  79. '''
  80. Class is used as results of SortedStratification, it can also do hold-outs
  81. '''
  82. data: EncodedFeatures
  83. X: pd.DataFrame
  84. Y: pd.DataFrame
  85. indexes: List[List[int]]
  86. validation_species: List[List[str]]
  87. nhold_out: int = 0 #how many partitions we hold for checking validation
  88. @cached_property
  89. def cv_indexes(self):
  90. return self.indexes[0:(len(self.indexes)-self.nhold_out)]
  91. @cached_property
  92. def hold_out_partition_indexes(self) -> List[List[int]]:
  93. return self.indexes[(len(self.indexes)-self.nhold_out):len(self.indexes)]
  94. @cached_property
  95. def hold_out_merged_index(self) -> List[int]:
  96. '''
  97. Hold out is required to check if cross-validation makes sense whe parameter tuning
  98. :return:
  99. '''
  100. return list(itertools.chain(*[pindex for pindex in self.hold_out_partition_indexes]))
  101. @cached_property
  102. def categorical_index(self):
  103. # temporaly making them auto
  104. return [ind for ind, c in enumerate(self.X.columns) if c in self.features.categorical]
  105. @property
  106. def folds(self):
  107. for ind in self.indexes:
  108. yield (ind,ind)
  109. @cached_property
  110. def nfold(self) -> int:
  111. len(self.partitions_x)
  112. @cached_property
  113. def partitions_x(self):
  114. return [self.X.iloc[pindex] for pindex in self.cv_indexes]
  115. @cached_property
  116. def partitions_y(self):
  117. return [self.Y.iloc[pindex] for pindex in self.cv_indexes]
  118. @cached_property
  119. def cv_merged_index(self):
  120. return list(itertools.chain(*[pindex for pindex in self.cv_indexes]))
  121. @cached_property
  122. def cv_merged_x(self):
  123. return self.X.iloc[self.cv_merged_index]
  124. @cached_property
  125. def cv_merged_y(self):
  126. return self.Y.iloc[self.cv_merged_index]
  127. @cached_property
  128. def hold_out_x(self):
  129. assert self.nhold_out > 0, "current nhold_out is 0 partitions, so no hold out data can be extracted!"
  130. return self.X.iloc[self.hold_out_merged_index]
  131. @cached_property
  132. def hold_out_y(self):
  133. assert self.nhold_out > 0, "current nhold_out is 0 partitions, so no hold out data can be extracted!"
  134. return self.Y.iloc[self.hold_out_merged_index]
  135. @cached_property
  136. def species(self):
  137. return self.X['species'].values
  138. @cached_property
  139. def species_partitions(self):
  140. return [self.species[pindex] for pindex in self.indexes]
  141. @cached_property
  142. def X_T(self) -> pd.DataFrame:
  143. return self.X.T
  144. @property
  145. def features(self):
  146. return self.data.features
  147. def split_fold(self, i: int):
  148. X_train, y_train = self.fold_train(i)
  149. X_test = self.partitions_x[i]
  150. y_test = self.partitions_y[i]
  151. return X_train, X_test, y_train, y_test
  152. def fold_train(self, i: int):
  153. '''
  154. prepares train data for the fold
  155. :param i: number of parition
  156. :return: tuple with X and Y
  157. '''
  158. return pd.concat(self.partitions_x[:i] + self.partitions_x[i + 1:]), np.concatenate(self.partitions_y[:i] + self.partitions_y[i + 1:], axis=0)
  159. def __repr__(self):
  160. #to fix jupyter freeze (see https://github.com/ipython/ipython/issues/9771 )
  161. return self._repr_html_()
  162. def _repr_html_(self):
  163. return f"<table>" \
  164. f"<tr><th>partitions_X</th><th>partitions_Y</th></tr>" \
  165. f"<tr><td align='left'>[ {','.join([str(x.shape) for x in self.partitions_x])} ]</td>" \
  166. f"<td align='left'>[ {','.join([str(y.shape) for y in self.partitions_y])} ]</td></tr>" \
  167. f"<tr><th>show(X,10,10)</th><th>show(Y,10,10)</th></tr>" \
  168. f"<tr><td>{show(self.X,10,10)._repr_html_()}</td><td>{show(self.Y,10,10)._repr_html_()}</td></tr>" \
  169. f"</table>"
  170. @dataclass
  171. class DataPartitioner(TransformerMixin):
  172. '''
  173. Partitions the data according to sorted stratification
  174. '''
  175. nfolds: int
  176. species_in_validation: int = 2 #exclude species to validate them
  177. not_validated_species: List[str] = field(default_factory=lambda: ["Homo sapiens"])
  178. nhold_out: int = 0
  179. def fit(self, X, y=None) -> 'DataExtractor':
  180. return self
  181. def transform(self, selected: EncodedFeatures) -> ExpressionPartitions:
  182. '''
  183. :param data: ExpressionDataset
  184. :param k: number of k-folds in sorted stratification
  185. :return: partitions
  186. '''
  187. assert isinstance(selected.samples, pd.DataFrame), "Should contain extracted Pandas DataFrame with X and Y"
  188. return self.sorted_stratification(selected, self.nfolds)
  189. def sorted_stratification(self, encodedFeatures: EncodedFeatures, k: int) -> ExpressionPartitions:
  190. '''
  191. :param df:
  192. :param features:
  193. :param k:
  194. :param species_validation: number of species to leave only in validation set
  195. :return:
  196. '''
  197. df = encodedFeatures.samples
  198. features = encodedFeatures.features
  199. X = df.sort_values(by=[features.to_predict], ascending=False).drop(columns=features.categorical,errors="ignore")
  200. if self.species_in_validation > 0:
  201. all_species = X.species[~X["species"].isin(self.not_validated_species)].drop_duplicates().values
  202. df_index = X.index
  203. #TODO: looks overly complicated (too many accumulating variables, refactor is needed)
  204. k_sets_indexes = []
  205. k_sets_of_species = []
  206. already_selected = []
  207. for i in range(k):
  208. index_set = []
  209. choices = []
  210. for j in range(self.species_in_validation):
  211. choice = random.choice(all_species)
  212. while choice in already_selected:
  213. choice = random.choice(all_species)
  214. choices.append(choice)
  215. already_selected.append(choice)
  216. k_sets_of_species.append(choices)
  217. species = X['species'].values
  218. for j, c in enumerate(species):
  219. if c in choices:
  220. index_set.append(j)
  221. k_sets_indexes.append(index_set)
  222. partition_indexes = [[] for i in range(k)]
  223. i = 0
  224. index_of_sample = 0
  225. while i < (int(len(X)/k)):
  226. for j in range(k):
  227. partition_indexes[j].append((i*k)+j)
  228. index_of_sample = (i*k)+j
  229. i += 1
  230. index_of_sample += 1
  231. i = 0
  232. while index_of_sample < len(X):
  233. partition_indexes[i].append(index_of_sample)
  234. index_of_sample += 1
  235. i += 1
  236. #in X also have Y columns which we will separate to Y
  237. X_sorted = features.prepare_for_training(X.drop([features.to_predict], axis=1))
  238. #we had Y inside X with pretified name in features, fixing it in paritions
  239. Y_sorted = features.prepare_for_training(X[[features.to_predict]])
  240. if self.species_in_validation > 0:
  241. for i, pindex in enumerate(partition_indexes):
  242. for j, sindex in enumerate(k_sets_indexes):
  243. if i == j:
  244. partition_indexes[i] = list(set(partition_indexes[i]).union(set(k_sets_indexes[j])))
  245. else:
  246. partition_indexes[i] = list(set(partition_indexes[i]).difference(set(k_sets_indexes[j])))
  247. return ExpressionPartitions(encodedFeatures, X_sorted, Y_sorted, partition_indexes, k_sets_of_species, nhold_out=self.nhold_out)
Tip!

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

Comments

Loading...