contextualbandits

repository·master·Indexed 21 days ago

https://github.com/david-cortes/contextualbandits

A Python package for contextual bandit algorithms focusing on online learning, off-policy learning, and policy evaluation. It supports discrete rewards {0, 1} and shared covariates. Key implementations include LinUCB, Linear Thompson Sampling, BootstrappedUCB, Offset Tree, and Doubly-Robust Policy Optimization. The library is designed for prototyping and research reproduction, requiring a C/C++ compiler for versions 0.2.0 and later.

Tokens
6.2K
Snippets
14
Records
26
Agent score
74%

What's inside contextualbandits

  1. Understand the Contextual Bandits problem model in this package

    master

    This package implements solutions for the contextual bandits problem (associative reinforcement learning).

    Core Constraints:

    • Discrete Rewards: This package deals only with discrete rewards in the set {0, 1}. It is not intended for continuous rewards.
    • Shared Covariates: It assumes all arms see the same covariates (features).
    • Iterative Process: At each round, an agent receives covariates, chooses an arm, and receives a reward for that arm only.

    Key Problem Areas Covered:

    • Online Learning (contextualbandits.online): Managing exploration/exploitation in real-time.
    • Off-policy Learning (contextualbandits.offpolicy): Learning from data collected by a different policy (Counter-factual Risk Minimization).
    • Policy Evaluation (contextualbandits.evaluation): Evaluating strategies based on partially-labeled data.
  2. Use Linear Regression for incremental updates

    master

    The package includes non-stochastic linear regression procedures with exact partial_fit solutions. These are recommended to be used alongside online policies to achieve better incremental updates.

    # Available classes in contextualbandits.linreg
    # - LinearRegression
    # - ElasticNet
  3. Install contextualbandits

    master

    The package is available on PyPI. Use the standard pip command to install the latest version. If you encounter errors related to C code compilation, you can install an earlier pure-Python version instead.

    # Standard installation
    pip install contextualbandits
    
    # Pure-Python fallback if C compilation fails
    pip install contextualbandits==0.1.8.5
  4. Configure compilation flags for optimized builds

    master

    The setup script attempts to add the -march=native flag to tune the package for the local CPU. This may make the resulting binary incompatible with other machines.

    To ensure maximum compatibility (at the cost of speed) when building wheels or Docker images, use one of the following methods:

    1. Disable native tuning: Set the DONT_SET_MARCH environment variable to 1.
    2. Manually specify architecture: Set CFLAGS and CXXFLAGS to a specific architecture (e.g., -march=x86-64).
    # Option 1: Disable native tuning
    export DONT_SET_MARCH=1
    pip install contextualbandits
    
    # Option 2: Specify architecture
    export CFLAGS="-march=x86-64"
    export CXXFLAGS="-march=x86-64"
    pip install contextualbandits
  5. Choose an Online Contextual Bandit policy

    master

    The contextualbandits.online module provides various policy classes for online learning. If you are unsure which method to choose, BootstrappedUCB is recommended as a safe starting point.

    Policies are categorized by their exploration strategy:

    • Randomized: AdaptiveGreedy, SoftmaxExplorer, EpsilonGreedy, ExploreFirst.
    • Active choices: ActiveExplorer, AdaptiveGreedy (with active_choice != None), ExploreFirst (with prob_active_choice > 0).
    • Thompson sampling: BootstrappedTS, PartitionedTS, ParametricTS, LogisticTS, LinTS.
    • Upper confidence bound (UCB): BootstrappedUCB, PartitionedUCB, LogisticUCB, LinUCB.
    • Naive: SeparateClassifiers.
  6. Serialize contextualbandits objects using cloudpickle or dill

    master

    Standard Python pickle is likely to fail when serializing objects from this library. Instead, use cloudpickle or dill, which provide the same syntax as pickle but handle the library's complex objects correctly.

    import cloudpickle
    from sklearn.linear_model import SGDClassifier
    from contextualbandits.online import BootstrappedUCB
    
    # Initialize model
    m = BootstrappedUCB(SGDClassifier(loss="log_loss"), nchoices = 5, batch_train = True)
    
    # Serialize
    cloudpickle.dump(m, open("saved_ucb_model.pkl", "wb"))
    
    # Deserialize
    m = cloudpickle.load(open("saved_ucb_model.pkl", "rb"))
  7. Install contextualbandits via pip

    master

    The package can be installed using pip. Note that as of version 0.2.0, the package contains Cython code and requires a C/C++ compiler configured for Python.

    Standard installation:

    pip install contextualbandits

    If the standard installation fails, try:

    pip install --no-use-pep517 contextualbandits

    To install an older, pure-python version (no C compiler required):

    pip install contextualbandits==0.1.8.5
  8. Overview of Online Contextual Bandit Algorithms

    master

    The contextualbandits.online module provides various meta-heuristics to solve the contextual bandit problem, where an agent selects an arm (action) based on covariates (context) to maximize discrete rewards $r \in {0,1}$.

    Most algorithms in this module are meta-heuristics that wrap a base binary classifier. The base classifier must follow a scikit-learn-like API, providing fit and either predict_proba, decision_function, or predict methods.

    Available algorithm families include:

    • Upper-confidence bounds (UCB): BootstrappedUCB, LogisticUCB, LinUCB.
    • Thompson Sampling (TS): BootstrappedTS, LogisticTS, LinTS, SoftmaxExplorer.
    • Greedy Exploration: EpsilonGreedy (randomly choosing an arm sometimes).
    • Adaptive Exploration: AdaptiveGreedy (choosing based on model certainty vs. randomness).
    • Other Heuristics: ExploreFirst (explore-then-exploit), ActiveExplorer (active learning based), SeparateClassifiers (fits separate models per arm), and SoftmaxExplorer.
  9. How policy evaluation methods work and when to use them

    master

    Policy evaluation in contextual bandits is challenging because data is typically collected by a biased policy aiming to maximize rewards. The evaluation module provides three main approaches:

    1. Rejection Sampling (evaluateRejectionSampling):

      • When to use: When you have data where actions were chosen at random.
      • Pros: Unbiased for both online and offline policies.
      • Cons: Requires random action data; otherwise, results are highly biased.
    2. Doubly Robust (evaluateDoublyRobust):

      • When to use: When random data is unavailable but there is variety in the actions chosen by the data-collecting policy.
      • Pros: Combines a reward model and a propensity model.
      • Cons: Best for continuous rewards; can struggle with many discrete labels.
    3. NCIS (evaluateNCIS):

      • When to use: As an alternative when doubly-robust estimates are unreliable.
      • Note: This implementation is an approximation and lacks the theoretical guarantees of the original method due to the package's handling of arm probabilities.
  10. Understand Off-policy Learning in Contextual Bandits

    master

    The offpolicy module is used to build new, exploit-only policies from previously collected (biased) data. Unlike the online module, off-policy learning assumes you have a dataset consisting of observed features, chosen actions, observed rewards, and ideally the estimated reward probabilities (scores) predicted by the original exploration policy.

    Key Characteristics:

    • Goal: To build a better policy than the one that generated the data.
    • Assumptions: It assumes a stationary (non-online) exploration policy for theoretical soundness, though it can work with data from online policies where reward estimates shift over time.
    • Data Requirements: For methods to work effectively, the data should ideally include the probabilities that the exploration policy assigned to the actions it chose.
    • Limitations: The algorithms are designed for exploit-only policies and do not extend easily to classifiers that allow exploration. In discrete reward settings, simple One-Vs-Rest approaches may sometimes outperform these specialized algorithms.