Skip to content

add check-scalar #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions obp/dataset/multiclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from scipy.stats import rankdata
from sklearn.base import ClassifierMixin, is_classifier, clone
from sklearn.model_selection import train_test_split
from sklearn.utils import check_random_state, check_X_y
from sklearn.utils import check_random_state, check_X_y, check_scalar

from .base import BaseBanditDataset
from ..types import BanditFeedback
Expand Down Expand Up @@ -152,10 +152,9 @@ def __post_init__(self) -> None:
"""Initialize Class."""
if not is_classifier(self.base_classifier_b):
raise ValueError("base_classifier_b must be a classifier")
if not isinstance(self.alpha_b, float) or not (0.0 <= self.alpha_b < 1.0):
raise ValueError(
f"alpha_b must be a float in the [0,1) interval, but {self.alpha_b} is given"
)
check_scalar(self.alpha_b, "alpha_b", float, min_val=0.0)
if self.alpha_b >= 1.0:
raise ValueError(f"`alpha_b`= {self.alpha_b}, must be < 1.0.")

self.X, y = check_X_y(X=self.X, y=self.y, ensure_2d=True, multi_output=False)
self.y = (rankdata(y, "dense") - 1).astype(int) # re-index action
Expand Down Expand Up @@ -280,10 +279,7 @@ def obtain_action_dist_by_eval_policy(
axis 2 represents the length of list; it is always 1 in the current implementation.

"""
if not isinstance(alpha_e, float) or not (0.0 <= alpha_e <= 1.0):
raise ValueError(
f"alpha_e must be a float in the [0,1] interval, but {alpha_e} is given"
)
check_scalar(alpha_e, "alpha_e", float, min_val=0.0, max_val=1.0)
# train a base ML classifier
if base_classifier_e is None:
base_clf_e = clone(self.base_classifier_b)
Expand Down
18 changes: 4 additions & 14 deletions obp/dataset/synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,8 @@ class SyntheticBanditDataset(BaseBanditDataset):

def __post_init__(self) -> None:
"""Initialize Class."""
if not isinstance(self.n_actions, int) or self.n_actions <= 1:
raise ValueError(
f"n_actions must be an integer larger than 1, but {self.n_actions} is given"
)
if not isinstance(self.dim_context, int) or self.dim_context <= 0:
raise ValueError(
f"dim_context must be a positive integer, but {self.dim_context} is given"
)
check_scalar(self.n_actions, "n_actions", int, min_val=2)
check_scalar(self.dim_context, "dim_context", int, min_val=1)
if RewardType(self.reward_type) not in [
RewardType.BINARY,
RewardType.CONTINUOUS,
Expand All @@ -164,7 +158,7 @@ def __post_init__(self) -> None:
check_scalar(self.reward_std, "reward_std", (int, float), min_val=0)
check_scalar(self.tau, "tau", (int, float), min_val=0)
if self.random_state is None:
raise ValueError("random_state must be given")
raise ValueError("`random_state` must be given")
self.random_ = check_random_state(self.random_state)
if self.reward_function is None:
self.expected_reward = self.sample_contextfree_expected_reward()
Expand Down Expand Up @@ -268,11 +262,7 @@ def obtain_batch_bandit_feedback(self, n_rounds: int) -> BanditFeedback:
Generated synthetic bandit feedback dataset.

"""
if not isinstance(n_rounds, int) or n_rounds <= 0:
raise ValueError(
f"n_rounds must be a positive integer, but {n_rounds} is given"
)

check_scalar(n_rounds, "n_rounds", int, min_val=1)
context = self.random_.normal(size=(n_rounds, self.dim_context))
# sample actions for each round based on the behavior policy
if self.behavior_policy_function is None:
Expand Down
2 changes: 1 addition & 1 deletion obp/dataset/synthetic_continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def calc_ground_truth_policy_value(
check_array(array=action, name="action", expected_dim=1)
if context.shape[1] != self.dim_context:
raise ValueError(
"Expected `context.shape[1] == self.dim_context`, found it False"
"Expected `context.shape[1] == self.dim_context`, but found it False"
)
if context.shape[0] != action.shape[0]:
raise ValueError(
Expand Down
34 changes: 10 additions & 24 deletions obp/dataset/synthetic_slate.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,24 +190,14 @@ class SyntheticSlateBanditDataset(BaseBanditDataset):

def __post_init__(self) -> None:
"""Initialize Class."""
if not isinstance(self.n_unique_action, int) or self.n_unique_action <= 1:
raise ValueError(
f"n_unique_action must be an integer larger than 1, but {self.n_unique_action} is given"
)
if not isinstance(self.len_list, int) or self.len_list <= 1:
raise ValueError(
f"len_list must be an integer larger than 1, but {self.len_list} is given"
)
if not self.is_factorizable and self.len_list > self.n_unique_action:
raise ValueError(
f"len_list must be equal to or smaller than n_unique_action, but {self.len_list} is given"
)
if not isinstance(self.dim_context, int) or self.dim_context <= 0:
raise ValueError(
f"dim_context must be a positive integer, but {self.dim_context} is given"
)
if not isinstance(self.random_state, int):
raise ValueError("random_state must be an integer")
check_scalar(self.n_unique_action, "n_unique_action", int, min_val=2)
if self.is_factorizable:
max_len_list = None
else:
max_len_list = self.n_unique_action
check_scalar(self.len_list, "len_list", int, min_val=2, max_val=max_len_list)

check_scalar(self.dim_context, "dim_context", int, min_val=1)
self.random_ = check_random_state(self.random_state)
if self.reward_type not in [
"binary",
Expand Down Expand Up @@ -744,11 +734,7 @@ def obtain_batch_bandit_feedback(
Generated synthetic slate bandit feedback dataset.

"""
if not isinstance(n_rounds, int) or n_rounds <= 0:
raise ValueError(
f"n_rounds must be a positive integer, but {n_rounds} is given"
)

check_scalar(n_rounds, "n_rounds", int, min_val=1)
context = self.random_.normal(size=(n_rounds, self.dim_context))
# sample actions for each round based on the behavior policy
if self.behavior_policy_function is None:
Expand Down Expand Up @@ -891,7 +877,7 @@ def calc_ground_truth_policy_value(
)
if context.shape[1] != self.dim_context:
raise ValueError(
"Expected `context.shape[1] == self.dim_context`, found it False"
"Expected `context.shape[1] == self.dim_context`, but found it False"
)
if evaluation_policy_logit_.shape[0] != context.shape[0]:
raise ValueError(
Expand Down
12 changes: 7 additions & 5 deletions obp/ope/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import numpy as np
from pandas import DataFrame
import seaborn as sns
from sklearn.utils import check_scalar


from .estimators import BaseOffPolicyEstimator, DirectMethod as DM, DoublyRobust as DR
from ..types import BanditFeedback
Expand Down Expand Up @@ -457,11 +459,11 @@ def evaluate_performance_of_estimators(
Dictionary containing evaluation metric for evaluating the estimation performance of OPE estimators.

"""

if not isinstance(ground_truth_policy_value, float):
raise ValueError(
f"ground_truth_policy_value must be a float, but {ground_truth_policy_value} is given"
)
check_scalar(
ground_truth_policy_value,
"ground_truth_policy_value",
float,
)
if metric not in ["relative-ee", "se"]:
raise ValueError(
f"metric must be either 'relative-ee' or 'se', but {metric} is given"
Expand Down
10 changes: 6 additions & 4 deletions obp/ope/meta_continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import numpy as np
from pandas import DataFrame
import seaborn as sns
from sklearn.utils import check_scalar

from .estimators_continuous import (
BaseContinuousOffPolicyEstimator,
Expand Down Expand Up @@ -477,10 +478,11 @@ def evaluate_performance_of_estimators(

"""

if not isinstance(ground_truth_policy_value, float):
raise ValueError(
f"ground_truth_policy_value must be a float, but {ground_truth_policy_value} is given"
)
check_scalar(
ground_truth_policy_value,
"ground_truth_policy_value",
float,
)
if metric not in ["relative-ee", "se"]:
raise ValueError(
f"metric must be either 'relative-ee' or 'se', but {metric} is given"
Expand Down
8 changes: 3 additions & 5 deletions obp/ope/meta_slate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import numpy as np
from pandas import DataFrame
import seaborn as sns
from sklearn.utils import check_scalar


from .estimators_slate import BaseSlateOffPolicyEstimator
from ..types import BanditFeedback
Expand Down Expand Up @@ -467,11 +469,7 @@ def evaluate_performance_of_estimators(
Dictionary containing evaluation metric for evaluating the estimation performance of OPE estimators.

"""

if not isinstance(ground_truth_policy_value, float):
raise ValueError(
f"ground_truth_policy_value must be a float, but {ground_truth_policy_value} is given"
)
check_scalar(ground_truth_policy_value, "ground_truth_policy_value", float)
if metric not in ["relative-ee", "se"]:
raise ValueError(
f"metric must be either 'relative-ee' or 'se', but {metric} is given"
Expand Down
23 changes: 6 additions & 17 deletions obp/ope/regression_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import numpy as np
from sklearn.base import BaseEstimator, clone, is_classifier
from sklearn.model_selection import KFold
from sklearn.utils import check_scalar, check_random_state


from ..utils import check_bandit_feedback_inputs

Expand Down Expand Up @@ -62,21 +64,15 @@ class RegressionModel(BaseEstimator):

def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(self.n_actions, "n_actions", int, min_val=2)
check_scalar(self.len_list, "len_list", int, min_val=1)
if not (
isinstance(self.fitting_method, str)
and self.fitting_method in ["normal", "iw", "mrdr"]
):
raise ValueError(
f"fitting_method must be one of 'normal', 'iw', or 'mrdr', but {self.fitting_method} is given"
)
if not (isinstance(self.n_actions, int) and self.n_actions > 1):
raise ValueError(
f"n_actions must be an integer larger than 1, but {self.n_actions} is given"
)
if not (isinstance(self.len_list, int) and self.len_list > 0):
raise ValueError(
f"len_list must be a positive integer, but {self.len_list} is given"
)
if not isinstance(self.base_model, BaseEstimator):
raise ValueError(
"base_model must be BaseEstimator or a child class of BaseEstimator"
Expand Down Expand Up @@ -292,15 +288,8 @@ def fit_predict(
)
n_rounds = context.shape[0]

if not (isinstance(n_folds, int) and n_folds > 0):
raise ValueError(
f"n_folds must be a positive integer, but {n_folds} is given"
)

if random_state is not None and not isinstance(random_state, int):
raise ValueError(
f"random_state must be an integer, but {random_state} is given"
)
check_scalar(n_folds, "n_folds", int, min_val=1)
check_random_state(random_state)

if position is None or self.len_list == 1:
position = np.zeros_like(action)
Expand Down
68 changes: 10 additions & 58 deletions obp/policy/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Optional

import numpy as np
from sklearn.utils import check_random_state
from sklearn.utils import check_random_state, check_scalar

from .policy_type import PolicyType

Expand Down Expand Up @@ -40,26 +40,9 @@ class BaseContextFreePolicy(metaclass=ABCMeta):

def __post_init__(self) -> None:
"""Initialize Class."""
if not isinstance(self.n_actions, int) or self.n_actions <= 1:
raise ValueError(
f"n_actions must be an integer larger than 1, but {self.n_actions} is given"
)

if not isinstance(self.len_list, int) or self.len_list <= 0:
raise ValueError(
f"len_list must be a positive integer, but {self.len_list} is given"
)

if not isinstance(self.batch_size, int) or self.batch_size <= 0:
raise ValueError(
f"batch_size must be a positive integer, but {self.batch_size} is given"
)

if self.n_actions < self.len_list:
raise ValueError(
f"n_actions >= len_list should hold, but n_actions is {self.n_actions} and len_list is {self.len_list}"
)

check_scalar(self.n_actions, "n_actions", int, min_val=2)
check_scalar(self.len_list, "len_list", int, min_val=1, max_val=self.n_actions)
check_scalar(self.batch_size, "batch_size", int, min_val=1)
self.n_trial = 0
self.random_ = check_random_state(self.random_state)
self.action_counts = np.zeros(self.n_actions, dtype=int)
Expand Down Expand Up @@ -124,29 +107,10 @@ class BaseContextualPolicy(metaclass=ABCMeta):

def __post_init__(self) -> None:
"""Initialize class."""
if not isinstance(self.dim, int) or self.dim <= 0:
raise ValueError(f"dim must be a positive integer, but {self.dim} is given")

if not isinstance(self.n_actions, int) or self.n_actions <= 1:
raise ValueError(
f"n_actions must be an integer larger than 1, but {self.n_actions} is given"
)

if not isinstance(self.len_list, int) or self.len_list <= 0:
raise ValueError(
f"len_list must be a positive integer, but {self.len_list} is given"
)

if not isinstance(self.batch_size, int) or self.batch_size <= 0:
raise ValueError(
f"batch_size must be a positive integer, but {self.batch_size} is given"
)

if self.n_actions < self.len_list:
raise ValueError(
f"n_actions >= len_list should hold, but n_actions is {self.n_actions} and len_list is {self.len_list}"
)

check_scalar(self.dim, "dim", int, min_val=1)
check_scalar(self.n_actions, "n_actions", int, min_val=2)
check_scalar(self.len_list, "len_list", int, min_val=1, max_val=self.n_actions)
check_scalar(self.batch_size, "batch_size", int, min_val=1)
self.n_trial = 0
self.random_ = check_random_state(self.random_state)
self.action_counts = np.zeros(self.n_actions, dtype=int)
Expand Down Expand Up @@ -197,20 +161,8 @@ class BaseOfflinePolicyLearner(metaclass=ABCMeta):

def __post_init__(self) -> None:
"""Initialize class."""
if not isinstance(self.n_actions, int) or self.n_actions <= 1:
raise ValueError(
f"n_actions must be an integer larger than 1, but {self.n_actions} is given"
)

if not isinstance(self.len_list, int) or self.len_list <= 0:
raise ValueError(
f"len_list must be a positive integer, but {self.len_list} is given"
)

if self.n_actions < self.len_list:
raise ValueError(
f"Expected `n_actions >= len_list`, but got n_actions={self.n_actions} < len_list={self.len_list}"
)
check_scalar(self.n_actions, "n_actions", int, min_val=2)
check_scalar(self.len_list, "len_list", int, min_val=1, max_val=self.n_actions)

@property
def policy_type(self) -> PolicyType:
Expand Down
6 changes: 2 additions & 4 deletions obp/policy/contextfree.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Optional

import numpy as np
from sklearn.utils import check_scalar

from .base import BaseContextFreePolicy

Expand Down Expand Up @@ -51,10 +52,7 @@ class EpsilonGreedy(BaseContextFreePolicy):

def __post_init__(self) -> None:
"""Initialize Class."""
if not 0 <= self.epsilon <= 1:
raise ValueError(
f"epsilon must be between 0 and 1, but {self.epsilon} is given"
)
check_scalar(self.epsilon, "epsilon", float, min_val=0.0, max_val=1.0)
self.policy_name = f"egreedy_{self.epsilon}"
super().__post_init__()

Expand Down
Loading