milia.core.config#

Pydantic configuration for registered estimators.

class milia.core.config.BaseModelConfig(*, name='base', kind='base', space=None)#

Bases: BaseModel

Hyperparameters for one registered estimator.

Subclasses fix name and kind and declare the estimator’s hyperparameters as fields, with the same names as the estimator’s constructor arguments:

class IForestConfig(BaseModelConfig):
    name: Literal["iforest"] = Field("iforest", exclude=True)
    kind: Literal["detector"] = Field("detector", exclude=True)
    n_estimators: int = 100
    space: SearchSpace | None = Field(SearchSpace(n_estimators=(50, 500)), exclude=True)
Parameters:
  • name (str) – Registry name of the estimator. Fixed per subclass.

  • kind (str) – "detector" or "clusterer". Fixed per subclass.

  • space (SearchSpace | None) – Optional hyperparameter search space for tuning.

Examples

>>> from milia import get
>>> estimator, config = get("detector", "knn")
>>> settings = config(n_neighbors=7)
>>> estimator(**settings.params()).n_neighbors
7
params()#

The estimator’s constructor keyword arguments.

The descriptive fields name, kind and space are left out, so the result can be passed straight to the estimator.

Return type:

dict[str, Any]

Returns:

Hyperparameter name to value.

Examples

>>> from milia import get
>>> _, config = get("detector", "lof")
>>> config(n_neighbors=10).params()
{'n_neighbors': 10, 'metric': 'minkowski', 'contamination': 0.1}
sample(trial)#

Fixed hyperparameters overridden by values sampled from space.

Parameters:

trial (Trial) – The active Optuna trial.

Return type:

dict[str, Any]

Returns:

Constructor keyword arguments for this trial.

milia.core.config.Field(default=PydanticUndefined, *, default_factory=PydanticUndefined, alias=PydanticUndefined, alias_priority=PydanticUndefined, validation_alias=PydanticUndefined, serialization_alias=PydanticUndefined, title=PydanticUndefined, field_title_generator=PydanticUndefined, description=PydanticUndefined, examples=PydanticUndefined, exclude=PydanticUndefined, exclude_if=PydanticUndefined, discriminator=PydanticUndefined, deprecated=PydanticUndefined, json_schema_extra=PydanticUndefined, frozen=PydanticUndefined, validate_default=PydanticUndefined, repr=PydanticUndefined, init=PydanticUndefined, init_var=PydanticUndefined, kw_only=PydanticUndefined, pattern=PydanticUndefined, strict=PydanticUndefined, coerce_numbers_to_str=PydanticUndefined, gt=PydanticUndefined, ge=PydanticUndefined, lt=PydanticUndefined, le=PydanticUndefined, multiple_of=PydanticUndefined, allow_inf_nan=PydanticUndefined, max_digits=PydanticUndefined, decimal_places=PydanticUndefined, min_length=PydanticUndefined, max_length=PydanticUndefined, union_mode=PydanticUndefined, fail_fast=PydanticUndefined, **extra)#
!!! abstract “Usage Documentation”

[Fields](../concepts/fields.md)

Overloads:

Create a field for objects that can be configured.

Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (int, float, Decimal) and some apply only to str.

Note

  • Any _Unset objects will be replaced by the corresponding default value of the FieldInfo constructor.

Parameters:
  • default (Any) – Default value if the field is not set.

  • default_factory (Callable[[], Any] | Callable[[dict[str, Any]], Any] | None) – A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data.

  • alias (str | None) – The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case.

  • alias_priority (int | None) – Priority of the alias. This affects whether an alias generator is used.

  • validation_alias (str | AliasPath | AliasChoices | None) – Like alias, but only affects validation, not serialization.

  • serialization_alias (str | None) – Like alias, but only affects serialization, not validation.

  • title (str | None) – Human-readable title.

  • field_title_generator (Callable[[str, FieldInfo], str] | None) – A callable that takes a field’s name and info and returns title for it.

  • description (str | None) – Human-readable description.

  • examples (list[Any] | None) – Example values for this field.

  • exclude (bool | None) – Whether to exclude the field from the model serialization.

  • exclude_if (Callable[[Any], bool] | None) – A callable that determines whether to exclude a field during serialization based on its value.

  • discriminator (str | Discriminator | None) – Field name or Discriminator for discriminating the type in a tagged union.

  • deprecated (deprecated | str | bool | None) – A deprecation message, an instance of warnings.deprecated or the typing_extensions.deprecated backport, or a boolean. If True, a default deprecation message will be emitted when accessing the field.

  • json_schema_extra (dict[str, Union[int, float, str, bool, None, list[JsonValue], JsonDict]] | Callable[[dict[str, Union[int, float, str, bool, None, list[JsonValue], JsonDict]]], None] | None) – A dict or callable to provide extra JSON schema properties.

  • frozen (bool | None) – Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.

  • validate_default (bool | None) – If True, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated.

  • repr (bool) – A boolean indicating whether to include the field in the __repr__ output.

  • init (bool | None) – Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)

  • init_var (bool | None) – Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.)

  • kw_only (bool | None) – Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)

  • coerce_numbers_to_str (bool | None) – Whether to enable coercion of any Number type to str (not applicable in strict mode).

  • strict (bool | None) – If True, strict validation is applied to the field. See [Strict Mode](../concepts/strict_mode.md) for details.

  • gt (SupportsGt | None) – Greater than. If set, value must be greater than this. Only applicable to numbers.

  • ge (SupportsGe | None) – Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.

  • lt (SupportsLt | None) – Less than. If set, value must be less than this. Only applicable to numbers.

  • le (SupportsLe | None) – Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.

  • multiple_of (float | None) – Value must be a multiple of this. Only applicable to numbers.

  • min_length (int | None) – Minimum length for iterables.

  • max_length (int | None) – Maximum length for iterables.

  • pattern (str | Pattern[str] | None) – Pattern for strings (a regular expression).

  • allow_inf_nan (bool | None) – Allow inf, -inf, nan. Only applicable to float and [Decimal][decimal.Decimal] numbers.

  • max_digits (int | None) – Maximum number of allowed digits for [Decimal][decimal.Decimal] numbers.

  • decimal_places (int | None) – Maximum number of decimal places allowed for numbers.

  • union_mode (Literal['smart', 'left_to_right']) – The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See [Union Mode](../concepts/unions.md#union-modes) for details.

  • fail_fast (bool | None) – If True, validation will stop on the first error. If False, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset).

  • extra (Unpack[_EmptyKwargs]) –

    (Deprecated) Extra fields that will be included in the JSON schema.

    !!! warning Deprecated

    The extra kwargs is deprecated. Use json_schema_extra instead.

Returns:

A new [FieldInfo][pydantic.fields.FieldInfo]. The return annotation is Any so Field can be used on

type-annotated fields without causing a type error.

Return type:

Any

class milia.core.config.SearchSpace(**extra_data)#

Bases: BaseModel

A validated hyperparameter search space.

Each field must be either a (low, high) tuple of numbers (a range) or a non-empty list (a categorical choice). Float ranges spanning at least one order of magnitude are sampled on a log scale.

Examples

>>> space = SearchSpace(n_estimators=(50, 500), max_features=[0.5, 1.0])
>>> sorted(space.model_dump())
['max_features', 'n_estimators']
checkfields()#

Check that every field is a valid range or categorical list.

Runs automatically after construction.

Return type:

SearchSpace

Returns:

The validated search space.

Raises:
  • ValueError – If a range is not low < high or does not have two elements, or a categorical list is empty or has duplicates.

  • TypeError – If a range holds non-numbers, or a field is neither a tuple nor a list.

suggest(trial, prefix='')#

Sample one value per field from an Optuna trial.

Parameters:
  • trial (Trial) – The active Optuna trial.

  • prefix (str) – Prepended to each trial parameter name, so several spaces can share one trial without collisions.

Return type:

dict[str, Any]

Returns:

Field name (without prefix) to sampled value.

check(config)#

Raise if a search-space field does not exist on config.

Catches a misspelled hyperparameter before any trial runs, rather than sampling a value that is silently never applied.

Parameters:

config (BaseModel) – The model config whose fields define the valid names.

Raises:

ValueError – If any field name is unknown to config.

Return type:

None

Examples

>>> from milia import get
>>> _, config = get("detector", "lof")
>>> SearchSpace(neighbours=(5, 50)).check(config())
Traceback (most recent call last):
...
ValueError: Search space contains unknown fields: ['neighbours']. ...

Modules

base

Base configuration shared by every registered estimator.

space

Hyperparameter search spaces for Optuna.