forked from scikit-learn/scikit-learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbench_saga.py
380 lines (337 loc) · 10.6 KB
/
bench_saga.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""Author: Arthur Mensch, Nelle Varoquaux
Benchmarks of sklearn SAGA vs lightning SAGA vs Liblinear. Shows the gain
in using multinomial logistic regression in term of learning time.
"""
import json
import time
import os
from sklearn.utils.parallel import delayed, Parallel
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import (
fetch_rcv1,
load_iris,
load_digits,
fetch_20newsgroups_vectorized,
)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer, LabelEncoder
from sklearn.utils.extmath import safe_sparse_dot, softmax
def fit_single(
solver,
X,
y,
penalty="l2",
single_target=True,
C=1,
max_iter=10,
skip_slow=False,
dtype=np.float64,
):
if skip_slow and solver == "lightning" and penalty == "l1":
print("skip_slowping l1 logistic regression with solver lightning.")
return
print(
"Solving %s logistic regression with penalty %s, solver %s."
% ("binary" if single_target else "multinomial", penalty, solver)
)
if solver == "lightning":
from lightning.classification import SAGAClassifier
if single_target or solver not in ["sag", "saga"]:
multi_class = "ovr"
else:
multi_class = "multinomial"
X = X.astype(dtype)
y = y.astype(dtype)
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=42, stratify=y
)
n_samples = X_train.shape[0]
n_classes = np.unique(y_train).shape[0]
test_scores = [1]
train_scores = [1]
accuracies = [1 / n_classes]
times = [0]
if penalty == "l2":
alpha = 1.0 / (C * n_samples)
beta = 0
lightning_penalty = None
else:
alpha = 0.0
beta = 1.0 / (C * n_samples)
lightning_penalty = "l1"
for this_max_iter in range(1, max_iter + 1, 2):
print(
"[%s, %s, %s] Max iter: %s"
% (
"binary" if single_target else "multinomial",
penalty,
solver,
this_max_iter,
)
)
if solver == "lightning":
lr = SAGAClassifier(
loss="log",
alpha=alpha,
beta=beta,
penalty=lightning_penalty,
tol=-1,
max_iter=this_max_iter,
)
else:
lr = LogisticRegression(
solver=solver,
multi_class=multi_class,
C=C,
penalty=penalty,
fit_intercept=False,
tol=0,
max_iter=this_max_iter,
random_state=42,
)
# Makes cpu cache even for all fit calls
X_train.max()
t0 = time.clock()
lr.fit(X_train, y_train)
train_time = time.clock() - t0
scores = []
for X, y in [(X_train, y_train), (X_test, y_test)]:
try:
y_pred = lr.predict_proba(X)
except NotImplementedError:
# Lightning predict_proba is not implemented for n_classes > 2
y_pred = _predict_proba(lr, X)
score = log_loss(y, y_pred, normalize=False) / n_samples
score += 0.5 * alpha * np.sum(lr.coef_**2) + beta * np.sum(
np.abs(lr.coef_)
)
scores.append(score)
train_score, test_score = tuple(scores)
y_pred = lr.predict(X_test)
accuracy = np.sum(y_pred == y_test) / y_test.shape[0]
test_scores.append(test_score)
train_scores.append(train_score)
accuracies.append(accuracy)
times.append(train_time)
return lr, times, train_scores, test_scores, accuracies
def _predict_proba(lr, X):
pred = safe_sparse_dot(X, lr.coef_.T)
if hasattr(lr, "intercept_"):
pred += lr.intercept_
return softmax(pred)
def exp(
solvers,
penalty,
single_target,
n_samples=30000,
max_iter=20,
dataset="rcv1",
n_jobs=1,
skip_slow=False,
):
dtypes_mapping = {
"float64": np.float64,
"float32": np.float32,
}
if dataset == "rcv1":
rcv1 = fetch_rcv1()
lbin = LabelBinarizer()
lbin.fit(rcv1.target_names)
X = rcv1.data
y = rcv1.target
y = lbin.inverse_transform(y)
le = LabelEncoder()
y = le.fit_transform(y)
if single_target:
y_n = y.copy()
y_n[y > 16] = 1
y_n[y <= 16] = 0
y = y_n
elif dataset == "digits":
X, y = load_digits(return_X_y=True)
if single_target:
y_n = y.copy()
y_n[y < 5] = 1
y_n[y >= 5] = 0
y = y_n
elif dataset == "iris":
iris = load_iris()
X, y = iris.data, iris.target
elif dataset == "20newspaper":
ng = fetch_20newsgroups_vectorized()
X = ng.data
y = ng.target
if single_target:
y_n = y.copy()
y_n[y > 4] = 1
y_n[y <= 16] = 0
y = y_n
X = X[:n_samples]
y = y[:n_samples]
out = Parallel(n_jobs=n_jobs, mmap_mode=None)(
delayed(fit_single)(
solver,
X,
y,
penalty=penalty,
single_target=single_target,
dtype=dtype,
C=1,
max_iter=max_iter,
skip_slow=skip_slow,
)
for solver in solvers
for dtype in dtypes_mapping.values()
)
res = []
idx = 0
for dtype_name in dtypes_mapping.keys():
for solver in solvers:
if not (skip_slow and solver == "lightning" and penalty == "l1"):
lr, times, train_scores, test_scores, accuracies = out[idx]
this_res = dict(
solver=solver,
penalty=penalty,
dtype=dtype_name,
single_target=single_target,
times=times,
train_scores=train_scores,
test_scores=test_scores,
accuracies=accuracies,
)
res.append(this_res)
idx += 1
with open("bench_saga.json", "w+") as f:
json.dump(res, f)
def plot(outname=None):
import pandas as pd
with open("bench_saga.json", "r") as f:
f = json.load(f)
res = pd.DataFrame(f)
res.set_index(["single_target"], inplace=True)
grouped = res.groupby(level=["single_target"])
colors = {"saga": "C0", "liblinear": "C1", "lightning": "C2"}
linestyles = {"float32": "--", "float64": "-"}
alpha = {"float64": 0.5, "float32": 1}
for idx, group in grouped:
single_target = idx
fig, axes = plt.subplots(figsize=(12, 4), ncols=4)
ax = axes[0]
for scores, times, solver, dtype in zip(
group["train_scores"], group["times"], group["solver"], group["dtype"]
):
ax.plot(
times,
scores,
label="%s - %s" % (solver, dtype),
color=colors[solver],
alpha=alpha[dtype],
marker=".",
linestyle=linestyles[dtype],
)
ax.axvline(
times[-1],
color=colors[solver],
alpha=alpha[dtype],
linestyle=linestyles[dtype],
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Training objective (relative to min)")
ax.set_yscale("log")
ax = axes[1]
for scores, times, solver, dtype in zip(
group["test_scores"], group["times"], group["solver"], group["dtype"]
):
ax.plot(
times,
scores,
label=solver,
color=colors[solver],
linestyle=linestyles[dtype],
marker=".",
alpha=alpha[dtype],
)
ax.axvline(
times[-1],
color=colors[solver],
alpha=alpha[dtype],
linestyle=linestyles[dtype],
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Test objective (relative to min)")
ax.set_yscale("log")
ax = axes[2]
for accuracy, times, solver, dtype in zip(
group["accuracies"], group["times"], group["solver"], group["dtype"]
):
ax.plot(
times,
accuracy,
label="%s - %s" % (solver, dtype),
alpha=alpha[dtype],
marker=".",
color=colors[solver],
linestyle=linestyles[dtype],
)
ax.axvline(
times[-1],
color=colors[solver],
alpha=alpha[dtype],
linestyle=linestyles[dtype],
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Test accuracy")
ax.legend()
name = "single_target" if single_target else "multi_target"
name += "_%s" % penalty
plt.suptitle(name)
if outname is None:
outname = name + ".png"
fig.tight_layout()
fig.subplots_adjust(top=0.9)
ax = axes[3]
for scores, times, solver, dtype in zip(
group["train_scores"], group["times"], group["solver"], group["dtype"]
):
ax.plot(
np.arange(len(scores)),
scores,
label="%s - %s" % (solver, dtype),
marker=".",
alpha=alpha[dtype],
color=colors[solver],
linestyle=linestyles[dtype],
)
ax.set_yscale("log")
ax.set_xlabel("# iterations")
ax.set_ylabel("Objective function")
ax.legend()
plt.savefig(outname)
if __name__ == "__main__":
solvers = ["saga", "liblinear", "lightning"]
penalties = ["l1", "l2"]
n_samples = [100000, 300000, 500000, 800000, None]
single_target = True
for penalty in penalties:
for n_sample in n_samples:
exp(
solvers,
penalty,
single_target,
n_samples=n_sample,
n_jobs=1,
dataset="rcv1",
max_iter=10,
)
if n_sample is not None:
outname = "figures/saga_%s_%d.png" % (penalty, n_sample)
else:
outname = "figures/saga_%s_all.png" % (penalty,)
try:
os.makedirs("figures")
except OSError:
pass
plot(outname)