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

data_util.py 14 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
  1. import os.path
  2. from os.path import join as oj
  3. from typing import Tuple
  4. import numpy as np
  5. import pandas as pd
  6. import requests
  7. import sklearn.datasets
  8. from scipy.sparse import issparse
  9. from sklearn.datasets import fetch_openml
  10. from sklearn.model_selection import train_test_split
  11. from sklearn.preprocessing import OneHotEncoder
  12. from imodels.util.tree_interaction_utils import make_rj, make_vp
  13. DSET_CLASSIFICATION_KWARGS = {
  14. # classification
  15. 'iris': {'dataset_name': 61, 'data_source': 'openml'},
  16. "pima_diabetes": {"dataset_name": 40715, "data_source": "openml"},
  17. "sonar": {"dataset_name": "sonar", "data_source": "pmlb"},
  18. "heart": {"dataset_name": "heart", "data_source": "imodels"},
  19. "diabetes": {"dataset_name": "diabetes", "data_source": "pmlb"},
  20. "breast_cancer_recurrence": {
  21. "dataset_name": "breast_cancer",
  22. "data_source": "imodels",
  23. },
  24. "breast_cancer_wisconsin": {
  25. "dataset_name": "breast_cancer",
  26. "data_source": "sklearn",
  27. },
  28. "credit_g": {"dataset_name": "credit_g", "data_source": "imodels"},
  29. "juvenile": {"dataset_name": "juvenile_clean", "data_source": "imodels"},
  30. "compas": {"dataset_name": "compas_two_year_clean", "data_source": "imodels"},
  31. "fico": {"dataset_name": "fico", "data_source": "imodels"},
  32. "readmission": {
  33. "dataset_name": "readmission_clean",
  34. "data_source": "imodels",
  35. }, # big, 100k points
  36. # big, 1e6 points
  37. "adult": {"dataset_name": 1182, "data_source": "openml"},
  38. # CDI classification
  39. "csi_pecarn": {"dataset_name": "csi_pecarn_pred", "data_source": "imodels"},
  40. "iai_pecarn": {"dataset_name": "iai_pecarn_pred", "data_source": "imodels"},
  41. "tbi_pecarn": {"dataset_name": "tbi_pecarn_pred", "data_source": "imodels"},
  42. }
  43. DSET_REGRESSION_KWARGS = {
  44. # regression
  45. "bike_sharing": {"dataset_name": 42712, "data_source": "openml"},
  46. "friedman1": {"dataset_name": "friedman1", "data_source": "synthetic"},
  47. "friedman2": {"dataset_name": "friedman2", "data_source": "synthetic"},
  48. "friedman3": {"dataset_name": "friedman3", "data_source": "synthetic"},
  49. "diabetes_regr": {"dataset_name": "diabetes", "data_source": "sklearn"},
  50. "abalone": {"dataset_name": 183, "data_source": "openml"},
  51. "echo_months": {"dataset_name": "1199_BNG_echoMonths", "data_source": "pmlb"},
  52. "satellite_image": {"dataset_name": "294_satellite_image", "data_source": "pmlb"},
  53. "california_housing": {
  54. "dataset_name": "california_housing",
  55. "data_source": "sklearn",
  56. },
  57. # 'breast_tumor': {'dataset_name': '1201_BNG_breastTumor', 'data_source': 'pmlb' # v big
  58. }
  59. DSET_CLASSIFICATION_MULTITASK_NAMES = [
  60. '3s-bbc1000', '3s-guardian1000', '3s-inter3000', '3s-reuters1000',
  61. 'birds', 'cal500', 'chd_49', 'corel16k001', 'corel16k002',
  62. 'corel16k003', 'corel16k004', 'corel16k005', 'corel16k006',
  63. 'corel16k007', 'corel16k008', 'corel16k009', 'corel16k010',
  64. 'corel5k', 'emotions', 'flags', 'foodtruck', 'genbase', 'image',
  65. 'mediamill', 'scene', 'stackex_chemistry', 'stackex_chess',
  66. 'stackex_cooking', 'stackex_cs', 'water-quality', 'yeast', 'yelp']
  67. DSET_CLASSIFICATION_MULTITASK_KWARGS = {
  68. name + '_multitask': {"dataset_name": name, "data_source": "imodels-multitask"}
  69. for name in DSET_CLASSIFICATION_MULTITASK_NAMES
  70. }
  71. DSET_KWARGS = {
  72. **DSET_CLASSIFICATION_KWARGS, **DSET_REGRESSION_KWARGS,
  73. **DSET_CLASSIFICATION_MULTITASK_KWARGS}
  74. def get_clean_dataset(
  75. dataset_name: str,
  76. data_source: str = "imodels",
  77. data_path=os.path.expanduser("~/cache_imodels_data"),
  78. convertna: bool = True,
  79. test_size: float = None,
  80. random_state: int = 42,
  81. verbose=True,
  82. return_target_col_names: bool = False,
  83. override_cache: bool = False,
  84. ) -> Tuple[np.ndarray, np.ndarray, list]:
  85. """Fetch clean data (as numpy arrays) from various sources including imodels, pmlb, openml, and sklearn.
  86. If data is not downloaded, will download and cache. Otherwise will load locally.
  87. Cleans features so that they are type float and features names don't start with a digit.
  88. Parameters
  89. ----------
  90. dataset_name: str
  91. Checks for unique identifier in imodels.util.data_util.DSET_KWARGS
  92. Otherwise, unique dataset identifier (see https://github.com/csinva/imodels-data for unique identifiers)
  93. data_source: str
  94. options: 'imodels', 'pmlb', 'sklearn', 'openml', 'synthetic'
  95. data_path: str
  96. path to load/save data (default: 'data')
  97. test_size: float, optional
  98. if not None, will split data into train and test sets (with fraction test_size in test set)
  99. & change the return signature to `X_train, X_test, y_train, y_test, feature_names`
  100. random_state: int, optional
  101. if test_size is not None, will use this random state to split data
  102. return_target_col_names: bool, optional
  103. if True, will return target columns for multitask datasets as final return value
  104. override_cache: bool, False
  105. if True, will override the downloaded cache for a dataset
  106. Returns
  107. -------
  108. X: np.ndarray
  109. features
  110. y: np.ndarray
  111. outcome
  112. feature_names: list
  113. (if passing test_size, will return more outputs)
  114. (if multitask dataset, will return target_col_names as well)
  115. Example
  116. -------
  117. ```
  118. # download compas dataset from imodels
  119. X, y, feature_names = imodels.get_clean_dataset('compas_two_year_clean', data_source='imodels')
  120. # download ionosphere dataset from pmlb
  121. X, y, feature_names = imodels.get_clean_dataset('ionosphere', data_source='pmlb')
  122. # download liver dataset from openml
  123. X, y, feature_names = imodels.get_clean_dataset('8', data_source='openml')
  124. # download ca housing from sklearn
  125. X, y, feature_names = imodels.get_clean_dataset('california_housing', data_source='sklearn')
  126. ```
  127. """
  128. if dataset_name in DSET_KWARGS:
  129. if verbose:
  130. data_source = DSET_KWARGS[dataset_name]["data_source"]
  131. dataset_name = DSET_KWARGS[dataset_name]["dataset_name"]
  132. print(f"fetching {dataset_name} from {data_source}")
  133. assert data_source in ["imodels", "pmlb", "imodels-multitask", "sklearn", "openml", "synthetic"], (
  134. data_source + " not correct"
  135. )
  136. if test_size is not None:
  137. def _split(X, y, feature_names):
  138. X_train, X_test, y_train, y_test = train_test_split(
  139. X, y, test_size=test_size, random_state=random_state
  140. )
  141. return X_train, X_test, y_train, y_test, feature_names
  142. else:
  143. def _split(X, y, feature_names):
  144. return X, y, feature_names
  145. if data_source == "imodels":
  146. if not dataset_name.endswith("csv"):
  147. dataset_name = dataset_name + ".csv"
  148. if not os.path.isfile(dataset_name) or override_cache:
  149. _download_imodels_dataset(dataset_name, data_path)
  150. df = pd.read_csv(oj(data_path, "imodels_data", dataset_name))
  151. X, y = df.iloc[:, :-1].values, df.iloc[:, -1].values
  152. feature_names = df.columns.values[:-1]
  153. if convertna:
  154. X = np.nan_to_num(X.astype("float32"))
  155. return _split(X, y, _clean_feat_names(feature_names))
  156. elif data_source == 'imodels-multitask':
  157. if not dataset_name.endswith("csv"):
  158. dataset_name = dataset_name + ".csv"
  159. if not os.path.isfile(dataset_name) or override_cache:
  160. _download_imodels_multitask_dataset(dataset_name, data_path)
  161. df = pd.read_csv(oj(data_path, "imodels_multitask_data", dataset_name))
  162. target_cols = [col for col in df.columns if col.endswith('__target')]
  163. feature_names = [col for col in df.columns if col not in target_cols]
  164. X, y = df[feature_names].values, df[target_cols].values
  165. if convertna:
  166. X = np.nan_to_num(X.astype("float32"))
  167. if return_target_col_names:
  168. return *(_split(X, y, _clean_feat_names(feature_names))), _clean_feat_names(target_cols)
  169. else:
  170. return _split(X, y, _clean_feat_names(feature_names))
  171. elif data_source == "pmlb":
  172. from pmlb import fetch_data
  173. feature_names = list(
  174. fetch_data(
  175. dataset_name,
  176. return_X_y=False,
  177. local_cache_dir=oj(data_path, "pmlb_data"),
  178. ).columns
  179. )
  180. feature_names.remove("target")
  181. X, y = fetch_data(
  182. dataset_name, return_X_y=True, local_cache_dir=oj(data_path, "pmlb_data")
  183. )
  184. if (
  185. np.unique(y).size == 2
  186. ): # if binary classification, ensure that the classes are 0 and 1
  187. y -= np.min(y)
  188. return _split(_clean_features(X), y, _clean_feat_names(feature_names))
  189. elif data_source == "sklearn":
  190. if dataset_name == "diabetes":
  191. data = sklearn.datasets.load_diabetes()
  192. elif dataset_name == "california_housing":
  193. data = sklearn.datasets.fetch_california_housing(
  194. data_home=oj(data_path, "sklearn_data")
  195. )
  196. elif dataset_name == "breast_cancer":
  197. data = sklearn.datasets.load_breast_cancer()
  198. return data["data"], data["target"], _clean_feat_names(data["feature_names"])
  199. elif (
  200. data_source == "openml"
  201. ): # note this api might change in newer sklearn - should give dataset-id not name
  202. data = sklearn.datasets.fetch_openml(
  203. data_id=dataset_name, data_home=oj(data_path, "openml_data"), parser="auto"
  204. )
  205. X, y, feature_names = (
  206. data["data"],
  207. data["target"],
  208. _clean_feat_names(data["feature_names"]),
  209. )
  210. if isinstance(X, pd.DataFrame):
  211. X = X.values
  212. if isinstance(y, pd.Series):
  213. y = y.values
  214. y = _define_openml_outcomes(y, dataset_name)
  215. return _split(_clean_features(X), y, _clean_feat_names(feature_names))
  216. elif data_source == "synthetic":
  217. if dataset_name == "friedman1":
  218. X, y = sklearn.datasets.make_friedman1(
  219. n_samples=200, n_features=10)
  220. elif dataset_name == "friedman2":
  221. X, y = sklearn.datasets.make_friedman2(n_samples=200)
  222. elif dataset_name == "friedman3":
  223. X, y = sklearn.datasets.make_friedman3(n_samples=200)
  224. elif dataset_name == "radchenko_james":
  225. X, y = make_rj()
  226. elif dataset_name == "vo_pati":
  227. X, y = make_vp()
  228. return _split(X, y, ["X_" + str(i + 1) for i in range(X.shape[1])])
  229. def _define_openml_outcomes(y, data_id: str):
  230. if data_id == "59": # ionosphere, positive is "good" class
  231. y = (y == "g").astype(int)
  232. if data_id == "183": # abalone, need to convert strings to floats
  233. y = y.astype(float)
  234. if data_id == "1182": # adult, positive is ">50K"
  235. y = (y == ">50K").astype(int)
  236. return y
  237. def _clean_feat_names(feature_names):
  238. # shouldn't start with a digit
  239. feature_names = ["X_" + x if x[0].isdigit() else x for x in feature_names]
  240. # shouldn't end with __target
  241. feature_names = [x if not x.endswith(
  242. "__target") else x[:-8] for x in feature_names]
  243. return feature_names
  244. def _clean_features(X):
  245. if issparse(X):
  246. X = X.toarray()
  247. try:
  248. return X.astype(float)
  249. except:
  250. for j in range(X.shape[1]):
  251. try:
  252. X[:, j].astype(float)
  253. except:
  254. # non-numeric get replaced with numerical values
  255. classes, X[:, j] = np.unique(X[:, j], return_inverse=True)
  256. return X.astype(float)
  257. def _download_imodels_dataset(dataset_fname, data_path: str):
  258. dataset_fname = dataset_fname.split(
  259. "/")[-1] # remove anything about the path
  260. download_path = f"https://raw.githubusercontent.com/csinva/imodels-data/master/data_cleaned/{dataset_fname}"
  261. r = requests.get(download_path)
  262. if r.status_code == 404:
  263. raise Exception(
  264. f"404 Error for dataset {dataset_fname} (see valid files at https://github.com/csinva/imodels-data/tree/master/data_cleaned)"
  265. )
  266. os.makedirs(oj(data_path, "imodels_data"), exist_ok=True)
  267. with open(oj(data_path, "imodels_data", dataset_fname), "w") as f:
  268. f.write(r.text)
  269. def _download_imodels_multitask_dataset(dataset_fname, data_path: str):
  270. dataset_fname = dataset_fname.split(
  271. "/")[-1] # remove anything about the path
  272. download_path = f"https://huggingface.co/datasets/imodels/multitask-tabular-datasets/raw/main/{dataset_fname}"
  273. download_path_large = f'https://huggingface.co/datasets/imodels/multitask-tabular-datasets/resolve/main/{dataset_fname}'
  274. r = requests.get(download_path)
  275. if r.status_code == 404:
  276. raise Exception(
  277. f"404 Error for dataset {dataset_fname} (see valid files at https://huggingface.co/datasets/imodels/multitask-tabular-datasets)"
  278. )
  279. elif 'git-lfs' in r.text:
  280. r = requests.get(download_path_large)
  281. os.makedirs(oj(data_path, "imodels_multitask_data"), exist_ok=True)
  282. with open(oj(data_path, "imodels_multitask_data", dataset_fname), "w") as f:
  283. f.write(r.text)
  284. def encode_categories(X, features, encoder=None):
  285. columns_to_keep = list(set(X.columns).difference(features))
  286. X_encoded = X.loc[:, columns_to_keep]
  287. X_cat = pd.DataFrame({f: X.loc[:, f] for f in features})
  288. if encoder is None:
  289. one_hot_encoder = OneHotEncoder(categories="auto")
  290. X_one_hot = pd.DataFrame(one_hot_encoder.fit_transform(X_cat))
  291. else:
  292. one_hot_encoder = encoder
  293. X_one_hot = pd.DataFrame(one_hot_encoder.transform(X_cat))
  294. X_one_hot.columns = one_hot_encoder.get_feature_names_out(features)
  295. X_encoded = pd.concat([X_encoded, X_one_hot], axis=1)
  296. if encoder is not None:
  297. return X_encoded
  298. return X_encoded, one_hot_encoder
  299. if __name__ == "__main__":
  300. import imodels
  301. # X, y, feature_names = imodels.get_clean_dataset('compas_two_year_clean', data_source='imodels', test_size=0.5)
  302. X_train, X_test, y_train, y_test, feature_names = imodels.get_clean_dataset(
  303. "compas_two_year_clean", data_source="imodels", test_size=0.5
  304. )
  305. print(X_train.shape, y_train.shape)
Tip!

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

Comments

Loading...