forked from scikit-optimize/scikit-optimize
-
Notifications
You must be signed in to change notification settings - Fork 6
/
plots.py
1397 lines (1142 loc) · 50.7 KB
/
plots.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: UTF-8 -*-
"""Plotting functions."""
import sys
import numpy as np
from itertools import count
from functools import partial
from scipy.optimize import OptimizeResult
from .acquisition import _gaussian_acquisition
from skopt import expected_minimum, expected_minimum_random_sampling
from .space import Categorical
from collections import Counter
# For plot tests, matplotlib must be set to headless mode early
if 'pytest' in sys.modules:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from matplotlib.ticker import LogLocator
from matplotlib.ticker import MaxNLocator, FuncFormatter # noqa: E402
def plot_convergence(*args, **kwargs):
"""Plot one or several convergence traces.
Parameters
----------
args[i] : `OptimizeResult`, list of `OptimizeResult`, or tuple
The result(s) for which to plot the convergence trace.
- if `OptimizeResult`, then draw the corresponding single trace;
- if list of `OptimizeResult`, then draw the corresponding convergence
traces in transparency, along with the average convergence trace;
- if tuple, then `args[i][0]` should be a string label and `args[i][1]`
an `OptimizeResult` or a list of `OptimizeResult`.
ax : `Axes`, optional
The matplotlib axes on which to draw the plot, or `None` to create
a new one.
true_minimum : float, optional
The true minimum value of the function, if known.
yscale : None or string, optional
The scale for the y-axis.
Returns
-------
ax : `Axes`
The matplotlib axes.
"""
# <3 legacy python
ax = kwargs.get("ax", None)
true_minimum = kwargs.get("true_minimum", None)
yscale = kwargs.get("yscale", None)
if ax is None:
ax = plt.gca()
ax.set_title("Convergence plot")
ax.set_xlabel("Number of calls $n$")
ax.set_ylabel(r"$\min f(x)$ after $n$ calls")
ax.grid()
if yscale is not None:
ax.set_yscale(yscale)
colors = cm.viridis(np.linspace(0.25, 1.0, len(args)))
for results, color in zip(args, colors):
if isinstance(results, tuple):
name, results = results
else:
name = None
if isinstance(results, OptimizeResult):
n_calls = len(results.x_iters)
mins = [np.min(results.func_vals[:i])
for i in range(1, n_calls + 1)]
ax.plot(range(1, n_calls + 1), mins, c=color,
marker=".", markersize=12, lw=2, label=name)
elif isinstance(results, list):
n_calls = len(results[0].x_iters)
iterations = range(1, n_calls + 1)
mins = [[np.min(r.func_vals[:i]) for i in iterations]
for r in results]
for m in mins:
ax.plot(iterations, m, c=color, alpha=0.2)
ax.plot(iterations, np.mean(mins, axis=0), c=color,
marker=".", markersize=12, lw=2, label=name)
if true_minimum:
ax.axhline(true_minimum, linestyle="--",
color="r", lw=1,
label="True minimum")
if true_minimum or name:
ax.legend(loc="best")
return ax
def plot_gaussian_process(res, **kwargs):
"""Plots the optimization results and the gaussian process
for 1-D objective functions.
Parameters
----------
res : `OptimizeResult`
The result for which to plot the gaussian process.
ax : `Axes`, optional
The matplotlib axes on which to draw the plot, or `None` to create
a new one.
n_calls : int, default: -1
Can be used to evaluate the model at call `n_calls`.
objective : func, default: None
Defines the true objective function. Must have one input parameter.
n_points : int, default: 1000
Number of data points used to create the plots
noise_level : float, default: 0
Sets the estimated noise level
show_legend : boolean, default: True
When True, a legend is plotted.
show_title : boolean, default: True
When True, a title containing the found minimum value
is shown
show_acq_func : boolean, default: False
When True, the acquisition function is plotted
show_next_point : boolean, default: False
When True, the next evaluated point is plotted
show_observations : boolean, default: True
When True, observations are plotted as dots.
show_mu : boolean, default: True
When True, the predicted model is shown.
Returns
-------
ax : `Axes`
The matplotlib axes.
"""
ax = kwargs.get("ax", None)
n_calls = kwargs.get("n_calls", -1)
objective = kwargs.get("objective", None)
noise_level = kwargs.get("noise_level", 0)
show_legend = kwargs.get("show_legend", True)
show_title = kwargs.get("show_title", True)
show_acq_func = kwargs.get("show_acq_func", False)
show_next_point = kwargs.get("show_next_point", False)
show_observations = kwargs.get("show_observations", True)
show_mu = kwargs.get("show_mu", True)
n_points = kwargs.get("n_points", 1000)
if ax is None:
ax = plt.gca()
n_dims = res.space.n_dims
assert n_dims == 1, "Space dimension must be 1"
dimension = res.space.dimensions[0]
x, x_model = _evenly_sample(dimension, n_points)
x = x.reshape(-1, 1)
x_model = x_model.reshape(-1, 1)
if res.specs is not None and "args" in res.specs:
n_random = res.specs["args"].get('n_random_starts', None)
acq_func = res.specs["args"].get("acq_func", "EI")
acq_func_kwargs = res.specs["args"].get("acq_func_kwargs", {})
if acq_func_kwargs is None:
acq_func_kwargs = {}
if acq_func is None or acq_func == "gp_hedge":
acq_func = "EI"
if n_random is None:
n_random = len(res.x_iters) - len(res.models)
if objective is not None:
fx = np.array([objective(x_i) for x_i in x])
if n_calls < 0:
model = res.models[-1]
curr_x_iters = res.x_iters
curr_func_vals = res.func_vals
else:
model = res.models[n_calls]
curr_x_iters = res.x_iters[:n_random + n_calls]
curr_func_vals = res.func_vals[:n_random + n_calls]
# Plot true function.
if objective is not None:
ax.plot(x, fx, "r--", label="True (unknown)")
ax.fill(np.concatenate(
[x, x[::-1]]),
np.concatenate(([fx_i - 1.9600 * noise_level
for fx_i in fx],
[fx_i + 1.9600 * noise_level
for fx_i in fx[::-1]])),
alpha=.2, fc="r", ec="None")
# Plot GP(x) + contours
if show_mu:
y_pred, sigma = model.predict(x_model, return_std=True)
ax.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$")
ax.fill(np.concatenate([x, x[::-1]]),
np.concatenate([y_pred - 1.9600 * sigma,
(y_pred + 1.9600 * sigma)[::-1]]),
alpha=.2, fc="g", ec="None")
# Plot sampled points
if show_observations:
ax.plot(curr_x_iters, curr_func_vals,
"r.", markersize=8, label="Observations")
if (show_mu or show_observations or objective is not None)\
and show_acq_func:
ax_ei = ax.twinx()
ax_ei.set_ylabel(str(acq_func) + "(x)")
plot_both = True
else:
ax_ei = ax
plot_both = False
if show_acq_func:
acq = _gaussian_acquisition(x_model, model,
y_opt=np.min(curr_func_vals),
acq_func=acq_func,
acq_func_kwargs=acq_func_kwargs)
next_x = x[np.argmin(acq)]
next_acq = acq[np.argmin(acq)]
acq = - acq
next_acq = -next_acq
ax_ei.plot(x, acq, "b", label=str(acq_func) + "(x)")
if not plot_both:
ax_ei.fill_between(x.ravel(), 0, acq.ravel(),
alpha=0.3, color='blue')
if show_next_point and next_x is not None:
ax_ei.plot(next_x, next_acq, "bo", markersize=6,
label="Next query point")
if show_title:
ax.set_title(r"x* = %.4f, f(x*) = %.4f" % (res.x[0], res.fun))
# Adjust plot layout
ax.grid()
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
if show_legend:
if plot_both:
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax_ei.get_legend_handles_labels()
ax_ei.legend(lines + lines2, labels + labels2, loc="best",
prop={'size': 6}, numpoints=1)
else:
ax.legend(loc="best", prop={'size': 6}, numpoints=1)
return ax
def plot_regret(*args, **kwargs):
"""Plot one or several cumulative regret traces.
Parameters
----------
args[i] : `OptimizeResult`, list of `OptimizeResult`, or tuple
The result(s) for which to plot the cumulative regret trace.
- if `OptimizeResult`, then draw the corresponding single trace;
- if list of `OptimizeResult`, then draw the corresponding cumulative
regret traces in transparency, along with the average cumulative
regret trace;
- if tuple, then `args[i][0]` should be a string label and `args[i][1]`
an `OptimizeResult` or a list of `OptimizeResult`.
ax : Axes`, optional
The matplotlib axes on which to draw the plot, or `None` to create
a new one.
true_minimum : float, optional
The true minimum value of the function, if known.
yscale : None or string, optional
The scale for the y-axis.
Returns
-------
ax : `Axes`
The matplotlib axes.
"""
# <3 legacy python
ax = kwargs.get("ax", None)
true_minimum = kwargs.get("true_minimum", None)
yscale = kwargs.get("yscale", None)
if ax is None:
ax = plt.gca()
ax.set_title("Cumulative regret plot")
ax.set_xlabel("Number of calls $n$")
ax.set_ylabel(r"$\sum_{i=0}^n(f(x_i) - optimum)$ after $n$ calls")
ax.grid()
if yscale is not None:
ax.set_yscale(yscale)
colors = cm.viridis(np.linspace(0.25, 1.0, len(args)))
if true_minimum is None:
results = []
for res in args:
if isinstance(res, tuple):
res = res[1]
if isinstance(res, OptimizeResult):
results.append(res)
elif isinstance(res, list):
results.extend(res)
true_minimum = np.min([np.min(r.func_vals) for r in results])
for results, color in zip(args, colors):
if isinstance(results, tuple):
name, results = results
else:
name = None
if isinstance(results, OptimizeResult):
n_calls = len(results.x_iters)
regrets = [np.sum(results.func_vals[:i] - true_minimum)
for i in range(1, n_calls + 1)]
ax.plot(range(1, n_calls + 1), regrets, c=color,
marker=".", markersize=12, lw=2, label=name)
elif isinstance(results, list):
n_calls = len(results[0].x_iters)
iterations = range(1, n_calls + 1)
regrets = [[np.sum(r.func_vals[:i] - true_minimum) for i in
iterations] for r in results]
for cr in regrets:
ax.plot(iterations, cr, c=color, alpha=0.2)
ax.plot(iterations, np.mean(regrets, axis=0), c=color,
marker=".", markersize=12, lw=2, label=name)
if name:
ax.legend(loc="best")
return ax
def _format_scatter_plot_axes(ax, space, ylabel, plot_dims,
dim_labels=None):
# Work out min, max of y axis for the diagonal so we can adjust
# them all to the same value
diagonal_ylim = _get_ylim_diagonal(ax)
# Number of search-space dimensions we are using.
if isinstance(ax, (list, np.ndarray)):
n_dims = len(plot_dims)
else:
n_dims = 1
if dim_labels is None:
dim_labels = ["$X_{%i}$" % i if d.name is None else d.name
for i, d in plot_dims]
# Axes for categorical dimensions are really integers; we have to
# label them with the category names
iscat = [isinstance(dim[1], Categorical) for dim in plot_dims]
# Deal with formatting of the axes
for i in range(n_dims): # rows
for j in range(n_dims): # columns
if n_dims > 1:
ax_ = ax[i, j]
else:
ax_ = ax
index_i, dim_i = plot_dims[i]
index_j, dim_j = plot_dims[j]
if j > i:
ax_.axis("off")
elif i > j: # off-diagonal plots
# plots on the diagonal are special, like Texas. They have
# their own range so do not mess with them.
if not iscat[i]: # bounds not meaningful for categoricals
ax_.set_ylim(*dim_i.bounds)
if iscat[j]:
# partial() avoids creating closures in a loop
ax_.xaxis.set_major_formatter(FuncFormatter(
partial(_cat_format, dim_j)))
else:
ax_.set_xlim(*dim_j.bounds)
if j == 0: # only leftmost column (0) gets y labels
ax_.set_ylabel(dim_labels[i])
if iscat[i]: # Set category labels for left column
ax_.yaxis.set_major_formatter(FuncFormatter(
partial(_cat_format, dim_i)))
else:
ax_.set_yticklabels([])
# for all rows except ...
if i < n_dims - 1:
ax_.set_xticklabels([])
# ... the bottom row
else:
[l.set_rotation(45) for l in ax_.get_xticklabels()]
ax_.set_xlabel(dim_labels[j])
# configure plot for linear vs log-scale
if dim_j.prior == 'log-uniform':
ax_.set_xscale('log')
else:
ax_.xaxis.set_major_locator(MaxNLocator(6, prune='both',
integer=iscat[j]))
if dim_i.prior == 'log-uniform':
ax_.set_yscale('log')
else:
ax_.yaxis.set_major_locator(MaxNLocator(6, prune='both',
integer=iscat[i]))
else: # diagonal plots
ax_.set_ylim(*diagonal_ylim)
if not iscat[i]:
low, high = dim_i.bounds
ax_.set_xlim(low, high)
ax_.yaxis.tick_right()
ax_.yaxis.set_label_position('right')
ax_.yaxis.set_ticks_position('both')
ax_.set_ylabel(ylabel)
ax_.xaxis.tick_top()
ax_.xaxis.set_label_position('top')
ax_.set_xlabel(dim_labels[j])
if dim_i.prior == 'log-uniform':
ax_.set_xscale('log')
else:
ax_.xaxis.set_major_locator(MaxNLocator(6, prune='both',
integer=iscat[i]))
if iscat[i]:
ax_.xaxis.set_major_formatter(FuncFormatter(
partial(_cat_format, dim_i)))
return ax
def partial_dependence(space, model, i, j=None, sample_points=None,
n_samples=250, n_points=40, x_eval=None):
"""Calculate the partial dependence for dimensions `i` and `j` with
respect to the objective value, as approximated by `model`.
The partial dependence plot shows how the value of the dimensions
`i` and `j` influence the `model` predictions after "averaging out"
the influence of all other dimensions.
When `x_eval` is not `None`, the given values are used instead of
random samples. In this case, `n_samples` will be ignored.
Parameters
----------
space : `Space`
The parameter space over which the minimization was performed.
model
Surrogate model for the objective function.
i : int
The first dimension for which to calculate the partial dependence.
j : int, default=None
The second dimension for which to calculate the partial dependence.
To calculate the 1D partial dependence on `i` alone set `j=None`.
sample_points : np.array, shape=(n_points, n_dims), default=None
Only used when `x_eval=None`, i.e in case partial dependence should
be calculated.
Randomly sampled and transformed points to use when averaging
the model function at each of the `n_points` when using partial
dependence.
n_samples : int, default=100
Number of random samples to use for averaging the model function
at each of the `n_points` when using partial dependence. Only used
when `sample_points=None` and `x_eval=None`.
n_points : int, default=40
Number of points at which to evaluate the partial dependence
along each dimension `i` and `j`.
x_eval : list, default=None
`x_eval` is a list of parameter values or None. In case `x_eval`
is not None, the parsed dependence will be calculated using these
values.
Otherwise, random selected samples will be used.
Returns
-------
For 1D partial dependence:
xi : np.array
The points at which the partial dependence was evaluated.
yi : np.array
The value of the model at each point `xi`.
For 2D partial dependence:
xi : np.array, shape=n_points
The points at which the partial dependence was evaluated.
yi : np.array, shape=n_points
The points at which the partial dependence was evaluated.
zi : np.array, shape=(n_points, n_points)
The value of the model at each point `(xi, yi)`.
For Categorical variables, the `xi` (and `yi` for 2D) returned are
the indices of the variable in `Dimension.categories`.
"""
# If we haven't parsed an x_eval list we use random sampled values instead
if x_eval is None and sample_points is None:
sample_points = space.transform(space.rvs(n_samples=n_samples))
elif sample_points is None:
sample_points = space.transform([x_eval])
if j is None:
return partial_dependence_1D(space, model, i,
sample_points, n_points)
else:
return partial_dependence_2D(space, model, i, j,
sample_points, n_points)
def plot_objective(result, levels=10, n_points=40, n_samples=250, size=2,
zscale='linear', dimensions=None, sample_source='random',
minimum='result', n_minimum_search=None, plot_dims=None,
show_points=True, cmap='viridis_r'):
"""Plot a 2-d matrix with so-called Partial Dependence plots
of the objective function. This shows the influence of each
search-space dimension on the objective function.
This uses the last fitted model for estimating the objective function.
The diagonal shows the effect of a single dimension on the
objective function, while the plots below the diagonal show
the effect on the objective function when varying two dimensions.
The Partial Dependence is calculated by averaging the objective value
for a number of random samples in the search-space,
while keeping one or two dimensions fixed at regular intervals. This
averages out the effect of varying the other dimensions and shows
the influence of one or two dimensions on the objective function.
Also shown are small black dots for the points that were sampled
during optimization.
A red star indicates per default the best observed minimum, but
this can be changed by changing argument ´minimum´.
.. note::
The Partial Dependence plot is only an estimation of the surrogate
model which in turn is only an estimation of the true objective
function that has been optimized. This means the plots show
an "estimate of an estimate" and may therefore be quite imprecise,
especially if few samples have been collected during the
optimization
(e.g. less than 100-200 samples), and in regions of the search-space
that have been sparsely sampled (e.g. regions away from the optimum).
This means that the plots may change each time you run the
optimization and they should not be considered completely reliable.
These compromises are necessary because we cannot evaluate the
expensive objective function in order to plot it, so we have to use
the cheaper surrogate model to plot its contour. And in order to
show search-spaces with 3 dimensions or more in a 2-dimensional
plot,
we further need to map those dimensions to only 2-dimensions using
the Partial Dependence, which also causes distortions in the plots.
Parameters
----------
result : `OptimizeResult`
The optimization results from calling e.g. `gp_minimize()`.
levels : int, default=10
Number of levels to draw on the contour plot, passed directly
to `plt.contourf()`.
n_points : int, default=40
Number of points at which to evaluate the partial dependence
along each dimension.
n_samples : int, default=250
Number of samples to use for averaging the model function
at each of the `n_points` when `sample_method` is set to 'random'.
size : float, default=2
Height (in inches) of each facet.
zscale : str, default='linear'
Scale to use for the z axis of the contour plots. Either 'linear'
or 'log'.
dimensions : list of str, default=None
Labels of the dimension
variables. `None` defaults to `space.dimensions[i].name`, or
if also `None` to `['X_0', 'X_1', ..]`.
plot_dims : list of str and int, default=None
List of dimension names or dimension indices from the
search-space dimensions to be included in the plot.
If `None` then use all dimensions except constant ones
from the search-space.
sample_source : str or list of floats, default='random'
Defines to samples generation to use for averaging the model function
at each of the `n_points`.
A partial dependence plot is only generated, when `sample_source`
is set to 'random' and `n_samples` is sufficient.
`sample_source` can also be a list of
floats, which is then used for averaging.
Valid strings:
- 'random' - `n_samples` random samples will used
- 'result' - Use only the best observed parameters
- 'expected_minimum' - Parameters that gives the best
minimum Calculated using scipy's minimize method.
This method currently does not work with categorical values.
- 'expected_minimum_random' - Parameters that gives the
best minimum when using naive random sampling.
Works with categorical values.
minimum : str or list of floats, default = 'result'
Defines the values for the red points in the plots.
Valid strings:
- 'result' - Use best observed parameters
- 'expected_minimum' - Parameters that gives the best
minimum Calculated using scipy's minimize method.
This method currently does not work with categorical values.
- 'expected_minimum_random' - Parameters that gives the
best minimum when using naive random sampling.
Works with categorical values
n_minimum_search : int, default = None
Determines how many points should be evaluated
to find the minimum when using 'expected_minimum' or
'expected_minimum_random'. Parameter is used when
`sample_source` and/or `minimum` is set to
'expected_minimum' or 'expected_minimum_random'.
show_points: bool, default = True
Choose whether to show evaluated points in the
contour plots.
cmap: str or Colormap, default = 'viridis_r'
Color map for contour plots. Passed directly to
`plt.contourf()`
Returns
-------
ax : `Matplotlib.Axes`
A 2-d matrix of Axes-objects with the sub-plots.
"""
# Here we define the values for which to plot the red dot (2d plot) and
# the red dotted line (1d plot).
# These same values will be used for evaluating the plots when
# calculating dependence. (Unless partial
# dependence is to be used instead).
space = result.space
# Get the relevant search-space dimensions.
if plot_dims is None:
# Get all dimensions.
plot_dims = []
for row in range(space.n_dims):
if space.dimensions[row].is_constant:
continue
plot_dims.append((row, space.dimensions[row]))
else:
plot_dims = space[plot_dims]
# Number of search-space dimensions we are using.
n_dims = len(plot_dims)
if dimensions is not None:
assert len(dimensions) == n_dims
x_vals = _evaluate_min_params(result, minimum, n_minimum_search)
if sample_source == "random":
x_eval = None
samples = space.transform(space.rvs(n_samples=n_samples))
else:
x_eval = _evaluate_min_params(result, sample_source,
n_minimum_search)
samples = space.transform([x_eval])
x_samples, minimum, _ = _map_categories(space, result.x_iters, x_vals)
if zscale == 'log':
locator = LogLocator()
elif zscale == 'linear':
locator = None
else:
raise ValueError("Valid values for zscale are 'linear' and 'log',"
" not '%s'." % zscale)
fig, ax = plt.subplots(n_dims, n_dims,
figsize=(size * n_dims, size * n_dims))
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,
hspace=0.1, wspace=0.1)
for i in range(n_dims):
for j in range(n_dims):
if i == j:
index, dim = plot_dims[i]
xi, yi = partial_dependence_1D(space, result.models[-1],
index,
samples=samples,
n_points=n_points)
if n_dims > 1:
ax_ = ax[i, i]
else:
ax_ = ax
ax_.plot(xi, yi)
ax_.axvline(minimum[index], linestyle="--", color="r", lw=1)
# lower triangle
elif i > j:
index1, dim1 = plot_dims[i]
index2, dim2 = plot_dims[j]
ax_ = ax[i, j]
xi, yi, zi = partial_dependence_2D(space, result.models[-1],
index1, index2,
samples, n_points)
ax_.contourf(xi, yi, zi, levels,
locator=locator, cmap=cmap)
if show_points:
ax_.scatter(x_samples[:, index2], x_samples[:, index1],
c='k', s=10, lw=0.)
ax_.scatter(minimum[index2], minimum[index1],
c=['r'], s=100, lw=0., marker='*')
ylabel = "Partial dependence"
# Make various adjustments to the plots.
return _format_scatter_plot_axes(ax, space, ylabel=ylabel,
plot_dims=plot_dims,
dim_labels=dimensions)
def plot_evaluations(result, bins=20, dimensions=None,
plot_dims=None):
"""Visualize the order in which points were sampled during optimization.
This creates a 2-d matrix plot where the diagonal plots are histograms
that show the distribution of samples for each search-space dimension.
The plots below the diagonal are scatter-plots of the samples for
all combinations of search-space dimensions.
The order in which samples
were evaluated is encoded in each point's color.
A red star shows the best found parameters.
Parameters
----------
result : `OptimizeResult`
The optimization results from calling e.g. `gp_minimize()`.
bins : int, bins=20
Number of bins to use for histograms on the diagonal.
dimensions : list of str, default=None
Labels of the dimension
variables. `None` defaults to `space.dimensions[i].name`, or
if also `None` to `['X_0', 'X_1', ..]`.
plot_dims : list of str and int, default=None
List of dimension names or dimension indices from the
search-space dimensions to be included in the plot.
If `None` then use all dimensions except constant ones
from the search-space.
Returns
-------
ax : `Matplotlib.Axes`
A 2-d matrix of Axes-objects with the sub-plots.
"""
space = result.space
# Convert categoricals to integers, so we can ensure consistent ordering.
# Assign indices to categories in the order they appear in the Dimension.
# Matplotlib's categorical plotting functions are only present in v 2.1+,
# and may order categoricals differently in different plots anyway.
samples, minimum, iscat = _map_categories(space, result.x_iters, result.x)
order = range(samples.shape[0])
if plot_dims is None:
# Get all dimensions.
plot_dims = []
for row in range(space.n_dims):
if space.dimensions[row].is_constant:
continue
plot_dims.append((row, space.dimensions[row]))
else:
plot_dims = space[plot_dims]
# Number of search-space dimensions we are using.
n_dims = len(plot_dims)
if dimensions is not None:
assert len(dimensions) == n_dims
fig, ax = plt.subplots(n_dims, n_dims,
figsize=(2 * n_dims, 2 * n_dims))
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,
hspace=0.1, wspace=0.1)
for i in range(n_dims):
for j in range(n_dims):
if i == j:
index, dim = plot_dims[i]
if iscat[j]:
bins_ = len(dim.categories)
elif dim.prior == 'log-uniform':
low, high = space.bounds[index]
bins_ = np.logspace(np.log10(low), np.log10(high), bins)
else:
bins_ = bins
if n_dims == 1:
ax_ = ax
else:
ax_ = ax[i, i]
ax_.hist(samples[:, index], bins=bins_,
range=None if iscat[j] else dim.bounds)
# lower triangle
elif i > j:
index_i, dim_i = plot_dims[i]
index_j, dim_j = plot_dims[j]
ax_ = ax[i, j]
ax_.scatter(samples[:, index_j], samples[:, index_i],
c=order, s=40, lw=0., cmap='viridis')
ax_.scatter(minimum[index_j], minimum[index_i],
c=['r'], s=100, lw=0., marker='*')
# Make various adjustments to the plots.
return _format_scatter_plot_axes(ax, space, ylabel="Number of samples",
plot_dims=plot_dims,
dim_labels=dimensions)
def _get_ylim_diagonal(ax):
"""Get the min / max of the ylim for all diagonal plots.
This is used in _adjust_fig() so the ylim is the same
for all diagonal plots.
Parameters
----------
ax : `Matplotlib.Axes`
2-dimensional matrix with Matplotlib Axes objects.
Returns
-------
ylim_diagonal : tuple(int)
The common min and max ylim for the diagonal plots.
"""
# Number of search-space dimensions used in this plot.
if isinstance(ax, (list, np.ndarray)):
n_dims = len(ax)
# Get ylim for all diagonal plots.
ylim = [ax[row, row].get_ylim() for row in range(n_dims)]
else:
n_dim = 1
ylim = [ax.get_ylim()]
# Separate into two lists with low and high ylim.
ylim_lo, ylim_hi = zip(*ylim)
# Min and max ylim for all diagonal plots.
ylim_min = np.min(ylim_lo)
ylim_max = np.max(ylim_hi)
return ylim_min, ylim_max
def partial_dependence_1D(space, model, i, samples,
n_points=40):
"""
Calculate the partial dependence for a single dimension.
This uses the given model to calculate the average objective value
for all the samples, where the given dimension is fixed at
regular intervals between its bounds.
This shows how the given dimension affects the objective value
when the influence of all other dimensions are averaged out.
Parameters
----------
space : `Space`
The parameter space over which the minimization was performed.
model
Surrogate model for the objective function.
i : int
The dimension for which to calculate the partial dependence.
samples : np.array, shape=(n_points, n_dims)
Randomly sampled and transformed points to use when averaging
the model function at each of the `n_points` when using partial
dependence.
n_points : int, default=40
Number of points at which to evaluate the partial dependence
along each dimension `i`.
Returns
-------
xi : np.array
The points at which the partial dependence was evaluated.
yi : np.array
The average value of the modelled objective function at
each point `xi`.
"""
# The idea is to step through one dimension, evaluating the model with
# that dimension fixed and averaging either over random values or over
# the given ones in x_val in all other dimensions.
# (Or step through 2 dimensions when i and j are given.)
# Categorical dimensions make this interesting, because they are one-
# hot-encoded, so there is a one-to-many mapping of input dimensions
# to transformed (model) dimensions.
# dim_locs[i] is the (column index of the) start of dim i in
# sample_points.
# This is usefull when we are using one hot encoding, i.e using
# categorical values
dim_locs = np.cumsum([0] + [d.transformed_size for d in space.dimensions])
def _calc(x):
"""
Helper-function to calculate the average predicted
objective value for the given model, when setting
the index'th dimension of the search-space to the value x,
and then averaging over all samples.
"""
rvs_ = np.array(samples) # copy
# We replace the values in the dimension that we want to keep
# fixed
rvs_[:, dim_locs[i]:dim_locs[i + 1]] = x
# In case of `x_eval=None` rvs conists of random samples.
# Calculating the mean of these samples is how partial dependence
# is implemented.
return np.mean(model.predict(rvs_))
xi, xi_transformed = _evenly_sample(space.dimensions[i], n_points)
# Calculate the partial dependence for all the points.
yi = [_calc(x) for x in xi_transformed]
return xi, yi
def partial_dependence_2D(space, model, i, j, samples,
n_points=40):
"""
Calculate the partial dependence for two dimensions in the search-space.
This uses the given model to calculate the average objective value
for all the samples, where the given dimensions are fixed at
regular intervals between their bounds.
This shows how the given dimensions affect the objective value
when the influence of all other dimensions are averaged out.
Parameters
----------
space : `Space`
The parameter space over which the minimization was performed.
model
Surrogate model for the objective function.
i : int
The first dimension for which to calculate the partial dependence.
j : int
The second dimension for which to calculate the partial dependence.
samples : np.array, shape=(n_points, n_dims)