Classifier API¶
The ANFISClassifier offers a scikit-learn inspired interface for multi-class
classification tasks, wrapping membership-function management, model
construction, and training into a single estimator.
anfis_toolbox.classifier.ANFISClassifier ¶
ANFISClassifier(
*,
n_classes: int | None = None,
n_mfs: int = 3,
mf_type: str = "gaussian",
init: str | None = "grid",
overlap: float = 0.5,
margin: float = 0.1,
inputs_config: Mapping[Any, Any] | None = None,
random_state: int | None = None,
optimizer: str
| BaseTrainer
| type[BaseTrainer]
| None = "adam",
optimizer_params: Mapping[str, Any] | None = None,
learning_rate: float | None = None,
epochs: int | None = None,
batch_size: int | None = None,
shuffle: bool | None = None,
verbose: bool = False,
loss: LossFunction | str | None = None,
rules: Sequence[Sequence[int]] | None = None,
)
Bases: BaseEstimatorLike, FittedMixin, ClassifierMixinLike
Adaptive Neuro-Fuzzy classifier with a scikit-learn style API.
The estimator manages membership-function synthesis, rule construction, and
trainer selection so you can focus on calling :meth:fit,
:meth:predict, :meth:predict_proba, and :meth:evaluate with familiar
NumPy-like data structures.
Examples:¶
clf = ANFISClassifier() clf.fit(X, y) ANFISClassifier(...) clf.predict([[0.1, -0.2]]) array([...])
Parameters¶
n_classes : int, optional
Number of target classes. Must be >= 2 when provided. If omitted, the
classifier infers the class count during the first call to fit.
n_mfs : int, default=3
Default number of membership functions per input.
mf_type : str, default="gaussian"
Default membership function family applied when membership functions are
inferred from data.
init : {"grid", "fcm", "random", None}, default="grid"
Strategy used when inferring membership functions from data. None
falls back to "grid".
overlap : float, default=0.5
Controls overlap when generating membership functions automatically.
margin : float, default=0.10
Margin added around observed data ranges during grid initialization.
inputs_config : Mapping, optional
Per-input overrides. Keys may be feature names (when X is a
:class:pandas.DataFrame) or integer indices. Values may be:
* ``dict`` with keys among ``{"n_mfs", "mf_type", "init", "overlap",
"margin", "range", "membership_functions", "mfs"}``.
* A list or tuple of membership function objects for full control.
* ``None`` for defaults.
random_state : int, optional
Random state forwarded to initialization routines and stochastic
optimizers.
optimizer : str, BaseTrainer, type[BaseTrainer], or None, default="adam"
Trainer identifier or instance used for fitting. Strings map to entries
in :data:TRAINER_REGISTRY. None defaults to "adam".
optimizer_params : Mapping, optional
Additional keyword arguments forwarded to the trainer constructor.
learning_rate, epochs, batch_size, shuffle, verbose : optional scalars
Common trainer hyper-parameters provided for convenience. When the
selected trainer supports the parameter it is included automatically.
loss : str or LossFunction, optional
Custom loss forwarded to trainers that expose a loss parameter.
rules : Sequence[Sequence[int]] | None, optional
Explicit fuzzy rule indices to use instead of the full Cartesian product. Each
rule lists the membership-function index per input. None keeps the default
exhaustive rule set.
Parameters¶
n_classes : int, optional
Number of output classes. Must be at least two when provided. If
omitted, the value is inferred from the training targets during
the first fit call.
n_mfs : int, default=3
Default number of membership functions to allocate per input when
inferred from data.
mf_type : str, default="gaussian"
Membership function family used for automatically generated
membership functions.
init : {"grid", "fcm", "random", None}, default="grid"
Initialization strategy applied when synthesizing membership
functions from the training data. None falls back to "grid".
overlap : float, default=0.5
Desired overlap between adjacent membership functions during
automatic generation.
margin : float, default=0.10
Additional range padding applied around observed feature minima
and maxima for grid initialization.
inputs_config : Mapping, optional
Per-feature overrides for the generated membership functions.
Keys may be feature names (when X is a :class:pandas.DataFrame),
integer indices, or "x{i}" aliases. Values may include dictionaries
with membership-generation arguments, explicit membership function
sequences, or None to retain defaults.
random_state : int, optional
Seed forwarded to stochastic initializers and optimizers.
optimizer : str | BaseTrainer | type[BaseTrainer] | None, default="adam"
Training algorithm identifier or instance. String aliases are looked
up in :data:TRAINER_REGISTRY. None defaults to "adam".
Hybrid variants that depend on least-squares refinements are limited
to regression and raise ValueError when supplied here.
optimizer_params : Mapping, optional
Additional keyword arguments provided to the trainer constructor
when a string alias or trainer class is supplied.
learning_rate, epochs, batch_size, shuffle, verbose : optional
Convenience hyper-parameters injected into the trainer whenever the
chosen implementation accepts them. shuffle supports False
to disable random shuffling.
loss : str | LossFunction, optional
Custom loss specification forwarded to trainers that expose a
loss parameter. None resolves to cross-entropy.
rules : Sequence[Sequence[int]] | None, optional
Optional explicit fuzzy rule definitions. Each rule lists the
membership-function index for each input. None uses the full
Cartesian product of configured membership functions.
Source code in anfis_toolbox/classifier.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__repr__ ¶
Return a formatted representation summarising configuration and fitted artefacts.
evaluate ¶
evaluate(
X: ArrayLike,
y: ArrayLike,
*,
return_dict: bool = True,
print_results: bool = True,
) -> Mapping[str, MetricValue] | None
Evaluate predictive performance on a labelled dataset.
Parameters¶
X : array-like
Evaluation inputs.
y : array-like
Ground-truth labels. Accepts integer labels or one-hot encodings.
return_dict : bool, default=True
When True return the computed metric dictionary; when False
return None after optional printing.
print_results : bool, default=True
Emit a formatted summary to stdout. Set to False to suppress
printing.
Returns:¶
Mapping[str, MetricValue] | None
Dictionary containing accuracy, balanced accuracy, macro/micro
precision/recall/F1 scores, and the confusion matrix when
return_dict is True; otherwise None.
Raises:¶
RuntimeError
If called before the estimator has been fitted.
ValueError
When X and y disagree on sample count or labels are
incompatible with the configured class count.
Source code in anfis_toolbox/classifier.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
fit ¶
fit(
X: ArrayLike,
y: ArrayLike,
*,
validation_data: tuple[ndarray, ndarray] | None = None,
validation_frequency: int = 1,
verbose: bool | None = None,
**fit_params: Any,
) -> ANFISClassifier
Fit the classifier on labelled data.
Parameters¶
X : array-like
Training inputs with shape (n_samples, n_features).
y : array-like
Target labels. Accepts integer or string labels as well as one-hot
matrices with shape (n_samples, n_classes).
validation_data : tuple[np.ndarray, np.ndarray], optional
Optional validation split supplied to the underlying trainer.
Inputs and targets must already be numeric and share the same row
count.
validation_frequency : int, default=1
Frequency (in epochs) at which validation metrics are computed when
validation_data is provided.
verbose : bool, optional
Override the estimator's verbose flag for this fit call. When
provided, the value is stored on the estimator and forwarded to the
trainer configuration.
**fit_params : Any
Additional keyword arguments forwarded directly to the trainer
fit method.
Returns:¶
ANFISClassifier
Reference to self to enable fluent-style chaining.
Raises:¶
ValueError
If the input arrays disagree on the number of samples or the label
encoding is incompatible with the configured n_classes.
TypeError
If the trainer fit implementation does not return a
dictionary-style training history.
Source code in anfis_toolbox/classifier.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
get_rules ¶
Return the fuzzy rule index combinations used by the fitted model.
Returns:¶
tuple[tuple[int, ...], ...] Immutable tuple describing each fuzzy rule as a per-input membership index.
Raises:¶
RuntimeError
If invoked before fit completes.
Source code in anfis_toolbox/classifier.py
load
classmethod
¶
Load a pickled ANFISClassifier from filepath and validate its type.
Source code in anfis_toolbox/classifier.py
predict ¶
Predict class labels for the provided samples.
Parameters¶
X : array-like
Samples to classify. One-dimensional arrays are treated as a single
sample; two-dimensional arrays must have shape (n_samples, n_features).
Returns:¶
np.ndarray
Predicted class labels with shape (n_samples,).
Raises:¶
RuntimeError If invoked before the estimator is fitted. ValueError When the supplied samples do not match the fitted feature count.
Source code in anfis_toolbox/classifier.py
predict_proba ¶
Predict class probabilities for the provided samples.
Parameters¶
X : array-like Samples for which to estimate class probabilities.
Returns:¶
np.ndarray
Matrix of shape (n_samples, n_classes) containing class
probability estimates.
Raises:¶
RuntimeError If the estimator has not been fitted. ValueError If sample dimensionality does not match the fitted feature count.
Source code in anfis_toolbox/classifier.py
save ¶
Serialize this estimator (including fitted artefacts) to filepath.