-
-
Notifications
You must be signed in to change notification settings - Fork 25.5k
/
Copy pathbench_random_projections.py
304 lines (255 loc) · 8.37 KB
/
bench_random_projections.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
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
"""
===========================
Random projection benchmark
===========================
Benchmarks for random projections.
"""
import collections
import gc
import optparse
import sys
from datetime import datetime
import numpy as np
import scipy.sparse as sp
from sklearn import clone
from sklearn.random_projection import (
GaussianRandomProjection,
SparseRandomProjection,
johnson_lindenstrauss_min_dim,
)
def type_auto_or_float(val):
if val == "auto":
return "auto"
else:
return float(val)
def type_auto_or_int(val):
if val == "auto":
return "auto"
else:
return int(val)
def compute_time(t_start, delta):
mu_second = 0.0 + 10**6 # number of microseconds in a second
return delta.seconds + delta.microseconds / mu_second
def bench_scikit_transformer(X, transformer):
gc.collect()
clf = clone(transformer)
# start time
t_start = datetime.now()
clf.fit(X)
delta = datetime.now() - t_start
# stop time
time_to_fit = compute_time(t_start, delta)
# start time
t_start = datetime.now()
clf.transform(X)
delta = datetime.now() - t_start
# stop time
time_to_transform = compute_time(t_start, delta)
return time_to_fit, time_to_transform
# Make some random data with uniformly located non zero entries with
# Gaussian distributed values
def make_sparse_random_data(n_samples, n_features, n_nonzeros, random_state=None):
rng = np.random.RandomState(random_state)
data_coo = sp.coo_matrix(
(
rng.randn(n_nonzeros),
(
rng.randint(n_samples, size=n_nonzeros),
rng.randint(n_features, size=n_nonzeros),
),
),
shape=(n_samples, n_features),
)
return data_coo.toarray(), data_coo.tocsr()
def print_row(clf_type, time_fit, time_transform):
print(
"%s | %s | %s"
% (
clf_type.ljust(30),
("%.4fs" % time_fit).center(12),
("%.4fs" % time_transform).center(12),
)
)
if __name__ == "__main__":
###########################################################################
# Option parser
###########################################################################
op = optparse.OptionParser()
op.add_option(
"--n-times",
dest="n_times",
default=5,
type=int,
help="Benchmark results are average over n_times experiments",
)
op.add_option(
"--n-features",
dest="n_features",
default=10**4,
type=int,
help="Number of features in the benchmarks",
)
op.add_option(
"--n-components",
dest="n_components",
default="auto",
help="Size of the random subspace. ('auto' or int > 0)",
)
op.add_option(
"--ratio-nonzeros",
dest="ratio_nonzeros",
default=10**-3,
type=float,
help="Number of features in the benchmarks",
)
op.add_option(
"--n-samples",
dest="n_samples",
default=500,
type=int,
help="Number of samples in the benchmarks",
)
op.add_option(
"--random-seed",
dest="random_seed",
default=13,
type=int,
help="Seed used by the random number generators.",
)
op.add_option(
"--density",
dest="density",
default=1 / 3,
help=(
"Density used by the sparse random projection. ('auto' or float (0.0, 1.0]"
),
)
op.add_option(
"--eps",
dest="eps",
default=0.5,
type=float,
help="See the documentation of the underlying transformers.",
)
op.add_option(
"--transformers",
dest="selected_transformers",
default="GaussianRandomProjection,SparseRandomProjection",
type=str,
help=(
"Comma-separated list of transformer to benchmark. "
"Default: %default. Available: "
"GaussianRandomProjection,SparseRandomProjection"
),
)
op.add_option(
"--dense",
dest="dense",
default=False,
action="store_true",
help="Set input space as a dense matrix.",
)
(opts, args) = op.parse_args()
if len(args) > 0:
op.error("this script takes no arguments.")
sys.exit(1)
opts.n_components = type_auto_or_int(opts.n_components)
opts.density = type_auto_or_float(opts.density)
selected_transformers = opts.selected_transformers.split(",")
###########################################################################
# Generate dataset
###########################################################################
n_nonzeros = int(opts.ratio_nonzeros * opts.n_features)
print("Dataset statistics")
print("===========================")
print("n_samples \t= %s" % opts.n_samples)
print("n_features \t= %s" % opts.n_features)
if opts.n_components == "auto":
print(
"n_components \t= %s (auto)"
% johnson_lindenstrauss_min_dim(n_samples=opts.n_samples, eps=opts.eps)
)
else:
print("n_components \t= %s" % opts.n_components)
print("n_elements \t= %s" % (opts.n_features * opts.n_samples))
print("n_nonzeros \t= %s per feature" % n_nonzeros)
print("ratio_nonzeros \t= %s" % opts.ratio_nonzeros)
print("")
###########################################################################
# Set transformer input
###########################################################################
transformers = {}
###########################################################################
# Set GaussianRandomProjection input
gaussian_matrix_params = {
"n_components": opts.n_components,
"random_state": opts.random_seed,
}
transformers["GaussianRandomProjection"] = GaussianRandomProjection(
**gaussian_matrix_params
)
###########################################################################
# Set SparseRandomProjection input
sparse_matrix_params = {
"n_components": opts.n_components,
"random_state": opts.random_seed,
"density": opts.density,
"eps": opts.eps,
}
transformers["SparseRandomProjection"] = SparseRandomProjection(
**sparse_matrix_params
)
###########################################################################
# Perform benchmark
###########################################################################
time_fit = collections.defaultdict(list)
time_transform = collections.defaultdict(list)
print("Benchmarks")
print("===========================")
print("Generate dataset benchmarks... ", end="")
X_dense, X_sparse = make_sparse_random_data(
opts.n_samples, opts.n_features, n_nonzeros, random_state=opts.random_seed
)
X = X_dense if opts.dense else X_sparse
print("done")
for name in selected_transformers:
print("Perform benchmarks for %s..." % name)
for iteration in range(opts.n_times):
print("\titer %s..." % iteration, end="")
time_to_fit, time_to_transform = bench_scikit_transformer(
X_dense, transformers[name]
)
time_fit[name].append(time_to_fit)
time_transform[name].append(time_to_transform)
print("done")
print("")
###########################################################################
# Print results
###########################################################################
print("Script arguments")
print("===========================")
arguments = vars(opts)
print(
"%s \t | %s "
% (
"Arguments".ljust(16),
"Value".center(12),
)
)
print(25 * "-" + ("|" + "-" * 14) * 1)
for key, value in arguments.items():
print("%s \t | %s " % (str(key).ljust(16), str(value).strip().center(12)))
print("")
print("Transformer performance:")
print("===========================")
print("Results are averaged over %s repetition(s)." % opts.n_times)
print("")
print(
"%s | %s | %s"
% ("Transformer".ljust(30), "fit".center(12), "transform".center(12))
)
print(31 * "-" + ("|" + "-" * 14) * 2)
for name in sorted(selected_transformers):
print_row(name, np.mean(time_fit[name]), np.mean(time_transform[name]))
print("")
print("")