ZeroRRegressor#

class sklearn_nominal.ZeroRRegressor(criterion='std', backend='pandas')[source]#

A ZeroR Regressor, equivalent to a TreeClassifier with a depth of 0 (only root).

[1] Holte, Robert C. “Very simple classification rules perform well on most commonly used datasets.” Machine learning 11.1 (1993): 63-90.

Args:
criterion (str, optional): The function to measure the error of a split.

Supported criteria are currently only “std”, for standard deviation (equivalent to root MSE). Defaults to “std”.

backend (str, optional): The backend to use for computations. Defaults to DEFAULT_BACKEND.

Attributes:

n_features_in_ (int): Number of features seen during fit. feature_names_in_ (ndarray of shape (n_features_in_,)): Names of features

seen during fit. Defined only when X has feature names that are all strings.

n_outputs_ (int): The number of outputs when fit is performed. model_ (RuleModel): The underlying model object.

See Also:

TreeRegressor: A decision tree regressor with nominal support. CN2Regressor: A CN2Classifier regressor with nominal support. OneRRegressor: A OneR regressor with nominal support.

Examples:
>>> from sklearn_nominal import ZeroRRegressor, read_golf_regression_dataset
>>> x, y = read_golf_regression_dataset(url)
>>> model = ZeroRRegressor()
>>> from sklearn.metrics import mean_absolute_error
>>> model.fit(x, y)
>>> y_pred = model.predict(x)
>>> print(f"{mean_absolute_error(y, y_pred):.2f}")
0.07

Methods

build_error(criterion)

Builds the regression error function for the given criterion.

check_is_fitted()

Checks if the model has been fitted.

complexity()

Returns the complexity of the fitted model.

fit(x, y)

Fit the ZeroR model according to the given training data.

get_dtypes(x)

Extracts and maps data types from the input.

get_feature_names()

Returns the names of the features seen during fit.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

make_model(d)

Creates the ZeroR trainer for the model.

predict(x)

Predict regression value for X.

pretty_print([class_names])

Returns a string representation of the fitted model.

score(X, y[, sample_weight])

Return the coefficient of determination of the prediction.

set_dtypes(x)

Sets and persists the data types based on the input.

set_fit_request(*[, x])

Request metadata passed to the fit method.

set_model(model)

Sets the underlying backend model and marks it as fitted.

set_params(**params)

Set the parameters of this estimator.

set_predict_request(*[, x])

Request metadata passed to the predict method.

set_score_request(*[, sample_weight])

Request metadata passed to the score method.

set_sklearn_tags(tags)

Sets scikit-learn tags for the supervised nominal model.

validate_data_fit_regression(x, y)

Validates and prepares data for regression fitting.

validate_data_predict(x)

Validates and prepares input data for prediction.

build_error(criterion)#

Builds the regression error function for the given criterion.

Parameters:
criterionstr

The error criterion to use (e.g., “std” for standard deviation).

Returns:
TargetError

An instance of the requested error function.

Raises:
ValueError

If the criterion is not recognized.

check_is_fitted()#

Checks if the model has been fitted.

Raises:
NotFittedError

If the is_fitted_ attribute is not set or is False.

complexity()#

Returns the complexity of the fitted model.

The definition of complexity is backend and model dependent. For trees, it typically represents the number of nodes.

Returns:
int or float

The complexity metric of the model.

Raises:
NotFittedError

If the model has not been fitted yet.

fit(x, y)[source]#

Fit the ZeroR model according to the given training data.

The ZeroR algorithm identifies the mean target value in the training data and uses it for all future predictions, ignoring all input features.

Args:
x (pd.DataFrame or np.ndarray): The training input samples.

These are ignored by the ZeroR algorithm.

y (np.ndarray): The target values (real numbers).

Returns:

self: Returns the instance itself.

get_dtypes(x)#

Extracts and maps data types from the input.

This method identifies the data types of the input features to ensure they are correctly handled by the backend.

Parameters:
x{array-like, sparse matrix} of shape (n_samples, n_features)

The input data.

Returns:
dict or None

A dictionary mapping column names to data types if x is a DataFrame, otherwise None.

get_feature_names()#

Returns the names of the features seen during fit.

Returns:
ndarray of str or None

The feature names, or None if they were not available during fit (e.g., if input was a numpy array).

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

make_model(d)[source]#

Creates the ZeroR trainer for the model.

Args:

d (Dataset): The dataset to train on.

Returns:

ZeroR: The ZeroR trainer instance.

predict(x)[source]#

Predict regression value for X.

Always predicts the mean target value identified during fit() for all input samples.

Args:

x (pd.DataFrame or np.ndarray): The input samples.

Returns:
np.ndarray: Predicted target values for X, all equal to the

training mean.

pretty_print(class_names=None)#

Returns a string representation of the fitted model.

Delegates the visualization logic to the underlying backend model.

Parameters:
class_nameslist of str, optional

Names of the classes to use in the output. If None, default identifiers are used.

Returns:
str

A human-readable representation of the model.

Raises:
NotFittedError

If the model has not been fitted yet.

score(X, y, sample_weight=None)#

Return the coefficient of determination of the prediction.

The coefficient of determination \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True values for X.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

\(R^2\) of self.predict(X) w.r.t. y.

Notes

The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_dtypes(x)#

Sets and persists the data types based on the input.

This is called during fit to ensure that subsequent calls to predict can cast the input data to the same types, preserving nominal/numeric distinctions.

Parameters:
x{pd.DataFrame, np.ndarray, sparse matrix}

The input data to extract types from.

Raises:
ValueError

If the input type is not supported or if the input is not 2D.

set_fit_request(*, x: bool | None | str = '$UNCHANGED$') ZeroRRegressor#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
xstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for x parameter in fit.

Returns:
selfobject

The updated object.

set_model(model)#

Sets the underlying backend model and marks it as fitted.

Parameters:
modelsklearn_nominal.backend.core.Model

The trained model instance from the backend.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_predict_request(*, x: bool | None | str = '$UNCHANGED$') ZeroRRegressor#

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
xstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for x parameter in predict.

Returns:
selfobject

The updated object.

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') ZeroRRegressor#

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns:
selfobject

The updated object.

set_sklearn_tags(tags)#

Sets scikit-learn tags for the supervised nominal model.

Parameters:
tagsTags

The scikit-learn tags object to be modified.

validate_data_fit_regression(x, y)#

Validates and prepares data for regression fitting.

This method ensures x and y are compatible, extracts data types, and packages them into a backend Dataset. It also ensures the target y is at least 2D for backend consistency.

Parameters:
xarray-like of shape (n_samples, n_features)

The input features.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

The target values.

Returns:
Dataset

The backend-specific dataset object.

Return type:

Dataset

validate_data_predict(x)#

Validates and prepares input data for prediction.

This method ensures the input features match the structure seen during training, handles feature name alignment, and restores data types.

Parameters:
xarray-like of shape (n_samples, n_features)

The input data to validate.

Returns:
pd.DataFrame

The validated data as a pandas DataFrame, with dtypes restored to match those observed during training.

Raises:
NotFittedError

If the model has not been fitted yet.

ValueError

If the input contains no samples or has inconsistent features.