Tutorial BalancingLearner

Note

Because this documentation consists of static html, the live_plot and live_info widget is not live. Download the notebook in order to see the real behaviour.

See also

The complete source code of this tutorial can be found in tutorial.BalancingLearner.ipynb

The balancing learner is a “meta-learner” that takes a list of learners. When you request a point from the balancing learner, it will query all of its “children” to figure out which one will give the most improvement.

The balancing learner can for example be used to implement a poor-man’s 2D learner by using the Learner1D.

def h(x, offset=0):
    a = 0.01
    return x + a**2 / (a**2 + (x - offset)**2)

learners = [adaptive.Learner1D(partial(h, offset=random.uniform(-1, 1)),
            bounds=(-1, 1)) for i in range(10)]

bal_learner = adaptive.BalancingLearner(learners)
runner = adaptive.Runner(bal_learner, goal=lambda l: l.loss() < 0.01)
runner.live_info()
plotter = lambda learner: hv.Overlay([L.plot() for L in learner.learners])
runner.live_plot(plotter=plotter, update_interval=0.1)

Often one wants to create a set of learners for a cartesian product of parameters. For that particular case we’ve added a classmethod called from_product. See how it works below

from scipy.special import eval_jacobi

def jacobi(x, n, alpha, beta): return eval_jacobi(n, alpha, beta, x)

combos = {
    'n': [1, 2, 4, 8],
    'alpha': np.linspace(0, 2, 3),
    'beta': np.linspace(0, 1, 5),
}

learner = adaptive.BalancingLearner.from_product(
    jacobi, adaptive.Learner1D, dict(bounds=(0, 1)), combos)

runner = adaptive.BlockingRunner(learner, goal=lambda l: l.loss() < 0.01)

# The `cdims` will automatically be set when using `from_product`, so
# `plot()` will return a HoloMap with correctly labeled sliders.
learner.plot().overlay('beta').grid().select(y=(-1, 3))
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj, include, exclude)
    968 
    969             if method is not None:
--> 970                 return method(include=include, exclude=exclude)
    971             return None
    972         else:

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/core/dimension.py in _repr_mimebundle_(self, include, exclude)
   1391         combined and returned.
   1392         """
-> 1393         return Store.render(self)
   1394 
   1395 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/core/options.py in render(cls, obj)
   1451         data, metadata = {}, {}
   1452         for hook in hooks:
-> 1453             ret = hook(obj)
   1454             if ret is None:
   1455                 continue

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/ipython/display_hooks.py in pprint_display(obj)
    270     if not ip.display_formatter.formatters['text/plain'].pprint:
    271         return None
--> 272     return display(obj, raw_output=True)
    273 
    274 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/ipython/display_hooks.py in display(obj, raw_output, **kwargs)
    237     if isinstance(obj, GridSpace):
    238         with option_state(obj):
--> 239             output = grid_display(obj)
    240     elif isinstance(obj, (CompositeOverlay, ViewableElement)):
    241         with option_state(obj):

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/ipython/display_hooks.py in wrapped(element)
    140         try:
    141             max_frames = OutputSettings.options['max_frames']
--> 142             mimebundle = fn(element, max_frames=max_frames)
    143             if mimebundle is None:
    144                 return {}, {}

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/ipython/display_hooks.py in grid_display(grid, max_frames)
    225         return None
    226 
--> 227     return render(grid)
    228 
    229 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/ipython/display_hooks.py in render(obj, **kwargs)
     63         renderer = renderer.instance(fig='png')
     64 
---> 65     return renderer.components(obj, **kwargs)
     66 
     67 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/renderer.py in components(self, obj, fmt, comm, **kwargs)
    247         # Bokeh has to handle comms directly in <0.12.15
    248         comm = False if bokeh_version < '0.12.15' else comm
--> 249         return super(BokehRenderer, self).components(obj,fmt, comm, **kwargs)
    250 
    251 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/renderer.py in components(self, obj, fmt, comm, **kwargs)
    319             plot = obj
    320         else:
--> 321             plot, fmt = self._validate(obj, fmt)
    322 
    323         widget_id = None

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/renderer.py in _validate(self, obj, fmt, **kwargs)
    218         if isinstance(obj, tuple(self.widgets.values())):
    219             return obj, 'html'
--> 220         plot = self.get_plot(obj, renderer=self, **kwargs)
    221 
    222         fig_formats = self.mode_formats['fig'][self.mode]

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/renderer.py in get_plot(self_or_cls, obj, doc, renderer, **kwargs)
    132             curdoc().theme = self_or_cls.theme
    133         doc.theme = self_or_cls.theme
--> 134         plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer, **kwargs)
    135         plot.document = doc
    136         return plot

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/renderer.py in get_plot(self_or_cls, obj, renderer, **kwargs)
    205             init_key = tuple(v if d is None else d for v, d in
    206                              zip(plot.keys[0], defaults))
--> 207             plot.update(init_key)
    208         else:
    209             plot = obj

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/plot.py in update(self, key)
    593     def update(self, key):
    594         if len(self) == 1 and ((key == 0) or (key == self.keys[0])) and not self.drawn:
--> 595             return self.initialize_plot()
    596         item = self.__getitem__(key)
    597         self.traverse(lambda x: setattr(x, '_updated', True))

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/plot.py in initialize_plot(self, ranges, plots)
    647         plot = gridplot(plots[::-1], toolbar_location=self.toolbar,
    648                         merge_tools=self.merge_tools)
--> 649         plot = self._make_axes(plot)
    650 
    651         title = self._get_title_div(self.keys[-1])

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/plot.py in _make_axes(self, plot)
    670 
    671     def _make_axes(self, plot):
--> 672         width, height = self.renderer.get_size(plot)
    673         x_axis, y_axis = None, None
    674         kwargs = dict(sizing_mode=self.sizing_mode)

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/renderer.py in get_size(self_or_cls, plot)
    354             raise ValueError('Can only compute sizes for HoloViews '
    355                              'and bokeh plot objects.')
--> 356         return compute_plot_size(plot)
    357 
    358 

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/util.py in compute_plot_size(plot)
    148         else:
    149             w_agg, h_agg = (np.max, np.sum)
--> 150         widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
    151         width, height = w_agg(widths), h_agg(heights)
    152     elif isinstance(plot, (Figure, Chart)):

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/util.py in <listcomp>(.0)
    148         else:
    149             w_agg, h_agg = (np.max, np.sum)
--> 150         widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
    151         width, height = w_agg(widths), h_agg(heights)
    152     elif isinstance(plot, (Figure, Chart)):

~/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.8.1/lib/python3.6/site-packages/holoviews/plotting/bokeh/util.py in compute_plot_size(plot)
    154     elif isinstance(plot, (Plot, DataTable, Spacer)):
    155         width, height = plot.width, plot.height
--> 156     return width, height
    157 
    158 

UnboundLocalError: local variable 'width' referenced before assignment
:GridSpace   [n,alpha]
   :NdOverlay   [beta]
      :Overlay
         .Scatter.I :Scatter   [x]   (y)
         .Path.I    :Path   [x,y]