-
Notifications
You must be signed in to change notification settings - Fork 29
/
uci_loader.py
66 lines (58 loc) · 1.89 KB
/
uci_loader.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
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import OneHotEncoder
import numpy as np
def dshape(X):
if len(X.shape) == 1:
return X.reshape(-1, 1)
else:
return X if X.shape[0] > X.shape[1] else X.T
def unpack(t):
while type(t) == list or type(t) == np.ndarray:
t = t[0]
return t
def tonumeric(lst):
lbls = {}
for t in lst.flatten():
if unpack(t) not in lbls:
lbls[unpack(t)] = len(lbls.keys())
return np.array([lbls[unpack(t)] for t in lst.flatten()])
def getdataset(datasetname, onehot_encode_strings=True):
# load
dataset = fetch_openml(datasetname)
# get X and y
X = dshape(dataset.data)
try:
target = dshape(dataset.target)
except:
print("WARNING: No target found. Taking last column of data matrix as target")
target = X[:, -1]
X = X[:, :-1]
if (
len(target.shape) > 1 and target.shape[1] > X.shape[1]
): # some mldata sets are mixed up...
X = target
target = dshape(dataset.data)
if len(X.shape) == 1 or X.shape[1] <= 1:
for k in dataset.keys():
if k != "data" and k != "target" and len(dataset[k]) == X.shape[1]:
X = np.hstack((X, dshape(dataset[k])))
# one-hot for categorical values
if onehot_encode_strings:
cat_ft = [
i
for i in range(X.shape[1])
if "str" in str(type(unpack(X[0, i])))
or "unicode" in str(type(unpack(X[0, i])))
]
if len(cat_ft):
for i in cat_ft:
X[:, i] = tonumeric(X[:, i])
X = OneHotEncoder(categorical_features=cat_ft).fit_transform(X)
# if sparse, make dense
try:
X = X.toarray()
except:
pass
# convert y to monotonically increasing ints
y = tonumeric(target).astype(int)
return np.nan_to_num(X.astype(float)), y