Skip to content

adaptive.BalancingLearner

BalancingLearner

BalancingLearner(learners: list[BaseLearner], *, cdims: CDIMS_TYPE = None, strategy: STRATEGY_TYPE = 'loss_improvements')

Bases: BaseLearner

Choose the optimal points from a set of learners.

Parameters:

Name Type Description Default
learners sequence of adaptive.BaseLearner\s

The learners from which to choose. These must all have the same type.

required
cdims sequence of dicts, or (keys, iterable of values)

Constant dimensions; the parameters that label the learners. Used in plot. Example inputs that all give identical results:

  • sequence of dicts:

    cdims = [{'A': True, 'B': 0}, ... {'A': True, 'B': 1}, ... {'A': False, 'B': 0}, ... {'A': False, 'B': 1}]`

  • tuple with (keys, iterable of values):

    cdims = (['A', 'B'], itertools.product([True, False], [0, 1])) cdims = (['A', 'B'], [(True, 0), (True, 1), ... (False, 0), (False, 1)])

None

Attributes:

Name Type Description
learners list

The sequence of BaseLearner\s.

function callable

A function that calls the functions of the underlying learners. Its signature is function(learner_index, point).

strategy 'loss_improvements' (default), 'loss', 'npoints', or 'cycle'.

The points that the BalancingLearner choses can be either based on: the best 'loss_improvements', the smallest total 'loss' of the child learners, the number of points per learner, using 'npoints', or by cycling through the learners one by one using 'cycle'. One can dynamically change the strategy while the simulation is running by changing the learner.strategy attribute.

Notes

This learner compares the loss calculated from the "child" learners. This requires that the 'loss' from different learners can be meaningfully compared. For the moment we enforce this restriction by requiring that all learners are the same type but (depending on the internals of the learner) it may be that the loss cannot be compared even between learners of the same type. In this case the BalancingLearner will behave in an undefined way. Change the strategy in that case.

Source code in adaptive/learner/balancing_learner.py
def __init__(
    self,
    learners: list[BaseLearner],
    *,
    cdims: CDIMS_TYPE = None,
    strategy: STRATEGY_TYPE = "loss_improvements",
) -> None:
    self.learners = learners

    # Naively we would make 'function' a method, but this causes problems
    # when using executors from 'concurrent.futures' because we have to
    # pickle the whole learner.
    self.function = partial(dispatch, [lrn.function for lrn in self.learners])  # type: ignore

    self._ask_cache: dict[int, Any] = {}
    self._loss: dict[int, float] = {}
    self._pending_loss: dict[int, float] = {}
    self._cdims_default = cdims

    if len({learner.__class__ for learner in self.learners}) > 1:
        raise TypeError("A BalacingLearner can handle only one type of learners.")

    self.strategy: STRATEGY_TYPE = strategy

learners instance-attribute

learners = learners

function instance-attribute

function = partial(dispatch, [lrn.function for lrn in self.learners])

strategy property writable

strategy: STRATEGY_TYPE

Can be either 'loss_improvements' (default), 'loss', 'npoints', or 'cycle'. The points that the BalancingLearner choses can be either based on: the best 'loss_improvements', the smallest total 'loss' of the child learners, the number of points per learner, using 'npoints', or by going through all learners one by one using 'cycle'. One can dynamically change the strategy while the simulation is running by changing the learner.strategy attribute.

data property

data: dict[tuple[int, Any], Any]

pending_points property

pending_points: set[tuple[int, Any]]

npoints property

npoints: int

nsamples property

nsamples

new

Create a new BalancingLearner with the same parameters.

Source code in adaptive/learner/balancing_learner.py
def new(self) -> BalancingLearner:
    """Create a new `BalancingLearner` with the same parameters."""
    return BalancingLearner(
        [learner.new() for learner in self.learners],
        cdims=self._cdims_default,
        strategy=self.strategy,
    )

ask

ask(n: int, tell_pending: bool = True) -> tuple[list[tuple[Int, Any]], list[float]]

Chose points for learners.

Source code in adaptive/learner/balancing_learner.py
def ask(
    self, n: int, tell_pending: bool = True
) -> tuple[list[tuple[Int, Any]], list[float]]:
    """Chose points for learners."""
    if n == 0:
        return [], []

    if not tell_pending:
        with restore(*self.learners):
            return self._ask_and_tell(n)
    else:
        return self._ask_and_tell(n)

tell

tell(x: tuple[Int, Any], y: Any) -> None
Source code in adaptive/learner/balancing_learner.py
def tell(self, x: tuple[Int, Any], y: Any) -> None:
    index, x_ = x
    self._ask_cache.pop(index, None)
    self._loss.pop(index, None)
    self._pending_loss.pop(index, None)
    self.learners[index].tell(x_, y)

tell_pending

tell_pending(x: tuple[Int, Any]) -> None
Source code in adaptive/learner/balancing_learner.py
def tell_pending(self, x: tuple[Int, Any]) -> None:
    index, x_ = x
    self._ask_cache.pop(index, None)
    self._loss.pop(index, None)
    self.learners[index].tell_pending(x_)

loss

loss(real: bool = True) -> float
Source code in adaptive/learner/balancing_learner.py
@cache_latest
def loss(self, real: bool = True) -> float:
    losses = self._losses(real)
    return max(losses)

plot

plot(cdims: CDIMS_TYPE = None, plotter: Callable[[BaseLearner], Any] | None = None, dynamic: bool = True)

Returns a DynamicMap with sliders.

Parameters:

Name Type Description Default
cdims sequence of dicts, or (keys, iterable of values)

Constant dimensions; the parameters that label the learners. Example inputs that all give identical results:

  • sequence of dicts:

    cdims = [{'A': True, 'B': 0}, ... {'A': True, 'B': 1}, ... {'A': False, 'B': 0}, ... {'A': False, 'B': 1}]`

  • tuple with (keys, iterable of values):

    cdims = (['A', 'B'], itertools.product([True, False], [0, 1])) cdims = (['A', 'B'], [(True, 0), (True, 1), ... (False, 0), (False, 1)])

None
plotter callable

A function that takes the learner as a argument and returns a holoviews object. By default learner.plot() will be called.

None
dynamic bool

Return a holoviews.core.DynamicMap if True, else a holoviews.core.HoloMap. The DynamicMap is rendered as the sliders change and can therefore not be exported to html. The HoloMap does not have this problem.

True

Returns:

Name Type Description
dm DynamicMap(default) or HoloMap

A DynamicMap (dynamic=True) or HoloMap (dynamic=False) with sliders that are defined by cdims.

Source code in adaptive/learner/balancing_learner.py
def plot(
    self,
    cdims: CDIMS_TYPE = None,
    plotter: Callable[[BaseLearner], Any] | None = None,
    dynamic: bool = True,
):
    """Returns a DynamicMap with sliders.

    Parameters
    ----------
    cdims : sequence of dicts, or (keys, iterable of values), optional
        Constant dimensions; the parameters that label the learners.
        Example inputs that all give identical results:

        - sequence of dicts:

            >>> cdims = [{'A': True, 'B': 0},
            ...          {'A': True, 'B': 1},
            ...          {'A': False, 'B': 0},
            ...          {'A': False, 'B': 1}]`

        - tuple with (keys, iterable of values):

            >>> cdims = (['A', 'B'], itertools.product([True, False], [0, 1]))
            >>> cdims = (['A', 'B'], [(True, 0), (True, 1),
            ...                       (False, 0), (False, 1)])

    plotter : callable, optional
        A function that takes the learner as a argument and returns a
        holoviews object. By default ``learner.plot()`` will be called.
    dynamic : bool, default True
        Return a `holoviews.core.DynamicMap` if True, else a
        `holoviews.core.HoloMap`. The `~holoviews.core.DynamicMap` is
        rendered as the sliders change and can therefore not be exported
        to html. The `~holoviews.core.HoloMap` does not have this problem.

    Returns
    -------
    dm : `holoviews.core.DynamicMap` (default) or `holoviews.core.HoloMap`
         A `DynamicMap` ``(dynamic=True)`` or `HoloMap`
         ``(dynamic=False)`` with sliders that are defined by `cdims`.
    """
    hv = ensure_holoviews()
    cdims = cdims or self._cdims_default

    if cdims is None:
        cdims = [{"i": i} for i in range(len(self.learners))]
    elif not isinstance(cdims[0], dict):
        # Normalize the format
        keys, values_list = cdims
        cdims = [dict(zip(keys, values)) for values in values_list]
    cdims = cast(list[dict[str, Real]], cdims)
    mapping = {
        tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims)
    }

    d = defaultdict(list)
    for _cdims in cdims:
        for k, v in _cdims.items():
            d[k].append(v)

    def plot_function(*args):
        with suppress(KeyError):
            learner = mapping[tuple(args)]
            return learner.plot() if plotter is None else plotter(learner)

    dm = hv.DynamicMap(plot_function, kdims=list(d.keys()))
    dm = dm.redim.values(**d)
    dm.cache_size = 1

    if dynamic:
        # XXX: change when https://github.com/pyviz/holoviews/issues/3637
        # is fixed.
        return dm.map(lambda obj: obj.opts(framewise=True), hv.Element)
    else:
        # XXX: change when https://github.com/ioam/holoviews/issues/3085
        # is fixed.
        vals = {d.name: d.values for d in dm.dimensions() if d.values}
        return hv.HoloMap(dm.select(**vals))

remove_unfinished

remove_unfinished() -> None

Remove uncomputed data from the learners.

Source code in adaptive/learner/balancing_learner.py
def remove_unfinished(self) -> None:
    """Remove uncomputed data from the learners."""
    for learner in self.learners:
        learner.remove_unfinished()

from_product classmethod

from_product(f, learner_type: LearnerType, learner_kwargs: dict[str, Any], combos: dict[str, Sequence[Any]]) -> BalancingLearner

Create a BalancingLearner with learners of all combinations of named variables’ values. The cdims will be set correctly, so calling learner.plot will be a holoviews.core.HoloMap with the correct labels.

Parameters:

Name Type Description Default
f callable

Function to learn, must take arguments provided in in combos.

required
learner_type BaseLearner

The learner that should wrap the function. For example Learner1D.

required
learner_kwargs dict

Keyword argument for the learner_type. For example dict(bounds=[0, 1]).

required
combos dict (mapping individual fn arguments -> sequence of values)

For all combinations of each argument a learner will be instantiated.

required

Returns:

Name Type Description
learner BalancingLearner

A BalancingLearner with learners of all combinations of combos

Example

def f(x, n, alpha, beta): ... return scipy.special.eval_jacobi(n, alpha, beta, x)

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

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

Notes

The order of the child learners inside learner.learners is the same as adaptive.utils.named_product(**combos).

Source code in adaptive/learner/balancing_learner.py
@classmethod
def from_product(
    cls,
    f,
    learner_type: LearnerType,
    learner_kwargs: dict[str, Any],
    combos: dict[str, Sequence[Any]],
) -> BalancingLearner:
    """Create a `BalancingLearner` with learners of all combinations of
    named variables’ values. The `cdims` will be set correctly, so calling
    `learner.plot` will be a `holoviews.core.HoloMap` with the correct labels.

    Parameters
    ----------
    f : callable
        Function to learn, must take arguments provided in in `combos`.
    learner_type : `BaseLearner`
        The learner that should wrap the function. For example `Learner1D`.
    learner_kwargs : dict
        Keyword argument for the `learner_type`. For example `dict(bounds=[0, 1])`.
    combos : dict (mapping individual fn arguments -> sequence of values)
        For all combinations of each argument a learner will be instantiated.

    Returns
    -------
    learner : `BalancingLearner`
        A `BalancingLearner` with learners of all combinations of `combos`

    Example
    -------
    >>> def f(x, n, alpha, beta):
    ...     return scipy.special.eval_jacobi(n, alpha, beta, x)

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

    >>> learner = BalancingLearner.from_product(
    ...     f, Learner1D, dict(bounds=(0, 1)), combos)

    Notes
    -----
    The order of the child learners inside `learner.learners` is the same
    as ``adaptive.utils.named_product(**combos)``.
    """
    learners = []
    arguments = named_product(**combos)
    for combo in arguments:
        learner = learner_type(function=partial(f, **combo), **learner_kwargs)  # type: ignore[operator]
        learners.append(learner)
    return cls(learners, cdims=arguments)

to_dataframe

to_dataframe(index_name: str = 'learner_index', **kwargs)

Return the data as a concatenated pandas.DataFrame from child learners.

Parameters:

Name Type Description Default
index_name str

The name of the index column indicating the learner index, by default "learner_index".

'learner_index'
**kwargs dict

Keyword arguments passed to each child_learner.to_dataframe(**kwargs).

{}

Returns:

Type Description
DataFrame

Raises:

Type Description
ImportError

If pandas is not installed.

Source code in adaptive/learner/balancing_learner.py
def to_dataframe(self, index_name: str = "learner_index", **kwargs):  # type: ignore[override]
    """Return the data as a concatenated `pandas.DataFrame` from child learners.

    Parameters
    ----------
    index_name : str, optional
        The name of the index column indicating the learner index,
        by default "learner_index".
    **kwargs : dict
        Keyword arguments passed to each ``child_learner.to_dataframe(**kwargs)``.

    Returns
    -------
    pandas.DataFrame

    Raises
    ------
    ImportError
        If `pandas` is not installed.
    """
    if not with_pandas:
        raise ImportError("pandas is not installed.")
    dfs = []
    for i, learner in enumerate(self.learners):
        df = learner.to_dataframe(**kwargs)
        cols = list(df.columns)
        df[index_name] = i
        df = df[[index_name] + cols]
        dfs.append(df)
    df = pandas.concat(dfs, axis=0, ignore_index=True)
    return df

load_dataframe

load_dataframe(df: DataFrame, index_name: str = 'learner_index', **kwargs)

Load the data from a pandas.DataFrame into the child learners.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with the data to load.

required
index_name str

The index_name used in to_dataframe, by default "learner_index".

'learner_index'
**kwargs dict

Keyword arguments passed to each child_learner.load_dataframe(**kwargs).

{}
Source code in adaptive/learner/balancing_learner.py
def load_dataframe(  # type: ignore[override]
    self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs
):
    """Load the data from a `pandas.DataFrame` into the child learners.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame with the data to load.
    index_name : str, optional
        The ``index_name`` used in `to_dataframe`, by default "learner_index".
    **kwargs : dict
        Keyword arguments passed to each ``child_learner.load_dataframe(**kwargs)``.
    """
    for i, gr in df.groupby(index_name):
        self.learners[i].load_dataframe(gr, **kwargs)

save

save(fname: Callable[[BaseLearner], str] | Sequence[str], compress: bool = True) -> None

Save the data of the child learners into pickle files in a directory.

Parameters:

Name Type Description Default
fname Callable[[BaseLearner], str] | Sequence[str]

Given a learner, returns a filename into which to save the data. Or a list (or iterable) with filenames.

required
compress bool

Compress the data upon saving using gzip. When saving using compression, one must load it with compression too.

True
Example

def combo_fname(learner): ... val = learner.function.keywords # because functools.partial ... fname = '__'.join([f'{k}_{v}.pickle' for k, v in val.items()]) ... return 'data_folder/' + fname

def f(x, a, b): return a * x**2 + b

learners = [Learner1D(functools.partial(f, **combo), (-1, 1)) ... for combo in adaptive.utils.named_product(a=[1, 2], b=[1])]

learner = BalancingLearner(learners)

Run the learner

runner = adaptive.Runner(learner)

Then save

learner.save(combo_fname) # use 'load' in the same way

Source code in adaptive/learner/balancing_learner.py
def save(
    self,
    fname: Callable[[BaseLearner], str] | Sequence[str],
    compress: bool = True,
) -> None:
    """Save the data of the child learners into pickle files
    in a directory.

    Parameters
    ----------
    fname: callable or sequence of strings
        Given a learner, returns a filename into which to save the data.
        Or a list (or iterable) with filenames.
    compress : bool, default True
        Compress the data upon saving using `gzip`. When saving
        using compression, one must load it with compression too.

    Example
    -------
    >>> def combo_fname(learner):
    ...     val = learner.function.keywords  # because functools.partial
    ...     fname = '__'.join([f'{k}_{v}.pickle' for k, v in val.items()])
    ...     return 'data_folder/' + fname
    >>>
    >>> def f(x, a, b): return a * x**2 + b
    >>>
    >>> learners = [Learner1D(functools.partial(f, **combo), (-1, 1))
    ...             for combo in adaptive.utils.named_product(a=[1, 2], b=[1])]
    >>>
    >>> learner = BalancingLearner(learners)
    >>> # Run the learner
    >>> runner = adaptive.Runner(learner)
    >>> # Then save
    >>> learner.save(combo_fname)  # use 'load' in the same way
    """
    if isinstance(fname, Iterable):
        for lrn, _fname in zip(self.learners, fname):
            lrn.save(_fname, compress=compress)
    else:
        for lrn in self.learners:
            lrn.save(fname(lrn), compress=compress)

load

load(fname: Callable[[BaseLearner], str] | Sequence[str], compress: bool = True) -> None

Load the data of the child learners from pickle files in a directory.

Parameters:

Name Type Description Default
fname Callable[[BaseLearner], str] | Sequence[str]

Given a learner, returns a filename from which to load the data. Or a list (or iterable) with filenames.

required
compress bool

If the data is compressed when saved, one must load it with compression too.

True
Example

See the example in the BalancingLearner.save doc-string.

Source code in adaptive/learner/balancing_learner.py
def load(
    self,
    fname: Callable[[BaseLearner], str] | Sequence[str],
    compress: bool = True,
) -> None:
    """Load the data of the child learners from pickle files
    in a directory.

    Parameters
    ----------
    fname: callable or sequence of strings
        Given a learner, returns a filename from which to load the data.
        Or a list (or iterable) with filenames.
    compress : bool, default True
        If the data is compressed when saved, one must load it
        with compression too.

    Example
    -------
    See the example in the `BalancingLearner.save` doc-string.
    """
    if isinstance(fname, Iterable):
        for lrn, _fname in zip(self.learners, fname):
            lrn.load(_fname, compress=compress)
    else:
        for lrn in self.learners:
            lrn.load(fname(lrn), compress=compress)