-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdataset.py
259 lines (214 loc) · 7.19 KB
/
dataset.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
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
import numpy
import csv
DATA_PATH = "data/"
DATA_FULL_PATH = DATA_PATH + 'full/'
DATASET_NAMES = ['accidents',
'ad',
'baudio',
'bbc',
'bnetflix',
'book',
'c20ng',
'cr52',
'cwebkb',
'dna',
'jester',
'kdd',
'msnbc',
'msweb',
'nltcs',
'plants',
'pumsb_star',
'tmovie',
'tretail']
import os
from spn import RND_SEED
def csv_2_numpy(file, path=DATA_PATH, sep=',', type='int8'):
"""
WRITEME
"""
file_path = path + file
reader = csv.reader(open(file_path, "r"), delimiter=sep)
x = list(reader)
dataset = numpy.array(x).astype(type)
return dataset
def load_train_val_test_csvs(dataset,
path=DATA_PATH,
sep=',',
type='int32',
suffixes=['.ts.data',
'.valid.data',
'.test.data']):
"""
WRITEME
"""
csv_files = [dataset + ext for ext in suffixes]
return [csv_2_numpy(file, path, sep, type) for file in csv_files]
def sample_indexes(indexes, perc, replace=False, rand_gen=None):
"""
index sampling
"""
n_indices = indexes.shape[0]
sample_size = int(n_indices * perc)
if rand_gen is None:
rand_gen = numpy.random.RandomState(RND_SEED)
sampled_indices = rand_gen.choice( # n_indices,
indexes,
size=sample_size,
replace=replace)
return sampled_indices
def sample_instances(dataset, perc, replace=False, rndState=None):
"""
Little utility to sample instances (rows) from
a dataset (2d numpy array)
"""
n_instances = dataset.shape[0]
sample_size = int(n_instances * perc)
if rndState is None:
row_indexes = numpy.random.choice(n_instances,
sample_size,
replace)
else:
row_indexes = rndState.choice(n_instances,
sample_size,
replace)
# print(row_indexes)
return dataset[row_indexes, :]
def sample_sets(datasets, perc, replace=False, rndState=None):
"""
WRITEME
"""
sampled_datasets = [sample_instances(dataset, perc, replace, rndState)
for dataset in datasets]
return sampled_datasets
def data_2_freqs(dataset):
"""
WRITEME
"""
freqs = []
features = []
for j, col in enumerate(dataset.T):
freq_dict = {'var': j}
# transforming into a set to get the feature value
# this is assuming not missing values features
# feature_values = max(2, len(set(col)))
feature_values = max(2, max(set(col)) + 1)
features.append(feature_values)
# create a list whose length is the number of feature values
freq_list = [0 for i in range(feature_values)]
# populate it with the seen values
for val in col:
freq_list[val] += 1
# update the dictionary and the resulting list
freq_dict['freqs'] = freq_list
freqs.append(freq_dict)
return freqs, features
def update_feature_count(old_freqs, new_freqs):
if not old_freqs:
return new_freqs
else:
for i, frew in enumerate(old_freqs):
old_freqs[i] = max(old_freqs[i], new_freqs[i])
return old_freqs
def data_clust_freqs(dataset,
n_clusters,
rand_state=None):
"""
WRITEME
"""
freqs = []
features = []
n_instances = dataset.shape[0]
# assign clusters randomly to instances
if rand_state is None:
rand_state = numpy.random.RandomState(RND_SEED)
# inst_2_clusters = numpy.random.randint(0, n_clusters, n_instances)
# getting the indices for each cluster
# this all stuff could be done with a single loop
clusters = [[] for i in range(n_clusters)]
# for instance in range(n_instances):
# rand_cluster = rand_state.randint(0, n_clusters)
# clusters[rand_cluster].append(instance)
instance_ids = numpy.arange(n_instances)
rand_state.shuffle(instance_ids)
print(instance_ids)
for i in range(n_instances):
clusters[i % n_clusters].append(instance_ids[i])
# now we can operate cluster-wise
for cluster_ids in clusters:
# collecting all the data for the cluster
cluster_data = dataset[cluster_ids, :]
# count the frequencies for the var values
cluster_freqs, cluster_features = data_2_freqs(cluster_data)
# updating stats
features = update_feature_count(features, cluster_features)
freqs.extend(cluster_freqs)
return freqs, features
def merge_datasets(dataset_name,
shuffle=True,
path=DATA_PATH,
sep=',',
type='int32',
suffixes=['.ts.data',
'.valid.data',
'.test.data'],
savetxt=True,
out_path=DATA_FULL_PATH,
output_suffix='.all.data',
rand_gen=None):
"""
Merging portions of a dataset
Loading them from file and optionally writing them to file
"""
dataset_parts = load_train_val_test_csvs(dataset_name,
path,
sep,
type,
suffixes)
print('Loaded dataset parts for', dataset_name)
#
# checking features
assert len(dataset_parts) > 0
first_dataset = dataset_parts[0]
n_features = first_dataset.shape[1]
for dataset_p in dataset_parts:
assert dataset_p.shape[1] == n_features
print('\tFeatures are conform')
#
# storing instances
n_instances = [dataset_p.shape[0]
for dataset_p in dataset_parts]
#
# merging
merged_dataset = numpy.concatenate(dataset_parts)
print('\tParts merged')
#
# shuffling
if shuffle:
if rand_gen is None:
rand_gen = numpy.random.RandomState(RND_SEED)
rand_gen.shuffle(merged_dataset)
print('\tShuffled')
#
#
tot_n_instances = sum(n_instances)
assert merged_dataset.shape[0] == tot_n_instances
#
# writing out
if savetxt:
out_path = out_path + dataset_name + output_suffix
if not os.path.exists(os.path.dirname(out_path)):
os.makedirs(os.path.dirname(out_path))
fmt = '%.8e'
if 'int' in type:
fmt = '%d'
numpy.savetxt(out_path, merged_dataset, delimiter=sep, fmt=fmt)
print('\tMerged Dataset saved to', out_path)
return merged_dataset
def split_into_folds(dataset,
n_folds=10,
percentages=[0.81, 0.09, 0.1]):
"""
Splitting a dataset into N folds (e.g. for cv)
and optionally each fold into train-valid-test
"""