david-cortes / contextualbandits

Python implementations of contextual bandits algorithms
http://contextual-bandits.readthedocs.io
BSD 2-Clause "Simplified" License
750 stars 148 forks source link

Cannot access model attributes when arms are floats #41

Closed Daniel8hen closed 3 years ago

Daniel8hen commented 3 years ago

I've been trying to access an sklearn's model coefficients and got an AttributeError, it seems like something modifies the base model.

This issue gets resolved if the arms are integers.

Minimal code that causes the exception:


import numpy as np
from contextualbandits import online as cb
from sklearn.naive_bayes import BernoulliNB
aa = np.array([0.2, 0.1, 0.2, 0.1, 0.4, 1.1, 0.3, 0.5, 0.6, 0.7])
XX = np.array([[1, 0, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0],
       [0, 1, 0]])
rr = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1])
n_arms = len({t for t in aa})
model = cb.SeparateClassifiers(BernoulliNB(), n_arms, batch_train=True)
model.partial_fit(XX, aa, rr)
[m.coef_ for m in model._oracles.algos]
david-cortes commented 3 years ago

Those floats are interpreted as integers and all of them get cast to zero, so only the first one is fitted. If you want to use non-integer IDs, you need to pass those under nchoices.