API Reference

Note

This API section focuses on the public Python wrappers. The internal compiled core is not documented here to avoid confusion.

Quick example

from fuzzycocopython import FuzzyCocoClassifier

clf = FuzzyCocoClassifier(random_state=0)
clf.fit(X, y)
preds = clf.predict(X)
print(clf.score(X, y))

Estimators

class fuzzycocopython.fuzzycoco_base.FuzzyCocoClassifier(nb_rules=5, nb_max_var_per_rule=3, max_generations=100, max_fitness=1.0, nb_cooperators=2, influence_rules_initial_population=False, influence_evolving_ratio=0.8, nb_sets_in=2, nb_sets_out=2, pop_size_rules=200, pop_size_mfs=200, elite_size_rules=5, elite_size_mfs=5, cx_prob_rules=0.6, cx_prob_mfs=0.9, mut_flip_genome_rules=0.4, mut_flip_genome_mfs=0.2, mut_flip_bit_rules=0.01, mut_flip_bit_mfs=0.01, nb_bits_pos_in=8, nb_bits_pos_out=8, nb_bits_vars_in=None, nb_bits_vars_out=None, nb_bits_sets_in=None, nb_bits_sets_out=None, threshold=0.5, metrics_weights=None, features_weights=None, random_state=None)[source]

Bases: ClassifierMixin, FuzzyCocoPlotMixin, _FuzzyCocoBase

describe()

Return the full model description (variables, rules, defaults).

Returns:

A dictionary mirroring the native engine description, including the serialized fuzzy system and related metadata.

fit(X, y, **kwargs)[source]

Fit the classifier on X and y.

See _FuzzyCocoBase.fit() for details on accepted parameters.

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

classmethod load(filepath)

Load a previously saved estimator instance of this class.

Parameters:

filepath – Path to the serialized estimator created via save().

Returns:

An instance of the estimator loaded from disk.

plot_aggregated_output(input_sample, figsize=(12, 10))

Visualize the aggregated fuzzy output for an input sample.

Uses a SingletonFIS to mirror the C++ singleton-based defuzzification.

Parameters:
  • input_sample – Single sample of crisp input values.

  • figsize – Matplotlib figure size.

plot_fuzzification(sample, variable=None, **kwargs)

Plot membership functions and overlay fuzzification for a sample.

Parameters:
  • sample – Array-like, dict, or pandas Series holding crisp inputs.

  • variable – None, str, or list[str]. If None, plot all input variables present in the sample; if str, only that variable; if list, each listed variable.

  • **kwargs – Extra options forwarded to the membership function viewer.

plot_fuzzy_sets(variable=None, **kwargs)

Plot membership functions for variables.

Parameters:
  • variable – None, str, or list[str]. If None, plot all variables; if str, plot only that variable; if list, plot each listed variable.

  • **kwargs – Extra options passed to the membership function viewer.

plot_rule_activations(x, figsize=(9, 4), sort=True, top=None, annotate=True, tick_fontsize=8)

Bar plot of rule activations for a single sample.

Parameters:
  • x – Single sample as array-like compatible with rules_activations.

  • figsize – Matplotlib figure size.

  • sort – Sort bars by activation descending.

  • top – Show only the first top rules after sorting.

  • annotate – Write activation values on top of bars.

  • tick_fontsize – Font size for x tick labels.

Returns:

None. Displays a matplotlib figure.

predict(X)[source]

Predict class labels for X.

Returns numpy array of labels matching the original label dtype.

rules_activations(X)

Compute rule activation levels for a single sample.

Parameters:

X – Single sample as 1D array-like, pandas Series, or single-row DataFrame.

Returns:

1D numpy array of length n_rules with activation strengths in [0, 1].

rules_stat_activations(X, threshold=1e-12, return_matrix=False, sort_by_impact=True)

Compute aggregate rule activations for a batch of samples.

Parameters:
  • X – 2D array-like or DataFrame of samples to analyze.

  • threshold – Minimum activation value to count a rule as “used”.

  • return_matrix – If True, also return the (n_samples, n_rules) activation matrix.

  • sort_by_impact – If True, sort the summary by estimated impact.

Returns:

If return_matrix is False, a pandas DataFrame with per-rule statistics (mean, std, min, max, usage rates, and impact). If True, returns a tuple (stats_df, activations_matrix).

save(filepath, *, compress=3)

Save this fitted estimator to disk (convenience wrapper).

Parameters:
  • filepath – Destination path for the serialized estimator.

  • compress – Joblib compression parameter.

Returns:

The path used to save the model.

score(X, y, sample_weight=None)

Return accuracy on provided 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:
  • X (array-like of shape (n_samples, n_features)) – Test samples.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.

  • sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.

Returns:

score – Mean accuracy of self.predict(X) w.r.t. y.

Return type:

float

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:

**params (dict) – Estimator parameters.

Returns:

self – Estimator instance.

Return type:

estimator instance

class fuzzycocopython.fuzzycoco_base.FuzzyCocoRegressor(nb_rules=5, nb_max_var_per_rule=3, max_generations=100, max_fitness=1.0, nb_cooperators=2, influence_rules_initial_population=False, influence_evolving_ratio=0.8, nb_sets_in=2, nb_sets_out=2, pop_size_rules=200, pop_size_mfs=200, elite_size_rules=5, elite_size_mfs=5, cx_prob_rules=0.6, cx_prob_mfs=0.9, mut_flip_genome_rules=0.4, mut_flip_genome_mfs=0.2, mut_flip_bit_rules=0.01, mut_flip_bit_mfs=0.01, nb_bits_pos_in=8, nb_bits_pos_out=8, nb_bits_vars_in=None, nb_bits_vars_out=None, nb_bits_sets_in=None, nb_bits_sets_out=None, threshold=0.5, metrics_weights=None, features_weights=None, random_state=None)[source]

Bases: RegressorMixin, FuzzyCocoPlotMixin, _FuzzyCocoBase

describe()

Return the full model description (variables, rules, defaults).

Returns:

A dictionary mirroring the native engine description, including the serialized fuzzy system and related metadata.

fit(X, y, **fit_params)

Fit a fuzzy rule-based model.

Parameters:
  • X – 2D array-like or pandas DataFrame of shape (n_samples, n_features).

  • y – 1D or 2D array-like or pandas Series/DataFrame with targets.

  • **fit_params – Optional keyword-only parameters: - feature_names: list of column names to use when X is not a DataFrame. - target_name: name of the output variable in the fuzzy system.

Returns:

The fitted estimator instance.

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

classmethod load(filepath)

Load a previously saved estimator instance of this class.

Parameters:

filepath – Path to the serialized estimator created via save().

Returns:

An instance of the estimator loaded from disk.

plot_aggregated_output(input_sample, figsize=(12, 10))

Visualize the aggregated fuzzy output for an input sample.

Uses a SingletonFIS to mirror the C++ singleton-based defuzzification.

Parameters:
  • input_sample – Single sample of crisp input values.

  • figsize – Matplotlib figure size.

plot_fuzzification(sample, variable=None, **kwargs)

Plot membership functions and overlay fuzzification for a sample.

Parameters:
  • sample – Array-like, dict, or pandas Series holding crisp inputs.

  • variable – None, str, or list[str]. If None, plot all input variables present in the sample; if str, only that variable; if list, each listed variable.

  • **kwargs – Extra options forwarded to the membership function viewer.

plot_fuzzy_sets(variable=None, **kwargs)

Plot membership functions for variables.

Parameters:
  • variable – None, str, or list[str]. If None, plot all variables; if str, plot only that variable; if list, plot each listed variable.

  • **kwargs – Extra options passed to the membership function viewer.

plot_rule_activations(x, figsize=(9, 4), sort=True, top=None, annotate=True, tick_fontsize=8)

Bar plot of rule activations for a single sample.

Parameters:
  • x – Single sample as array-like compatible with rules_activations.

  • figsize – Matplotlib figure size.

  • sort – Sort bars by activation descending.

  • top – Show only the first top rules after sorting.

  • annotate – Write activation values on top of bars.

  • tick_fontsize – Font size for x tick labels.

Returns:

None. Displays a matplotlib figure.

predict(X)[source]

Predict continuous targets for X.

Returns a 1D array for single-output models or 2D for multi-output.

rules_activations(X)

Compute rule activation levels for a single sample.

Parameters:

X – Single sample as 1D array-like, pandas Series, or single-row DataFrame.

Returns:

1D numpy array of length n_rules with activation strengths in [0, 1].

rules_stat_activations(X, threshold=1e-12, return_matrix=False, sort_by_impact=True)

Compute aggregate rule activations for a batch of samples.

Parameters:
  • X – 2D array-like or DataFrame of samples to analyze.

  • threshold – Minimum activation value to count a rule as “used”.

  • return_matrix – If True, also return the (n_samples, n_rules) activation matrix.

  • sort_by_impact – If True, sort the summary by estimated impact.

Returns:

If return_matrix is False, a pandas DataFrame with per-rule statistics (mean, std, min, max, usage rates, and impact). If True, returns a tuple (stats_df, activations_matrix).

save(filepath, *, compress=3)

Save this fitted estimator to disk (convenience wrapper).

Parameters:
  • filepath – Destination path for the serialized estimator.

  • compress – Joblib compression parameter.

Returns:

The path used to save the model.

score(X, y, sample_weight=None)

Return coefficient of determination on test data.

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:
  • X (array-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.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.

  • sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.

Returns:

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

Return type:

float

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_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:

**params (dict) – Estimator parameters.

Returns:

self – Estimator instance.

Return type:

estimator instance

Utilities

fuzzycocopython.fuzzycoco_base.save_model(model, filepath, *, compress=3)[source]

Save a fitted estimator to disk with joblib.

Parameters - model: the fitted estimator instance (classifier or regressor) - filepath: target path (str or Path-like) - compress: joblib compression level or bool

Returns the path string.

fuzzycocopython.fuzzycoco_base.load_model(filepath)[source]

Load a previously saved estimator created with save_model.

from fuzzycocopython import FuzzyCocoClassifier
from fuzzycocopython.fuzzycoco_base import save_model, load_model

clf = FuzzyCocoClassifier().fit(X, y)
save_model(clf, "clf.joblib")

restored = load_model("clf.joblib")
print(restored.predict(X[:5]))

Plotting

class fuzzycocopython.fuzzycoco_plot_mixin.FuzzyCocoPlotMixin[source]

Bases: object

A mixin class providing plotting methods for FuzzyCoco estimators.

Requires that the estimator using this mixin define:

  • self.variables_

  • self.rules_

  • self.model_ (if using plot_rule_activations or plot_aggregated_output)

  • self.default_rules_ (if referencing default rules, e.g. in plot_aggregated_output)

  • self._predict (if used in plot_aggregated_output)

plot_aggregated_output(input_sample, figsize=(12, 10))[source]

Visualize the aggregated fuzzy output for an input sample.

Uses a SingletonFIS to mirror the C++ singleton-based defuzzification.

Parameters:
  • input_sample – Single sample of crisp input values.

  • figsize – Matplotlib figure size.

plot_fuzzification(sample, variable=None, **kwargs)[source]

Plot membership functions and overlay fuzzification for a sample.

Parameters:
  • sample – Array-like, dict, or pandas Series holding crisp inputs.

  • variable – None, str, or list[str]. If None, plot all input variables present in the sample; if str, only that variable; if list, each listed variable.

  • **kwargs – Extra options forwarded to the membership function viewer.

plot_fuzzy_sets(variable=None, **kwargs)[source]

Plot membership functions for variables.

Parameters:
  • variable – None, str, or list[str]. If None, plot all variables; if str, plot only that variable; if list, plot each listed variable.

  • **kwargs – Extra options passed to the membership function viewer.

plot_rule_activations(x, figsize=(9, 4), sort=True, top=None, annotate=True, tick_fontsize=8)[source]

Bar plot of rule activations for a single sample.

Parameters:
  • x – Single sample as array-like compatible with rules_activations.

  • figsize – Matplotlib figure size.

  • sort – Sort bars by activation descending.

  • top – Show only the first top rules after sorting.

  • annotate – Write activation values on top of bars.

  • tick_fontsize – Font size for x tick labels.

Returns:

None. Displays a matplotlib figure.