ModelBase
- class rectools.models.base.ModelBase(*args: Any, verbose: int = 0, **kwargs: Any)[source]
Bases:
Generic[ModelConfig_T]Base model class.
Warning: This class should not be used directly. Use derived classes instead.
- Inherited-members
- Parameters
args (Any) –
verbose (int) –
kwargs (Any) –
Methods
dumps()Serialize model to bytes.
fit(dataset, *args, **kwargs)Fit model.
fit_partial(dataset, *args, **kwargs)Fit model.
from_config(config)Create model from config.
Return model config.
get_params([simple_types, sep])Return model parameters.
load(f)Load model from file.
loads(data)Load model from bytes.
recommend(users, dataset, k, filter_viewed)Recommend items for users.
recommend_to_items(target_items, dataset, k)Recommend items for target items.
save(f)Save model to file.
Attributes
recommends_for_coldrecommends_for_warmconfig_class- fit(dataset: Dataset, *args: Any, **kwargs: Any) T[source]
Fit model.
- Parameters
dataset (Dataset) – Dataset with input data.
self (T) –
args (Any) –
kwargs (Any) –
- Return type
self
- fit_partial(dataset: Dataset, *args: Any, **kwargs: Any) Self[source]
Fit model. Unlike fit, repeated calls to this method will cause training to resume from the current model state.
- Parameters
dataset (Dataset) – Dataset with input data.
args (Any) –
kwargs (Any) –
- Return type
self
- classmethod from_config(config: Union[dict, ModelConfig_T]) Self[source]
Create model from config.
- Parameters
config (dict or ModelConfig) – Model config.
- Return type
Model instance.
- get_config(mode: tp.Literal['pydantic'], simple_types: bool = False) ModelConfig_T[source]
- get_config(mode: tp.Literal['dict'] = 'dict', simple_types: bool = False) tp.Dict[str, tp.Any]
Return model config.
- Parameters
mode ({'pydantic', 'dict'}, default 'dict') – Format of returning config.
simple_types (bool, default False) – If True, return config with JSON serializable types. Only works for mode=’dict’.
- Returns
Model config.
- Return type
Pydantic model or dict
- Raises
ValueError – If mode is not ‘object’ or ‘dict’, or if simple_types is
Trueand format is not ‘dict’.
- get_params(simple_types: bool = False, sep: str = '.') Dict[str, Any][source]
Return model parameters. Same as get_config but returns flat dict.
- Parameters
simple_types (bool, default False) – If True, return config with JSON serializable types.
sep (str, default ".") – Separator for nested keys.
- Returns
Model parameters.
- Return type
dict
- classmethod load(f: Union[str, Path, IO[bytes]]) Self[source]
Load model from file.
- Parameters
f (str or Path or file-like object) – Path to file or file-like object.
- Returns
Model instance.
- Return type
model
- classmethod loads(data: bytes) Self[source]
Load model from bytes.
- Parameters
data (bytes) – Serialized model.
- Returns
Model instance.
- Return type
model
- Raises
TypeError – If loaded object is not a direct instance of model class.
- recommend(users: Union[Sequence[Hashable], ndarray], dataset: Dataset, k: int, filter_viewed: bool, items_to_recommend: Optional[Union[Sequence[Hashable], ndarray]] = None, add_rank_col: bool = True, on_unsupported_targets: Literal['ignore', 'warn', 'raise'] = 'raise') DataFrame[source]
Recommend items for users.
To use this method model must be fitted.
- Parameters
users (array-like) – Array of user ids to recommend for. User ids are supposed to be external
dataset (Dataset) – Dataset with input data. Usually it’s the same dataset that was used to fit model.
k (int) – Derived number of recommendations for every user. Pay attention that in some cases real number of recommendations may be less than k.
filter_viewed (bool) – Whether to filter from recommendations items that user has already interacted with. Works only for “hot” users.
items_to_recommend (array-like, optional, default None) – Whitelist of item ids. If given, only these items will be used for recommendations. Otherwise all items from dataset will be used. Item ids are supposed to be external.
add_rank_col (bool, default True) – Whether to add rank column to recommendations. If True column Columns.Rank will be added. This column contain integers from 1 to
number of user recommendations. In any case recommendations are sorted per rank for every user. The lesser the rank the more recommendation is relevant.on_unsupported_targets (Literal["raise", "warn", "ignore"], default "raise") – How to handle warm/cold target users when model doesn’t support warm/cold inference. Specify “raise” to raise ValueError in case unsupported targets are passed (default). Specify “ignore” to filter unsupported targets. Specify “warn” to filter with warning.
- Returns
Recommendations table with columns Columns.User, Columns.Item, Columns.Score`[, `Columns.Rank]. External user and item ids are used by default. For internal ids set return_external_ids to
False. 1st column contains user ids, 2nd - ids of recommended items sorted by relevance for each user, 3rd - score that model gives for the user-item pair, 4th (present only if add_rank_col isTrue) - integers from1to number of user recommendations.- Return type
pd.DataFrame
- Raises
NotFittedError – If called for not fitted model.
TypeError, ValueError – If arguments have inappropriate type or value
ValueError – If some of given users are warm/cold and model doesn’t support such type of users and on_unsupported_targets is set to “raise”.
- recommend_to_items(target_items: Union[Sequence[Hashable], ndarray], dataset: Dataset, k: int, filter_itself: bool = True, items_to_recommend: Optional[Union[Sequence[Hashable], ndarray]] = None, add_rank_col: bool = True, on_unsupported_targets: Literal['ignore', 'warn', 'raise'] = 'raise') DataFrame[source]
Recommend items for target items.
To use this method model must be fitted.
- Parameters
target_items (array-like) – Array of item ids to recommend for. Item ids are supposed to be external.
dataset (Dataset) – Dataset with input data. Usually it’s the same dataset that was used to fit model.
k (int) – Derived number of recommendations for every target item. Pay attention that in some cases real number of recommendations may be less than k.
filter_itself (bool, default True) – If True, item will be excluded from recommendations to itself.
items_to_recommend (array-like, optional, default None) – Whitelist of item ids. If given, only these items will be used for recommendations. Otherwise all items from dataset will be used. Item ids are supposed to be external
add_rank_col (bool, default True) – Whether to add rank column to recommendations. If True column Columns.Rank will be added. This column contain integers from 1 to
number of item recommendations. In any case recommendations are sorted per rank for every target item. Less rank means more relevant recommendation.on_unsupported_targets (Literal["raise", "warn", "ignore"], default "raise") – How to handle warm/cold target users when model doesn’t support warm/cold inference. Specify “raise” to raise ValueError in case unsupported targets are passed (default). Specify “ignore” to filter unsupported targets. Specify “warn” to filter with warning.
- Returns
Recommendations table with columns Columns.TargetItem, Columns.Item, Columns.Score`[, `Columns.Rank]. External item ids are used by default. For internal ids set return_external_ids to
False. 1st column contains target item ids, 2nd - ids of recommended items sorted by relevance for each target item, 3rd - score that model gives for the target-item pair, 4th (present only if add_rank_col isTrue) - integers from 1 to number of recommendations.- Return type
pd.DataFrame
- Raises
NotFittedError – If called for not fitted model.
TypeError, ValueError – If arguments have inappropriate type or value
ValueError – If some of given users are warm/cold and model doesn’t support such type of users and on_unsupported_targets is set to “raise”.