NominalClassifier#
- class sklearn_nominal.sklearn.nominal_model.NominalClassifier(class_weight=None, *args, **kwargs)[source]#
Base class for nominal classifiers.
This class coordinates the end-to-end classification workflow, including target encoding, class weight computation, and delegation to backend trainers.
- Attributes:
- class_weightdict, list of dicts or “balanced”, default=None
Weights associated with classes in the form
{class_label: weight}. If not given, all classes are supposed to have weight one.- classes_ndarray of shape (n_classes,)
The unique class labels observed during
fit.- le_sklearn.preprocessing.LabelEncoder
The encoder used to map class labels to internal integer indices.
Examples
>>> from sklearn_nominal.sklearn.nominal_model import NominalClassifier >>> class MyClassifier(NominalClassifier): ... def make_model(self, d, class_weight): ... # Return a backend-specific trainer ... pass
Methods
build_error(criterion, class_weight)Builds the error function for the given criterion.
Checks if the model has been fitted.
Returns the complexity of the fitted model.
fit(x, y)Fits the nominal classifier.
Computes the class weights based on the input target.
get_dtypes(x)Extracts and maps data types from the input.
Returns the names of the features seen during fit.
get_y(y)Validates and encodes the target labels.
make_model(d, class_weight)Abstract method to create the model trainer.
predict(x)Predicts class labels for input samples.
Predicts class probabilities for input samples.
pretty_print([class_names])Returns a string representation of the fitted model.
score(X, y[, sample_weight])Return the mean accuracy on the given test data and labels.
set_dtypes(x)Sets and persists the data types based on the input.
set_model(model)Sets the underlying backend model and marks it as fitted.
set_sklearn_tags(tags)Sets scikit-learn tags for the supervised nominal model.
Validates and transforms data for classification fitting.
Validates and prepares input data for prediction.
- build_error(criterion, class_weight)[source]#
Builds the error function for the given criterion.
- Parameters:
- criterionstr
The error criterion to use (e.g., “entropy”, “gini”, “gain_ratio”).
- class_weightnp.ndarray
The class weights to be used by the error function.
- Returns:
- TargetError
An instance of the requested error function from
sklearn_nominal.shared.
- Raises:
- ValueError
If the criterion is not recognized.
- Return type:
TargetError
- 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]#
Fits the nominal classifier.
- Parameters:
- x{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples.
- yarray-like of shape (n_samples,)
The target values (class labels).
- Returns:
- selfobject
Returns the instance itself.
- get_class_weights(y)[source]#
Computes the class weights based on the input target.
- Parameters:
- yarray-like of shape (n_samples,)
The target labels.
- Returns:
- np.ndarray
The computed weights for each class, aligned with
self.classes_.
- 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
xis 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_y(y)[source]#
Validates and encodes the target labels.
- Parameters:
- yarray-like of shape (n_samples,)
The target labels to encode.
- Returns:
- ndarray
The integer-encoded target labels.
- abstractmethod make_model(d, class_weight)[source]#
Abstract method to create the model trainer.
- Parameters:
- dDataset
The training dataset prepared by
validate_data_fit_classification.- class_weightnp.ndarray
The class weights computed during validation.
- Returns:
- trainerobject
A trainer instance capable of fitting the provided dataset.
- predict(x)[source]#
Predicts class labels for input samples.
- Parameters:
- x{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples to predict.
- Returns:
- ndarray of shape (n_samples,)
The predicted class labels.
- Return type:
- predict_proba(x)[source]#
Predicts class probabilities for input samples.
This method first validates the input data to ensure compatibility with the fitted model, then delegates the prediction to the backend
model_.- Parameters:
- x{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples to predict.
- Returns:
- ndarray of shape (n_samples, n_classes)
The class probabilities of the input samples. The order of the classes corresponds to that in the attribute
classes_.
- Return type:
- 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 mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Test samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True labels for
X.- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns:
- scorefloat
Mean accuracy of
self.predict(X)w.r.t.y.
- set_dtypes(x)#
Sets and persists the data types based on the input.
This is called during
fitto ensure that subsequent calls topredictcan 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_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_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_classification(x, y)[source]#
Validates and transforms data for classification fitting.
This method performs the following transformations: 1. Validates
xandyusing scikit-learn’svalidate_data. 2. Determines the unique classes and stores them inclasses_. 3. EncodesyusingLabelEncoder. 4. Calculates class weights based on theclass_weightparameter. 5. Packages features and the encoded target into a backend-specificDataset(e.g.,PandasDataset).- 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 labels.
- Returns:
- tuple
A tuple containing: - Dataset : The backend-specific dataset object. - np.ndarray : The computed class weights for each class in
classes_.
- Raises:
- ValueError
If
ycontains only one unique class.
- 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.