Fuzzy Sets#

The fuzzy_sets module provides the fundamental building blocks for fuzzy logic systems in Ex-Fuzzy.

Overview#

Fuzzy sets extend classical set theory by allowing partial membership. Instead of binary membership (in/out), fuzzy sets assign membership degrees between 0 and 1, enabling more nuanced representation of concepts.

Key Classes#

FS(name, membership_parameters, domain)

Base class for Type-1 fuzzy sets (Zadeh fuzzy sets).

gaussianFS(name, membership_parameters, domain)

Gaussian Type-1 Fuzzy Set Implementation.

gaussianIVFS(name, secondMF_lower, ...[, ...])

Gaussian Interval-Valued (Type-2) Fuzzy Set Implementation.

categoricalFS(name, category)

fuzzyVariable(name, fuzzy_sets[, units])

Fuzzy Variable Container and Management Class.

Enumerations#

FUZZY_SETS(value[, names, module, qualname, ...])

Core Classes#

Base Fuzzy Set#

class ex_fuzzy.fuzzy_sets.FS(name, membership_parameters, domain)[source]#

Bases: object

Base 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.

The base class for all fuzzy sets in Ex-Fuzzy. Provides fundamental operations and the interface that all fuzzy set types must implement.

Key Methods:

FS.membership(x)

Compute membership degrees for input values.

__init__(name, membership_parameters, domain)[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:

FUZZY_SETS

__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

__str__()[source]#

Returns the name of the fuzzy set, its type and its parameters.

Returns:

string.

Return type:

str

shape()[source]#

Returns the shape of the fuzzy set.

Returns:

string.

Return type:

str

Gaussian Fuzzy Set#

class ex_fuzzy.fuzzy_sets.gaussianFS(name, membership_parameters, domain)[source]#

Bases: FS

Gaussian 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)

Implements Gaussian (normal) membership functions. These are the most commonly used fuzzy sets due to their smooth shape and mathematical properties.

Example:

import ex_fuzzy.fuzzy_sets as fs

# Create a Gaussian fuzzy set
gaussian_set = fs.gaussianFS(
    mean=5.0,
    std=1.5,
    domain=[0, 10],
    name="Medium"
)

# Calculate membership
membership = gaussian_set.membership(4.5)
print(f"Membership of 4.5: {membership:.3f}")
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]
type()[source]#

Returns the type of the fuzzy set.

Returns:

Always returns FUZZY_SETS.t1 for Type-1 fuzzy sets

Return type:

FUZZY_SETS

shape()[source]#

Returns the shape of the fuzzy set.

Returns:

Always returns ‘gaussian’

Return type:

str

Interval-Valued Gaussian Fuzzy Set#

class ex_fuzzy.fuzzy_sets.gaussianIVFS(name, secondMF_lower, secondMF_upper, domain, lower_height=1.0)[source]#

Bases: IVFS

Gaussian 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.

Extends Gaussian fuzzy sets to handle uncertainty in the membership function itself using interval-valued membership degrees.

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
type()[source]#

Returns the type of the fuzzy set.

Returns:

Always returns FUZZY_SETS.t2 for Type-2 fuzzy sets

Return type:

FUZZY_SETS

shape()[source]#

Returns the shape of the fuzzy set.

Returns:

Always returns ‘gaussian’

Return type:

str

Categorical Fuzzy Set#

class ex_fuzzy.fuzzy_sets.categoricalFS(name, category)[source]#

Bases: FS

Handles discrete, categorical variables by mapping categories to membership degrees. Useful for non-numeric data.

__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.

type()[source]#

Returns the corresponding fuzzy set type according to FUZZY_SETS enum.

__str__()[source]#

Returns the name of the fuzzy set, its type and its parameters.

Returns:

string.

Return type:

str

shape()[source]#

Returns the shape of the fuzzy set.

Returns:

string.

Return type:

str

Fuzzy Variable#

class ex_fuzzy.fuzzy_sets.fuzzyVariable(name, fuzzy_sets, units=None)[source]#

Bases: object

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

FUZZY_SETS

Example

>>> # Create fuzzy sets for temperature
>>> low_temp = gaussianFS([15, 5], "Low", 100)
>>> medium_temp = gaussianFS([25, 5], "Medium", 100)
>>> high_temp = gaussianFS([35, 5], "High", 100)
>>>
>>> # Create fuzzy variable
>>> temp_var = fuzzyVariable("Temperature", [low_temp, medium_temp, high_temp], "°C")
>>> memberships = temp_var.membership([20, 25, 30])
>>> print(memberships.shape)  # (3, 3) - 3 inputs, 3 fuzzy sets

Note

All fuzzy sets in the variable must be of the same type (t1 or t2).

Represents a complete fuzzy variable with multiple linguistic terms (fuzzy sets). This is the main class users interact with for defining input and output variables.

Example:

import ex_fuzzy.fuzzy_sets as fs

# Create a fuzzy variable for temperature
temperature = fs.fuzzyVariable(
    domain=[0, 40],  # Celsius
    name="temperature",
    n_linguistic_vars=3  # Cold, Warm, Hot
)

# The variable automatically creates linguistic terms
print(temperature.linguistic_variable_names())
# Output: ['Cold', 'Warm', 'Hot']

# Evaluate membership for a specific value
memberships = temperature.membership(25.0)
print(f"Memberships for 25°C: {memberships}")
__init__(name, fuzzy_sets, units=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

Raises:

ValueError – If fuzzy_sets is empty or contains mixed types

Example

>>> fs1 = gaussianFS([0, 1], "Low", 10)
>>> fs2 = gaussianFS([5, 1], "High", 10)
>>> var = fuzzyVariable("Speed", [fs1, fs2], "m/s")
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.

Return type:

list

domain()[source]#

Returns the domain of the fuzzy variable.

Returns:

list of floats.

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:

FUZZY_SETS

validate(X, verbose=False)[source]#

Validates the fuzzy variable. Checks that all the fuzzy sets have the same type and domain.

Parameters:

X – np.array. Input data to validate the fuzzy variable.

Returns:

bool. True if the fuzzy variable is valid, False otherwise.

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:

FS

__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]

__len__()[source]#

Returns the number of linguistic variables.

Returns:

int. Number of linguistic variables.

Return type:

int

__call__(x)[source]#

Computes the membership to each of the FS in the fuzzy variables.

Parameters:

x (array) – numeric value or array.

Returns:

list of floats. Membership to each of the FS in the fuzzy variables.

Return type:

list

Constants and Enums#

Fuzzy Set Types#

class ex_fuzzy.fuzzy_sets.FUZZY_SETS(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Enumeration of available fuzzy set types:

  • t1: Type-1 fuzzy sets (crisp membership values)

  • t2: Type-2 fuzzy sets (fuzzy membership values)

  • gt2: General Type-2 fuzzy sets

  • it2: Interval Type-2 fuzzy sets

t1 = 'Type 1'#
t2 = 'Type 2'#
gt2 = 'General Type 2'#
temporal = 'temporal'#
temporal_t2 = 'temporal_t2'#
temporal_gt2 = 'temporal_gt2'#

Linguistic Types#

Functions#

Utility Functions#

Examples#

Basic Usage#

import ex_fuzzy.fuzzy_sets as fs
import numpy as np
import matplotlib.pyplot as plt

# Create a fuzzy variable for age
age = fs.fuzzyVariable(
    domain=[0, 100],
    name="age",
    linguistic_variable_names=["Young", "Middle-aged", "Old"]
)

# Plot the membership functions
x = np.linspace(0, 100, 1000)
plt.figure(figsize=(10, 6))

for i, term_name in enumerate(age.linguistic_variable_names()):
    y = [age[i].membership(val) for val in x]
    plt.plot(x, y, label=term_name, linewidth=2)

plt.xlabel('Age')
plt.ylabel('Membership Degree')
plt.title('Age Fuzzy Variable')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Advanced Usage#

# Create custom fuzzy sets with specific parameters
young = fs.gaussianFS(mean=20, std=10, domain=[0, 100], name="Young")
middle = fs.gaussianFS(mean=50, std=15, domain=[0, 100], name="Middle-aged")
old = fs.gaussianFS(mean=80, std=12, domain=[0, 100], name="Old")

# Create variable with custom sets
age_custom = fs.fuzzyVariable(
    domain=[0, 100],
    name="age_custom",
    fuzzy_sets=[young, middle, old]
)

# Evaluate multiple values
ages_to_test = [15, 35, 55, 75]
for age_val in ages_to_test:
    memberships = age_custom.membership(age_val)
    print(f"Age {age_val}: {dict(zip(age_custom.linguistic_variable_names(), memberships))}")

Type-2 Fuzzy Sets#

# Create Type-2 fuzzy variable for handling uncertainty
uncertain_temp = fs.fuzzyVariable(
    domain=[0, 40],
    name="uncertain_temperature",
    fuzzy_type=fs.FUZZY_SETS.t2,
    n_linguistic_vars=3
)

# Type-2 membership returns intervals
temp_value = 25.0
memberships = uncertain_temp.membership(temp_value)
print(f"Type-2 memberships for {temp_value}°C:")
for i, name in enumerate(uncertain_temp.linguistic_variable_names()):
    lower, upper = memberships[i]
    print(f"  {name}: [{lower:.3f}, {upper:.3f}]")

See Also#

  • ../user-guide/fuzzy-sets: Detailed guide on using fuzzy sets

  • ../examples/custom-fuzzy-sets: Examples of creating custom fuzzy sets

  • Evolutionary Fit Module: Using fuzzy variables in classification

  • Rules Module: Creating rules with fuzzy variables