Fuzzy Sets#
The ex_fuzzy.fuzzy_sets module provides core fuzzy-set primitives used by
classifiers and rule bases.
Key Classes#
- class ex_fuzzy.fuzzy_sets.FS(name, membership_parameters, domain=None)[source]#
Bases:
objectBase class for Type-1 fuzzy sets (Zadeh fuzzy sets).
This class implements the fundamental Type-1 fuzzy set with crisp membership functions. It serves as the base class for more specialized fuzzy set types like triangular, gaussian, and categorical fuzzy sets.
- name#
The linguistic name of the fuzzy set (e.g., “low”, “medium”, “high”)
- Type:
str
- membership_parameters#
Parameters defining the membership function
- Type:
list[float]
- domain#
Two-element list defining the universe of discourse [min, max]
- Type:
list[float]
Example
>>> fs = FS("medium", [1, 2, 3, 4], [0, 5]) # Trapezoidal fuzzy set >>> membership = fs.membership(2.5) >>> print(membership) # Should be 1.0 (fully in the set)
Note
This class uses trapezoidal membership functions by default. For other shapes, use specialized subclasses like gaussianFS or triangularFS.
- __init__(name, membership_parameters, domain=None)[source]#
Initialize a Type-1 fuzzy set.
- Parameters:
name (str) – Linguistic name for the fuzzy set
membership_parameters (list[float]) – Four parameters [a, b, c, d] defining the trapezoidal membership function where: - a: left foot (membership starts rising from 0) - b: left shoulder (membership reaches 1.0) - c: right shoulder (membership starts falling from 1.0) - d: right foot (membership reaches 0)
domain (list[float]) – Two-element list [min, max] defining the universe of discourse for this fuzzy set
Example
>>> fs = FS("medium", [2, 3, 7, 8], [0, 10]) >>> # Creates a trapezoidal set: rises from 2-3, flat 3-7, falls 7-8
- membership(x)[source]#
Compute membership degrees for input values.
This method calculates the membership degree(s) for the given input value(s) using the trapezoidal membership function defined by this fuzzy set’s parameters.
- Parameters:
x (np.array) – Input value(s) for which to compute membership degrees. Can be a single value, list, or numpy array.
- Returns:
Membership degree(s) in the range [0, 1]. Shape matches input.
- Return type:
np.array
Example
>>> fs = FS("medium", [2, 3, 7, 8], [0, 10]) >>> print(fs.membership(5)) # 1.0 (in flat region) >>> print(fs.membership(2.5)) # 0.5 (on rising slope) >>> print(fs.membership([1, 5, 9])) # [0.0, 1.0, 0.0]
- type()[source]#
Return the fuzzy set type identifier.
- Returns:
The type identifier (FUZZY_SETS.t1 for Type-1 fuzzy sets)
- Return type:
- __call__(x)[source]#
Calling the Fuzzy set returns its membership.
- Parameters:
x (array) – input values in the fuzzy set referencial domain.
- Returns:
membership of the fuzzy set.
- Return type:
array
- class ex_fuzzy.fuzzy_sets.gaussianFS(name, membership_parameters, domain=None)[source]#
Bases:
FSGaussian Type-1 Fuzzy Set Implementation.
This class implements a Gaussian fuzzy set with bell-shaped membership function. Gaussian fuzzy sets are characterized by their mean and standard deviation, providing smooth membership transitions ideal for continuous variables.
- membership_parameters#
[mean, standard_deviation] defining the Gaussian curve
- Type:
list
- name#
Human-readable name for the fuzzy set
- Type:
str
- universe_size#
Size of the universe of discourse
- Type:
int
Example
>>> params = [5.0, 1.5] # mean=5, std=1.5 >>> gauss_fs = gaussianFS(params, "Medium", 10) >>> membership = gauss_fs.membership(np.array([4.0, 5.0, 6.0])) >>> print(membership) # [0.606, 1.0, 0.606]
Note
The membership function follows the formula: μ(x) = exp(-0.5 * ((x - mean) / std)^2)
- membership(input)[source]#
Computes the Gaussian membership values for input points.
The membership function implements the Gaussian curve formula using the mean and standard deviation parameters.
- Parameters:
input (np.array) – Input values in the fuzzy set domain
- Returns:
Membership values in range [0, 1]
- Return type:
np.array
Example
>>> gauss_fs = gaussianFS([0, 1], "Zero", 5) >>> values = gauss_fs.membership(np.array([-1, 0, 1])) >>> print(values) # [0.606, 1.0, 0.606]
- class ex_fuzzy.fuzzy_sets.gaussianIVFS(name, secondMF_lower, secondMF_upper, domain, lower_height=1.0)[source]#
Bases:
IVFSGaussian Interval-Valued (Type-2) Fuzzy Set Implementation.
This class implements a Gaussian interval-valued fuzzy set with two Gaussian membership functions (upper and lower) representing the uncertainty boundaries. This allows for modeling higher-order uncertainty in fuzzy systems.
- secondMF_lower#
Parameters [mean, std] for the lower membership function
- Type:
list
- secondMF_upper#
Parameters [mean, std] for the upper membership function
- Type:
list
- name#
Human-readable name for the fuzzy set
- Type:
str
- universe_size#
Size of the universe of discourse
- Type:
int
Example
>>> lower_params = [5.0, 1.0] >>> upper_params = [5.0, 1.5] >>> iv_gauss = gaussianIVFS(lower_params, upper_params, "Medium", 10) >>> membership = iv_gauss.membership(np.array([4.0, 5.0, 6.0])) >>> print(membership.shape) # (3, 2) - lower and upper bounds
Note
The interval-valued membership function provides both lower and upper bounds for each input, enabling Type-2 fuzzy reasoning.
- __init__(name, secondMF_lower, secondMF_upper, domain, lower_height=1.0)[source]#
Initialize a Gaussian interval-valued fuzzy set.
- Parameters:
name (str) – Linguistic name for the fuzzy set
secondMF_lower (list[float]) – [mean, std] of the lower membership function
secondMF_upper (list[float]) – [mean, std] of the upper membership function
domain (list[float]) – Two-element list [min, max] defining universe of discourse
lower_height (float, optional) – Maximum height of lower membership function. Defaults to 1.0.
- membership(input)[source]#
Computes the Gaussian interval-valued membership values for input points.
Returns both lower and upper membership bounds for each input value, enabling Type-2 fuzzy set operations.
- Parameters:
input (np.array) – Input values in the fuzzy set domain
- Returns:
Array of shape (n, 2) with [lower, upper] bounds for each input
- Return type:
np.array
Example
>>> iv_gauss = gaussianIVFS([0, 1], [0, 1.5], "Zero", 5) >>> values = iv_gauss.membership(np.array([0.0, 1.0])) >>> print(values.shape) # (2, 2) - 2 inputs, 2 bounds each
- class ex_fuzzy.fuzzy_sets.categoricalFS(name, category)[source]#
Bases:
FS- __init__(name, category)[source]#
Creates a categorical fuzzy set. It gives 1 to the category and 0 to the rest. Use it when the variable is categorical and the categories are known, so that rule inference systems can naturally support both crisp and fuzzy variables.
- Parameters:
name (str) – string.
categories – list of strings. Possible categories.
- membership(x)[source]#
Computes the membership of a point or vector of elements.
- Parameters:
x (array) – input values in the referencial domain.
- class ex_fuzzy.fuzzy_sets.fuzzyVariable(name, fuzzy_sets, units=None, ordinal_conditions=False, compound_terms=None)[source]#
Bases:
objectFuzzy Variable Container and Management Class.
This class represents a fuzzy variable composed of multiple fuzzy sets (linguistic variables). It provides methods to compute memberships across all fuzzy sets and manage the linguistic terms of the variable.
- linguistic_variables#
List of fuzzy sets that define the variable
- Type:
list
- name#
Name of the fuzzy variable
- Type:
str
- units#
Units of measurement (optional, for display purposes)
- Type:
str
- fs_type#
Type of fuzzy sets (t1 or t2)
- Type:
Example
>>> # Create fuzzy sets for temperature >>> low_temp = gaussianFS("Low", [15, 5], [0, 50]) >>> medium_temp = gaussianFS("Medium", [25, 5], [0, 50]) >>> high_temp = gaussianFS("High", [35, 5], [0, 50]) >>> >>> # Create fuzzy variable >>> temp_var = fuzzyVariable("Temperature", [low_temp, medium_temp, high_temp], "°C") >>> memberships = temp_var.compute_memberships([20, 25, 30]) # or temp_var([20, 25, 30]) >>> print(memberships.shape) # (3, 3) - (fuzzy sets, inputs)
Note
All fuzzy sets in the variable must be of the same type (t1 or t2).
The terms are ordered as they are listed, from low to high. With
ordinal_conditions=Truethe variable also offers the conditionsat least t_jandat most t_j(j = 1 .. n - 2), whose membership is the bounded summin(1, sum of the memberships of the terms they cover); seeordinal_alphabet_size(). A condition is named by an integer code: the term index for a single term, then theat leastcodes, then theat mostones, then the named compound terms (condition()).compound_terms=[(name, [terms])...]adds one condition per entry, whose membership is the bounded sum of the listed terms, which need not be contiguous (a union that wraps around, such as[last, first], is two shoulders, one at each end of the axis). Off by default, and then nothing about the variable changes.- ordinal = False#
Class default, so that variables pickled before ordinal conditions existed load as they were.
- compound = ()#
Named compound terms,
((name, (term indexes...)), ...); empty unless asked for.
- __init__(name, fuzzy_sets, units=None, ordinal_conditions=False, compound_terms=None)[source]#
Creates a fuzzy variable with the specified fuzzy sets.
- Parameters:
name (str) – Name of the fuzzy variable
fuzzy_sets (list[FS]) – List of fuzzy sets that comprise the linguistic variables
units (str, optional) – Units of the fuzzy variable for display purposes
ordinal_conditions (bool, optional) – offer
at least/at mostconditions over the ordered terms (default False). Needs 3 or more Type-1 or interval Type-2 terms that are not categorical.compound_terms (list, optional) –
[(name, [terms])...], each entry one more condition whose membership is the bounded sum of the listed terms (names or indexes): at least 2 distinct terms and not all of them; the sets must differ from each other and from the ordinal conditions of the variable.
- Raises:
ValueError – If fuzzy_sets is empty or contains mixed types, or
ordinal_conditionsis asked of a variable that cannot have them
Example
>>> fs1 = gaussianFS([0, 1], "Low", 10) >>> fs2 = gaussianFS([5, 1], "High", 10) >>> var = fuzzyVariable("Speed", [fs1, fs2], "m/s")
- ordinal_eligible(strict=False)[source]#
Whether this variable can offer ordinal conditions: 3 or more ordered, non-categorical Type-1 or interval Type-2 terms. With
stricta general Type-2 variable raises instead of returning False.
- n_conditions()[source]#
Number of conditions (term codes) the variable offers: its terms, then the ordinal ones if enabled, then the named compound terms.
- condition(code)[source]#
(operator, reference)of a condition code.The operator is
'is'(reference: term index),'at_least'or'at_most'(reference: term indext_j) or'any_of'(reference: position of the compound inself.compound).
- condition_code(operator, term)[source]#
Code of the condition
operator+ term index (inverse ofcondition()); for'any_of'termis the name of the compound term (or its position).
- condition_terms(code)[source]#
Indexes of the terms a condition covers: one for
is,t_j .. t_(n-1)forat_least t_j,t_0 .. t_jforat_most t_j, the listed terms (low to high) forany_of.
- condition_names()[source]#
Text of every condition, by code: the term names, then
at least <term>, thenat most <term>, then the names of the compound terms. Without extra conditions this islinguistic_variable_names().
- condition_memberships(terms)[source]#
Memberships of every condition from those of the terms,
(n_terms, ...)to(n_conditions, ...).
- append(fs)[source]#
Appends a fuzzy set to the fuzzy variable.
- Parameters:
fs (FS) – FS. Fuzzy set to append.
- linguistic_variable_names()[source]#
Returns the name of the linguistic variables.
- Returns:
list of strings.
- Return type:
list
- get_linguistic_variables()[source]#
Returns the name of the linguistic variables.
- Returns:
list of strings.
- Return type:
list[FS]
- compute_memberships(x)[source]#
Computes the membership to each of the FS in the fuzzy variables.
- Parameters:
x (array) – numeric value or array. Computes the membership to each of the FS in the fuzzy variables.
- Returns:
list of floats. Membership to each of the FS in the fuzzy variables. With ordinal conditions there is one more row per extra condition, after the terms (see
ordinal_memberships()andcompound_memberships()).- Return type:
list
- domain()[source]#
Returns the domain of the fuzzy variable.
- Returns:
list of floats, or None for a categorical variable.
- Return type:
list[float]
- fuzzy_type()[source]#
Returns the fuzzy type of the domain
- Returns:
the type of the fuzzy set present in the fuzzy variable.
- Return type:
- validate(X, verbose=False)[source]#
Validates the fuzzy variable. Checks that all the fuzzy sets have the same type and domain.
A categorical variable is valid by definition: it has one crisp fuzzy set per category, so there is nothing to check. The properties below are only defined for numerical Type-1 variables, over crisp memberships along a numerical domain, and an interval or general Type-2 variable answers with one membership interval per sample instead of a single value.
- Parameters:
X – np.array. Input data to validate the fuzzy variable.
- Returns:
bool. True if the fuzzy variable is valid, False otherwise.
- Raises:
NotImplementedError – if the fuzzy variable is numerical and not Type-1.
- Return type:
bool
- __str__()[source]#
Returns the name of the fuzzy variable, its type and its parameters.
- Returns:
string.
- Return type:
str
- __getitem__(item)[source]#
Returns the corresponding fs.
- Parameters:
item – int. Index of the FS.
- Returns:
FS. The corresponding FS.
- Return type:
- __setitem__(item, elem)[source]#
Sets the corresponding fs.
- Parameters:
item (int) – int. Index of the FS.
elem (FS) – FS. The FS to set.
- __iter__()[source]#
Returns the corresponding fs.
- Parameters:
item – int. Index of the FS.
- Returns:
FS. The corresponding FS.
- Return type:
Generator[FS, None, None]
Enums#
- class ex_fuzzy.fuzzy_sets.FUZZY_SETS(*values)[source]#
Bases:
EnumEnumeration defining the types of fuzzy sets supported by the library.
This enum is used throughout the library to specify which type of fuzzy set should be created or used in operations.
Example
>>> fz_type = FUZZY_SETS.t1 >>> if fz_type == FUZZY_SETS.t1: ... print("Using Type-1 fuzzy sets")
- t1 = 'Type 1'#
Type-1 fuzzy sets with crisp membership functions.
- t2 = 'Type 2'#
Type-2 interval fuzzy sets with upper and lower membership bounds.
- gt2 = 'General Type 2'#
General Type-2 fuzzy sets with full secondary membership functions.