skfuzzy

scikit-fuzzy (a.k.a. skfuzzy): Fuzzy Logic Toolbox for Python.

This package implements many useful tools and functions for computation and projects involving fuzzy logic, also known as grey logic.

Most of the functionality is actually located in subpackages, but like numpy we bring most of the core functionality into the base namespace.

skfuzzy.addval(interval1, interval2) Add intervals interval1 and interval2.
skfuzzy.arglcut(ms, lambdacut) Determines the subset of indices mi of the elements in an N-point resultant fuzzy membership sequence ms that have a grade of membership >= lambdacut.
skfuzzy.cartadd(x, y) Cartesian addition of fuzzy membership vectors using the algebraic method.
skfuzzy.cartprod(x, y) Cartesian product of two fuzzy membership vectors.
skfuzzy.centroid(x, mfx) Defuzzification using centroid (center of gravity) method.
skfuzzy.classic_relation(a, b) Determine the classic relation matrix, R, between two fuzzy sets.
skfuzzy.cmeans(data, c, m, error, maxiter[, ...]) Fuzzy c-means clustering algorithm [1].
skfuzzy.cmeans_predict(test_data, ...[, ...]) Prediction of new data in given a trained fuzzy c-means framework [1].
skfuzzy.continuous_to_discrete(a, b, ...) Converts a continuous-time system to its equivalent discrete-time version.
skfuzzy.contrast(arr[, amount, split, normalize]) General contrast booster or diffuser of normalized array-like data.
skfuzzy.dcentroid(x, mfx, x0) Defuzzification using a differential centroidal method about x0.
skfuzzy.defocus_local_means(im) Defocusing non-normalized image im using local arithmatic mean.
skfuzzy.defuzz(x, mfx, mode) Defuzzification of a membership function, returning a defuzzified value of the function at x, using various defuzzification methods.
skfuzzy.divval(interval1, interval2) Divide interval2 into interval1, by inversion and multiplication.
skfuzzy.dsigmf(x, b1, c1, b2, c2) Difference of two fuzzy sigmoid membership functions.
skfuzzy.dsw_add(x, mfx, y, mfy, n) Add two fuzzy variables together using the restricted DSW method [1].
skfuzzy.dsw_div(x, mfx, y, mfy, n) Divide one fuzzy variable by another using the restricted DSW method [1].
skfuzzy.dsw_mult(x, mfx, y, mfy, n) Multiply two fuzzy variables using the restricted DSW method [1].
skfuzzy.dsw_sub(x, mfx, y, mfy, n) Subtract a fuzzy variable from another by the restricted DSW method [1].
skfuzzy.fire1d(x[, l1, l2]) 1-D filtering using Fuzzy Inference Ruled by Else-action (FIRE) [1].
skfuzzy.fire2d(im[, l1, l2, fuzzyresolution]) 2-D filtering using Fuzzy Inference Ruled by Else-action (FIRE) [1].
skfuzzy.fuzzy_add(x, a, y, b) Add fuzzy set a to fuzzy set b.
skfuzzy.fuzzy_and(x, mfx, y, mfy) Fuzzy AND operator, a.k.a.
skfuzzy.fuzzy_compare(q) Determine the comparison matrix, c, based on the fuzzy pairwise comparison matrix, q, using Shimura’s special relativity formula.
skfuzzy.fuzzy_div(x, a, y, b) Divide fuzzy set b into fuzzy set a.
skfuzzy.fuzzy_min(x, a, y, b) Find minimum between fuzzy set a fuzzy set b.
skfuzzy.fuzzy_mult(x, a, y, b) Multiplies fuzzy set a and fuzzy set b.
skfuzzy.fuzzy_not(mfx) Fuzzy NOT operator, a.k.a.
skfuzzy.fuzzy_or(x, mfx, y, mfy) Fuzzy OR operator, a.k.a.
skfuzzy.fuzzy_similarity(ai, b[, mode]) The fuzzy similarity between set ai and observation set b.
skfuzzy.fuzzy_sub(x, a, y, b) Subtract fuzzy set b from fuzzy set a.
skfuzzy.gauss2mf(x, mean1, sigma1, mean2, sigma2) Gaussian fuzzy membership function of two combined Gaussians.
skfuzzy.gaussmf(x, mean, sigma) Gaussian fuzzy membership function.
skfuzzy.gbellmf(x, a, b, c) Generalized Bell function fuzzy membership generator.
skfuzzy.inner_product(a, b) Inner product (dot product) of two fuzzy sets.
skfuzzy.interp10(x) Utility function which conducts linear interpolation of any rank-1 array.
skfuzzy.interp_membership(x, xmf, xx) Find the degree of membership u(xx) for a given value of x = xx.
skfuzzy.interp_universe(x, xmf, y) Find interpolated universe value(s) for a given fuzzy membership value.
skfuzzy.lambda_cut(ms, lcut) The crisp (binary) lambda-cut set of the membership sequence ms with membership >= lcut.
skfuzzy.lambda_cut_boundaries(x, mfx, lambdacut) Find exact boundaries where mfx crosses lambdacut using interpolation.
skfuzzy.lambda_cut_series(x, mfx, n) Determine a series of lambda-cuts in a sweep from 0+ to 1.0 in n steps.
skfuzzy.maxmin_composition(s, r) The max-min composition t of two fuzzy relation matrices.
skfuzzy.maxprod_composition(s, r) The max-product composition t of two fuzzy relation matrices.
skfuzzy.modus_ponens(a, b, ap[, c]) Generalized modus ponens deduction to make approximate reasoning in a rules-base system.
skfuzzy.multval(interval1, interval2) Multiply intervals interval1 and interval2.
skfuzzy.nmse(known, degraded) Computes the percent normalized mean square error (NMSE %) between known and degraded arrays.
skfuzzy.outer_product(a, b) Outer product of two fuzzy sets.
skfuzzy.pad(array, pad_width[, mode]) Pads an array.
skfuzzy.partial_dmf(x, mf_name, ...) Calculate the partial derivative of a specified membership function.
skfuzzy.piecemf(x, abc) Piecewise linear membership function (particularly used in FIRE filters).
skfuzzy.pimf(x, a, b, c, d) Pi-function fuzzy membership generator.
skfuzzy.psigmf(x, b1, c1, b2, c2) Product of two sigmoid membership functions.
skfuzzy.relation_min(a, b) Determine fuzzy relation matrix R using Mamdani implication for the fuzzy antecedent a and consequent b inputs.
skfuzzy.relation_product(a, b) Determine the fuzzy relation matrix, R, using product implication for the fuzzy antecedent a and the fuzzy consequent b.
skfuzzy.scaleval(q, interval) Multiply scalar q with interval interval.
skfuzzy.sigmf(x, b, c) The basic sigmoid membership function generator.
skfuzzy.sigmoid(x, power[, split]) Intensify grayscale values in an array using a sigmoid function.
skfuzzy.smf(x, a, b) S-function fuzzy membership generator.
skfuzzy.subval(interval1, interval2) Subtract interval interval2 from interval interval1.
skfuzzy.test([doctest, verbose]) Run all unit tests.
skfuzzy.trapmf(x, abcd) Trapezoidal membership function generator.
skfuzzy.trimf(x, abc) Triangular membership function generator.
skfuzzy.view_as_blocks(arr_in, block_shape) Block view of the input n-dimensional array (using re-striding).
skfuzzy.view_as_windows(arr_in, window_shape) Rolling window view of the input n-dimensional array.
skfuzzy.zmf(x, a, b) Z-function fuzzy membership generator.

addval

skfuzzy.addval(interval1, interval2)[source]

Add intervals interval1 and interval2.

Parameters:

interval1 : 2-element iterable

First interval set.

interval2 : 2-element iterable

Second interval set.

Returns:

Z : 2-element array

Sum of interval1 and interval2, defined as:

Z = interval1 + interval2 = [a + c, b + d]

arglcut

skfuzzy.arglcut(ms, lambdacut)[source]

Determines the subset of indices mi of the elements in an N-point resultant fuzzy membership sequence ms that have a grade of membership >= lambdacut.

Parameters:

ms : 1d array

Fuzzy membership sequence.

lambdacut : float

Value used for lambda cutting.

Returns:

lidx : 1d array

Indices corresponding to the lambda-cut subset of ms.

Notes

This is a convenience function for np.nonzero(lambdacut <= ms) and only half of the indexing operation that can be more concisely accomplished via:

ms[lambdacut <= ms]

cartadd

skfuzzy.cartadd(x, y)[source]

Cartesian addition of fuzzy membership vectors using the algebraic method.

Parameters:

x : 1D array or iterable

First fuzzy membership vector, of length M.

y : 1D array or iterable

Second fuzzy membership vector, of length N.

Returns:

z : 2D array

Cartesian addition of x and y, of shape (M, N).

cartprod

skfuzzy.cartprod(x, y)[source]

Cartesian product of two fuzzy membership vectors. Uses min().

Parameters:

x : 1D array or iterable

First fuzzy membership vector, of length M.

y : 1D array or iterable

Second fuzzy membership vector, of length N.

Returns:

z : 2D array

Cartesian product of x and y, of shape (M, N).

centroid

skfuzzy.centroid(x, mfx)[source]

Defuzzification using centroid (center of gravity) method.

Parameters:

x : 1d array, length M

Independent variable

mfx : 1d array, length M

Fuzzy membership function

Returns:

u : 1d array, length M

Defuzzified result

classic_relation

skfuzzy.classic_relation(a, b)[source]

Determine the classic relation matrix, R, between two fuzzy sets.

Parameters:

a : 1D array or iterable

First fuzzy membership vector, of length M.

b : 1D array or iterable

Second fuzzy membership vector, of length N.

Returns:

R : 2D array

Classic relation matrix between a and b, shape (M, N)

Notes

The classic relation is defined as:

r = [a x b] U [(1 - a) x ones(1, N)],

where x represents a cartesian product and N is len(b).

cmeans

skfuzzy.cmeans(data, c, m, error, maxiter, init=None, seed=None)[source]

Fuzzy c-means clustering algorithm [1].

Parameters:

data : 2d array, size (S, N)

Data to be clustered. N is the number of data sets; S is the number of features within each sample vector.

c : int

Desired number of clusters or classes.

m : float

Array exponentiation applied to the membership function u_old at each iteration, where U_new = u_old ** m.

error : float

Stopping criterion; stop early if the norm of (u[p] - u[p-1]) < error.

maxiter : int

Maximum number of iterations allowed.

init : 2d array, size (S, N)

Initial fuzzy c-partitioned matrix. If none provided, algorithm is randomly initialized.

seed : int

If provided, sets random seed of init. No effect if init is provided. Mainly for debug/testing purposes.

Returns:

cntr : 2d array, size (S, c)

Cluster centers. Data for each center along each feature provided for every cluster (of the c requested clusters).

u : 2d array, (S, N)

Final fuzzy c-partitioned matrix.

u0 : 2d array, (S, N)

Initial guess at fuzzy c-partitioned matrix (either provided init or random guess used if init was not provided).

d : 2d array, (S, N)

Final Euclidian distance matrix.

jm : 1d array, length P

Objective function history.

p : int

Number of iterations run.

fpc : float

Final fuzzy partition coefficient.

Notes

The algorithm implemented is from Ross et al. [R11].

Fuzzy C-Means has a known problem with high dimensionality datasets, where the majority of cluster centers are pulled into the overall center of gravity. If you are clustering data with very high dimensionality and encounter this issue, another clustering method may be required. For more information and the theory behind this, see Winkler et al. [R12].

References

[R11](1, 2) Ross, Timothy J. Fuzzy Logic With Engineering Applications, 3rd ed. Wiley. 2010. ISBN 978-0-470-74376-8 pp 352-353, eq 10.28 - 10.35.
[R12](1, 2) Winkler, R., Klawonn, F., & Kruse, R. Fuzzy c-means in high dimensional spaces. 2012. Contemporary Theory and Pragmatic Approaches in Fuzzy Computing Utilization, 1.

cmeans_predict

skfuzzy.cmeans_predict(test_data, cntr_trained, m, error, maxiter, init=None, seed=None)[source]

Prediction of new data in given a trained fuzzy c-means framework [1].

Parameters:

test_data : 2d array, size (S, N)

New, independent data set to be predicted based on trained c-means from cmeans. N is the number of data sets; S is the number of features within each sample vector.

cntr_trained : 2d array, size (S, c)

Location of trained centers from prior training c-means.

m : float

Array exponentiation applied to the membership function u_old at each iteration, where U_new = u_old ** m.

error : float

Stopping criterion; stop early if the norm of (u[p] - u[p-1]) < error.

maxiter : int

Maximum number of iterations allowed.

init : 2d array, size (S, N)

Initial fuzzy c-partitioned matrix. If none provided, algorithm is randomly initialized.

seed : int

If provided, sets random seed of init. No effect if init is provided. Mainly for debug/testing purposes.

Returns:

u : 2d array, (S, N)

Final fuzzy c-partitioned matrix.

u0 : 2d array, (S, N)

Initial guess at fuzzy c-partitioned matrix (either provided init or random guess used if init was not provided).

d : 2d array, (S, N)

Final Euclidian distance matrix.

jm : 1d array, length P

Objective function history.

p : int

Number of iterations run.

fpc : float

Final fuzzy partition coefficient.

Notes

Ross et al. [R13] did not include a prediction algorithm to go along with fuzzy c-means. This prediction algorithm works by repeating the clustering with fixed centers, then efficiently finds the fuzzy membership at all points.

References

[R13](1, 2) Ross, Timothy J. Fuzzy Logic With Engineering Applications, 3rd ed. Wiley. 2010. ISBN 978-0-470-74376-8 pp 352-353, eq 10.28 - 10.35.

continuous_to_discrete

skfuzzy.continuous_to_discrete(a, b, sampling_rate)[source]

Converts a continuous-time system to its equivalent discrete-time version.

Parameters:

a : (N, N) array of floats

State variable coefficients describing the continuous-time system.

b : (N,) or (N, 1) array of floats

Constant coefficients describing the continuous-time system. Can be either a rank-1 array or a rank-2 array of shape (N, 1).

sampling_rate : float

Rate in Hz at which the continuous-time system is to be sampled.

Returns:

phi : (N, N) array of floats

Variable coefficients describing the discrete-time system.

gamma : (N,) or (N, 1) array of floats

Constant coefficients describing the discrete-time system. Shape of this output maintains the shape passed as b.

contrast

skfuzzy.contrast(arr, amount=0.2, split=0.5, normalize=True)[source]

General contrast booster or diffuser of normalized array-like data.

Parameters:

arr : ndarray

Input array (of floats on range [0, 1] if normalize=False). If values exist outside this range, with normalize=True the image will be normalized for calculation.

amount : float or length-2 iterable of floats

Controls the exponential contrast mechanism for values above and below split in I. If positive, the curve provides added contrast; if negative, the curve provides reduced contrast.

If provided as a lenth-2 iterable of floats, they control the regions (below, above) split separately.

split : float

Positive scalar, on range [0, 1], determining the midpoint of the exponential contrast. Default of 0.5 is reasonable for well-exposed images.

normalize : bool, default True

Controls normalization to the range [0, 1].

Returns:

focused : ndarray

Contrast adjusted, normalized, floating-point image on range [0, 1].

Notes

The result of this algorithm is like applying a Curves adjustment in the GIMP or Photoshop.

Algorithm for curves adjustment at a given pixel, x, is given by:

       | split * (x/split)^below,                        0 <= x <= split
y(x) = |
       | 1 - (1-split) * ((1-x) / (1-split))^above,   split < x <= 1.0

dcentroid

skfuzzy.dcentroid(x, mfx, x0)[source]

Defuzzification using a differential centroidal method about x0.

Parameters:

x : 1d array or iterable

Independent variable.

mfx : 1d array or iterable

Fuzzy membership function.

x0 : float

Central value to calculate differential centroid about.

Returns:

u : 1d array

Defuzzified result.

defocus_local_means

skfuzzy.defocus_local_means(im)[source]

Defocusing non-normalized image im using local arithmatic mean.

Parameters:

im : ndarray

Input image, normalization not required. NaN values unsupported.

Returns:

D : ndarray of floats, same shape as im

Defocused output image. By definition will not extend the range of im, but the result returned will be an array of floats regardless of input dtype.

Notes

Reduces ‘salt & pepper’ noise in a quantized image by taking the arithmatic mean of the 4-connected neighborhood. So the new value at X, given the 4-connected neighborhood:

    +---+
    | c |
+---+---+---+
| a | X | b |
+---+---+---+
    | d |
    +---+

is defined by the relationship:

X = 0.25 * (a + b + c + d)

defuzz

skfuzzy.defuzz(x, mfx, mode)[source]

Defuzzification of a membership function, returning a defuzzified value of the function at x, using various defuzzification methods.

Parameters:

x : 1d array or iterable, length N

Independent variable.

mfx : 1d array of iterable, length N

Fuzzy membership function.

mode : string

Controls which defuzzification method will be used. * ‘centroid’: Centroid of area * ‘bisector’: bisector of area * ‘mom’ : mean of maximum * ‘som’ : min of maximum * ‘lom’ : max of maximum

Returns:

u : float or int

Defuzzified result.

divval

skfuzzy.divval(interval1, interval2)[source]

Divide interval2 into interval1, by inversion and multiplication.

Parameters:

interval1 : 2-element iterable

First interval set.

interval2 : 2-element iterable

Second interval set.

Returns:

z : 2-element array

Interval result of interval1 / interval2.

dsigmf

skfuzzy.dsigmf(x, b1, c1, b2, c2)[source]

Difference of two fuzzy sigmoid membership functions.

Parameters:

x : 1d array

Independent variable.

b1 : float

Midpoint of first sigmoid; f1(b1) = 0.5

c1 : float

Width and sign of first sigmoid.

b2 : float

Midpoint of second sigmoid; f2(b2) = 0.5

c2 : float

Width and sign of second sigmoid.

Returns:

y : 1d array

Generated sigmoid values, defined as

y = f1 - f2 f1(x) = 1 / (1. + exp[- c1 * (x - b1)]) f2(x) = 1 / (1. + exp[- c2 * (x - b2)])

dsw_add

skfuzzy.dsw_add(x, mfx, y, mfy, n)[source]

Add two fuzzy variables together using the restricted DSW method [1].

Parameters:

x : 1d array

Universe for first fuzzy variable.

mfx : 1d array

Fuzzy membership for universe x. Must be convex.

y : 1d array

Universe for second fuzzy variable.

mfy : 1d array

Fuzzy membership for universe y. Must be convex.

n : int

Number of lambda-cuts to use; a higher number will have greater resolution toward the limit imposed by input sets x and y.

Returns:

z : 1d array

Output universe variable.

mfz : 1d array

Output fuzzy membership on universe z.

Notes

The Dong, Shah, and Wong (DSW) method requires convex fuzzy membership functions. The dsw_* functions return results similar to Matplotlib’s fuzarith function.

References

[R14]W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.

dsw_div

skfuzzy.dsw_div(x, mfx, y, mfy, n)[source]

Divide one fuzzy variable by another using the restricted DSW method [1].

Parameters:

x : 1d array

Universe for first fuzzy variable.

mfx : 1d array

Fuzzy membership for universe x. Must be convex.

y : 1d array

Universe for second fuzzy variable.

mfy : 1d array

Fuzzy membership for universe y. Must be convex.

n : int

Number of lambda-cuts to use; a higher number will have greater resolution toward the limit imposed by input sets x and y.

Returns:

z : 1d array

Output universe variable.

mfz : 1d array

Output fuzzy membership on universe z.

Notes

The Dong, Shah, and Wong (DSW) method requires convex fuzzy membership functions. The dsw_* functions return results similar to Matplotlib’s fuzarith function.

References

[R15]W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.

dsw_mult

skfuzzy.dsw_mult(x, mfx, y, mfy, n)[source]

Multiply two fuzzy variables using the restricted DSW method [1].

Parameters:

x : 1d array

Universe for first fuzzy variable.

mfx : 1d array

Fuzzy membership for universe x. Must be convex.

y : 1d array

Universe for second fuzzy variable.

mfy : 1d array

Fuzzy membership for universe y. Must be convex.

n : int

Number of lambda-cuts to use; a higher number will have greater resolution toward the limit imposed by input sets x and y.

Returns:

z : 1d array

Output universe variable.

mfz : 1d array

Output fuzzy membership on universe z.

Notes

The Dong, Shah, and Wong (DSW) method requires convex fuzzy membership functions. The dsw_* functions return results similar to Matplotlib’s fuzarith function.

References

[R16]W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.

dsw_sub

skfuzzy.dsw_sub(x, mfx, y, mfy, n)[source]

Subtract a fuzzy variable from another by the restricted DSW method [1].

Parameters:

x : 1d array

Universe for first fuzzy variable.

mfx : 1d array

Fuzzy membership for universe x. Must be convex.

y : 1d array

Universe for second fuzzy variable, which will be subtracted from x.

mfy : 1d array

Fuzzy membership for universe y. Must be convex.

n : int

Number of lambda-cuts to use; a higher number will have greater resolution toward the limit imposed by input sets x and y.

Returns:

z : 1d array

Output universe variable.

mfz : 1d array

Output fuzzy membership on universe z.

Notes

The Dong, Shah, and Wong (DSW) method requires convex fuzzy membership functions. The dsw_* functions return results similar to Matplotlib’s fuzarith function.

References

[R17]W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.

fire1d

skfuzzy.fire1d(x, l1=0, l2=1)[source]

1-D filtering using Fuzzy Inference Ruled by Else-action (FIRE) [1].

FIRE filtering is nonlinear, and is specifically designed to remove impulse (salt and pepper) noise.

Parameters:

x : 1d array or iterable

Input sequence, filtered range limited by l1 and l2.

l1 : float

Lower input range limit for x.

l2 : float

Upper input range limit for x.

Returns:

y : 1d array

FIRE filtered sequence.

Notes

Filtering occurs for l1 < |x| < l2; for |x| < l1 there is no effect.

References

[R18]Fabrizio Russo, Fuzzy Filtering of Noisy Sensor Data, IEEE Instrumentation and Measurement Technology Conference, Brussels, Belgium, June 4 - 6, 1996, pp 1281 - 1285.

fire2d

skfuzzy.fire2d(im, l1=0, l2=255, fuzzyresolution=1)[source]

2-D filtering using Fuzzy Inference Ruled by Else-action (FIRE) [1].

FIRE filtering is nonlinear, and is specifically designed to remove impulse (salt and pepper) noise.

Parameters:

I : 2d array

Input image.

l1 : float

Lower limit of filtering range.

l2 : float

Upper limit of filtering range.

fuzzyresolution : float, default = 1

Resolution of fuzzy input sequence, or spacing between [-l2+1, l2-1]. The default assumes an integer input; for floating point images a decimal value should be used approximately equal to the bit depth.

Returns:

J : 2d array

FIRE filtered image.

Notes

Filtering occurs for l1 < |x| < l2; outside this range the data is unaffected.

References

[R19]Fabrizio Russo, Fuzzy Filtering of Noisy Sensor Data, IEEE Instrumentation and Measurement Technology Conference, Brussels, Belgium, June 4 - 6, 1996, pp 1281 - 1285.

fuzzy_add

skfuzzy.fuzzy_add(x, a, y, b)[source]

Add fuzzy set a to fuzzy set b.

Parameters:

x : 1d array, length N

Universe variable for fuzzy set a.

a : 1d array, length N

Fuzzy set for universe x.

y : 1d array, length M

Universe variable for fuzzy set b.

b : 1d array, length M

Fuzzy set for universe y.

Returns:

z : 1d array

Output variable.

mfz : 1d array

Fuzzy membership set for variable z.

Notes

Uses Zadeh’s Extension Principle as described in Ross, Fuzzy Logic with Engineering Applications (2010), pp. 414, Eq. 12.17.

If these results are unexpected and your membership functions are convex, consider trying the skfuzzy.dsw_* functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.

fuzzy_and

skfuzzy.fuzzy_and(x, mfx, y, mfy)[source]

Fuzzy AND operator, a.k.a. the intersection of two fuzzy sets.

Parameters:

x : 1d array

Universe variable for fuzzy membership function mfx.

mfx : 1d array

Fuzzy membership function for universe variable x.

y : 1d array

Universe variable for fuzzy membership function mfy.

mfy : 1d array

Fuzzy membership function for universe variable y.

Returns:

z : 1d array

Universe variable for union of the two provided fuzzy sets.

mfz : 1d array

Fuzzy AND (intersection) of mfx and mfy.

fuzzy_compare

skfuzzy.fuzzy_compare(q)[source]

Determine the comparison matrix, c, based on the fuzzy pairwise comparison matrix, q, using Shimura’s special relativity formula.

Parameters:

q : 2d array, (N, N)

Fuzzy pairwise comparison matrix.

Returns:

c : 2d array, (N, N)

Comparison matrix.

fuzzy_div

skfuzzy.fuzzy_div(x, a, y, b)[source]

Divide fuzzy set b into fuzzy set a.

Parameters:

x : 1d array, length N

Universe variable for fuzzy set a.

a : 1d array, length N

Fuzzy set for universe x.

y : 1d array, length M

Universe variable for fuzzy set b.

b : 1d array, length M

Fuzzy set for universe y.

Returns:

z : 1d array

Output variable.

mfz : 1d array

Fuzzy membership set for variable z.

Notes

Uses Zadeh’s Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17.

If these results are unexpected and your membership functions are convex, consider trying the skfuzzy.dsw_* functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.

fuzzy_min

skfuzzy.fuzzy_min(x, a, y, b)[source]

Find minimum between fuzzy set a fuzzy set b.

Parameters:

x : 1d array, length N

Universe variable for fuzzy set a.

a : 1d array, length N

Fuzzy set for universe x.

y : 1d array, length M

Universe variable for fuzzy set b.

b : 1d array, length M

Fuzzy set for universe y.

Returns:

z : 1d array

Output variable.

mfz : 1d array

Fuzzy membership set for variable z.

Notes

Uses Zadeh’s Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17.

If these results are unexpected and your membership functions are convex, consider trying the skfuzzy.dsw_* functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.

fuzzy_mult

skfuzzy.fuzzy_mult(x, a, y, b)[source]

Multiplies fuzzy set a and fuzzy set b.

Parameters:

x : 1d array, length N

Universe variable for fuzzy set a.

A : 1d array, length N

Fuzzy set for universe x.

y : 1d array, length M

Universe variable for fuzzy set b.

b : 1d array, length M

Fuzzy set for universe y.

Returns:

z : 1d array

Output variable.

mfz : 1d array

Fuzzy membership set for variable z.

Notes

Uses Zadeh’s Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17.

If these results are unexpected and your membership functions are convex, consider trying the skfuzzy.dsw_* functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.

fuzzy_not

skfuzzy.fuzzy_not(mfx)[source]

Fuzzy NOT operator, a.k.a. complement of a fuzzy set.

Parameters:

mfx : 1d array

Fuzzy membership function.

Returns:

mfz : 1d array

Fuzzy NOT (complement) of mfx.

Notes

This operation does not require a universe variable, because the complement is defined for a single set. The output remains defined on the same universe.

fuzzy_or

skfuzzy.fuzzy_or(x, mfx, y, mfy)[source]

Fuzzy OR operator, a.k.a. union of two fuzzy sets.

Parameters:

x : 1d array

Universe variable for fuzzy membership function mfx.

mfx : 1d array

Fuzzy membership function for universe variable x.

y : 1d array

Universe variable for fuzzy membership function mfy.

mfy : 1d array

Fuzzy membership function for universe variable y.

Returns:

z : 1d array

Universe variable for intersection of the two provided fuzzy sets.

mfz : 1d array

Fuzzy OR (union) of mfx and mfy.

fuzzy_similarity

skfuzzy.fuzzy_similarity(ai, b, mode='min')[source]

The fuzzy similarity between set ai and observation set b.

Parameters:

ai : 1d array

Fuzzy membership function of set ai.

b : 1d array

Fuzzy membership function of set b.

mode : string

Controls the method of similarity calculation. * 'min' : Computed by array minimum operation. * 'avg' : Computed by taking the array average.

Returns:

s : float

Fuzzy similarity.

fuzzy_sub

skfuzzy.fuzzy_sub(x, a, y, b)[source]

Subtract fuzzy set b from fuzzy set a.

Parameters:

x : 1d array, length N

Universe variable for fuzzy set a.

A : 1d array, length N

Fuzzy set for universe x.

y : 1d array, length M

Universe variable for fuzzy set b.

b : 1d array, length M

Fuzzy set for universe y.

Returns:

z : 1d array

Output variable.

mfz : 1d array

Fuzzy membership set for variable z.

Notes

Uses Zadeh’s Extension Principle from Ross, Fuzzy Logic w/Engineering Applications, (2010), pp.414, Eq. 12.17.

If these results are unexpected and your membership functions are convex, consider trying the skfuzzy.dsw_* functions for fuzzy mathematics using interval arithmetic via the restricted Dong, Shah, and Wong method.

gauss2mf

skfuzzy.gauss2mf(x, mean1, sigma1, mean2, sigma2)[source]

Gaussian fuzzy membership function of two combined Gaussians.

Parameters:

x : 1d array or iterable

Independent variable.

mean1 : float

Gaussian parameter for center (mean) value of left-side Gaussian. Note mean1 <= mean2 reqiured.

sigma1 : float

Standard deviation of left Gaussian.

mean2 : float

Gaussian parameter for center (mean) value of right-side Gaussian. Note mean2 >= mean1 required.

sigma2 : float

Standard deviation of right Gaussian.

Returns:

y : 1d array

Membership function with left side up to mean1 defined by the first Gaussian, and the right side above mean2 defined by the second. In the range mean1 <= x <= mean2 the function has value = 1.

gaussmf

skfuzzy.gaussmf(x, mean, sigma)[source]

Gaussian fuzzy membership function.

Parameters:

x : 1d array or iterable

Independent variable.

mean : float

Gaussian parameter for center (mean) value.

sigma : float

Gaussian parameter for standard deviation.

Returns:

y : 1d array

Gaussian membership function for x

gbellmf

skfuzzy.gbellmf(x, a, b, c)[source]

Generalized Bell function fuzzy membership generator.

Parameters:

x : 1d array

Independent variable.

a : float

Bell function parameter controlling width. See Note for definition.

b : float

Bell function parameter controlling center. See Note for definition.

c : float

Bell function parameter controlling slope. See Note for definition.

Returns:

y : 1d array

Generalized Bell fuzzy membership function.

Notes

Definition of Generalized Bell function is:

y(x) = 1 / (1 + abs([x - c] / a) ** [2 * b])

inner_product

skfuzzy.inner_product(a, b)[source]

Inner product (dot product) of two fuzzy sets.

Parameters:

a : 1d array or iterable

Fuzzy membership function.

b : 1d array or iterable

Fuzzy membership function.

Returns:

y : float

Fuzzy inner product value, on range [0, 1]

interp10

skfuzzy.interp10(x)[source]

Utility function which conducts linear interpolation of any rank-1 array. Result will have 10x resolution.

Parameters:

x : 1d array, length N

Input array to be interpolated.

Returns:

y : 1d array, length 10 * N + 1

Linearly interpolated output.

interp_membership

skfuzzy.interp_membership(x, xmf, xx)[source]

Find the degree of membership u(xx) for a given value of x = xx.

Parameters:

x : 1d array

Independent discrete variable vector.

xmf : 1d array

Fuzzy membership function for x. Same length as x.

xx : float

Discrete singleton value on universe x.

Returns:

xxmf : float

Membership function value at xx, u(xx).

Notes

For use in Fuzzy Logic, where an interpolated discrete membership function u(x) for discrete values of x on the universe of x is given. Then, consider a new value x = xx, which does not correspond to any discrete values of x. This function computes the membership value u(xx) corresponding to the value xx using linear interpolation.

interp_universe

skfuzzy.interp_universe(x, xmf, y)[source]

Find interpolated universe value(s) for a given fuzzy membership value.

Parameters:

x : 1d array

Independent discrete variable vector.

xmf : 1d array

Fuzzy membership function for x. Same length as x.

y : float

Specific fuzzy membership value.

Returns:

xx : list

List of discrete singleton values on universe x whose membership function value is y, u(xx[i])==y. If there are not points xx[i] such that u(xx[i])==y it returns an empty list.

Notes

For use in Fuzzy Logic, where a membership function level y is given. Consider there is some value (or set of values) xx for which u(xx) == y is true, though xx may not correspond to any discrete values on x. This function computes the value (or values) of xx such that u(xx) == y using linear interpolation.

lambda_cut

skfuzzy.lambda_cut(ms, lcut)[source]

The crisp (binary) lambda-cut set of the membership sequence ms with membership >= lcut.

Parameters:

ms : 1d array

Fuzzy membership set.

lcut : float

Value used for lambda-cut, on range [0, 1.0].

Returns:

mlambda : 1d array

Lambda-cut set of ms: ones if ms[i] >= lcut, zeros otherwise.

lambda_cut_boundaries

skfuzzy.lambda_cut_boundaries(x, mfx, lambdacut)[source]

Find exact boundaries where mfx crosses lambdacut using interpolation.

Parameters:

x : 1d array, length N

Universe variable

mfx : 1d array, length N

Fuzzy membership function

lambdacut : float

Floating point value on range [0, 1].

Returns:

boundaries : 1d array

Floating point values of x where mfx crosses lambdacut. Calculated using linear interpolation.

Notes

The values returned by this function can be thought of as intersections between a hypothetical horizontal line at lambdacut and the membership function mfx. This function assumes the end values of mfx continue on forever in positive and negative directions. This means there will NOT be crossings found exactly at the bounds of x unless the value of mfx at the boundary is exactly lambdacut.

lambda_cut_series

skfuzzy.lambda_cut_series(x, mfx, n)[source]

Determine a series of lambda-cuts in a sweep from 0+ to 1.0 in n steps.

Parameters:

x : 1d array

Universe function for fuzzy membership function mfx.

mfx : 1d array

Fuzzy membership function for x.

n : int

Number of steps.

Returns:

z : 2d array, (n, 3)

Lambda cut intevals.

maxmin_composition

skfuzzy.maxmin_composition(s, r)[source]

The max-min composition t of two fuzzy relation matrices.

Parameters:

s : 2d array, (M, N)

Fuzzy relation matrix #1.

r : 2d array, (N, P)

Fuzzy relation matrix #2.

Returns:

T ; 2d array, (M, P) :

Max-min composition, defined by T = s o r.

maxprod_composition

skfuzzy.maxprod_composition(s, r)[source]

The max-product composition t of two fuzzy relation matrices.

Parameters:

s : 2d array, (M, N)

Fuzzy relation matrix #1.

r : 2d array, (N, P)

Fuzzy relation matrix #2.

Returns:

t : 2d array, (M, P)

Max-product composition matrix.

modus_ponens

skfuzzy.modus_ponens(a, b, ap, c=None)[source]

Generalized modus ponens deduction to make approximate reasoning in a rules-base system.

Parameters:

a : 1d array

Fuzzy set a on universe x

b : 1d array

Fuzzy set b on universe y

ap : 1d array

New fuzzy fact a’ (a prime, not transpose)

c : 1d array, OPTIONAL

Keyword argument representing fuzzy set c on universe y. Default = None, which will use np.ones() instead.

Returns:

R : 2d array

Full fuzzy relation.

bp : 1d array

Fuzzy conclusion b’ (b prime)

multval

skfuzzy.multval(interval1, interval2)[source]

Multiply intervals interval1 and interval2.

Parameters:

interval1 : 1d array, length 2

First interval.

interval2 : 1d array, length 2

Second interval.

Returns:

z : 1d array, length 2

Interval resulting from multiplication of interval1 and interval2.

nmse

skfuzzy.nmse(known, degraded)[source]

Computes the percent normalized mean square error (NMSE %) between known and degraded arrays.

Parameters:

known : ndarray

Known array of arbitrary size and shape. Must be convertible to float.

degraded : ndarray, same shape as known

Degraded version of known, must have same shape as known.

Returns:

nmse : float

Calculated NMSE, as a percentage.

Notes

Usually used to compare a true/original image to a degraded version. For this calculation, which image is provided as true and which degraded does not matter.

outer_product

skfuzzy.outer_product(a, b)[source]

Outer product of two fuzzy sets.

Parameters:

a : 1d array or iterable

Fuzzy membership function.

b : 1d array or iterable

Fuzzy membership function.

Returns:

y : float

Fuzzy outer product value, on range [0, 1]

pad

skfuzzy.pad(array, pad_width, mode=None, **kwargs)[source]

Pads an array.

Parameters:

array : array_like of rank N

Input array

pad_width : {sequence, array_like, int}

Number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

mode : str or function

One of the following string values or a user supplied function.

‘constant’

Pads with a constant value.

‘edge’

Pads with the edge values of array.

‘linear_ramp’

Pads with the linear ramp between end_value and the array edge value.

‘maximum’

Pads with the maximum value of all or part of the vector along each axis.

‘mean’

Pads with the mean value of all or part of the vector along each axis.

‘median’

Pads with the median value of all or part of the vector along each axis.

‘minimum’

Pads with the minimum value of all or part of the vector along each axis.

‘reflect’

Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

‘symmetric’

Pads with the reflection of the vector mirrored along the edge of the array.

‘wrap’

Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.

<function>

Padding function, see Notes.

stat_length : sequence or int, optional

Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value.

((before_1, after_1), ... (before_N, after_N)) unique statistic lengths for each axis.

((before, after),) yields same before and after statistic lengths for each axis.

(stat_length,) or int is a shortcut for before = after = statistic length for all axes.

Default is None, to use the entire axis.

constant_values : sequence or int, optional

Used in ‘constant’. The values to set the padded values for each axis.

((before_1, after_1), ... (before_N, after_N)) unique pad constants for each axis.

((before, after),) yields same before and after constants for each axis.

(constant,) or int is a shortcut for before = after = constant for all axes.

Default is 0.

end_values : sequence or int, optional

Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded array.

((before_1, after_1), ... (before_N, after_N)) unique end values for each axis.

((before, after),) yields same before and after end values for each axis.

(constant,) or int is a shortcut for before = after = end value for all axes.

Default is 0.

reflect_type : {‘even’, ‘odd’}, optional

Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extented part of the array is created by subtracting the reflected values from two times the edge value.

Returns:

pad : ndarray

Padded array of rank equal to array with shape increased according to pad_width.

Notes

This function exists in NumPy >= 1.7.0, but is included in scikit-fuzzy for backwards compatibility with earlier versions.

For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis.

The padding function, if used, should return a rank 1 array equal in length to the vector argument with padded values replaced. It has the following signature:

padding_func(vector, iaxis_pad_width, iaxis, **kwargs)

where

vector : ndarray
A rank 1 array already padded with zeros. Padded values are vector[:pad_tuple[0]] and vector[-pad_tuple[1]:].
iaxis_pad_width : tuple
A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector.
iaxis : int
The axis currently being calculated.
kwargs : misc
Any keyword arguments the function requires.

Examples

>>> a = [1, 2, 3, 4, 5]
>>> fuzz.pad(a, (2,3), 'constant', constant_values=(4, 6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])
>>> fuzz.pad(a, (2, 3), 'edge')
array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5])
>>> fuzz.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])
>>> fuzz.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
>>> fuzz.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> fuzz.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> a = [[1, 2], [3, 4]]
>>> fuzz.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])
>>> a = [1, 2, 3, 4, 5]
>>> fuzz.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
>>> fuzz.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])
>>> fuzz.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
>>> fuzz.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
>>> fuzz.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
>>> def padwithtens(vector, pad_width, iaxis, kwargs):
...     vector[:pad_width[0]] = 10
...     vector[-pad_width[1]:] = 10
...     return vector
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> fuzz.pad(a, 2, padwithtens)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])

partial_dmf

skfuzzy.partial_dmf(x, mf_name, mf_parameter_dict, partial_parameter)[source]

Calculate the partial derivative of a specified membership function.

Parameters:

x : float

input variable.

mf_name : string

Membership function name as a string. The following are supported: * 'gaussmf' : parameters 'sigma' or 'mean' * 'gbellmf' : parameters 'a', 'b', or 'c' * 'sigmf' : parameters 'b' or 'c'

mf_parameter_dict : dict

A dictionary of {param : key-value, ...} pairs for a particular membership function as defined above.

partial_parameter : string

Name of the parameter against which we take the partial derivative.

Returns:

d : float

Partial derivative of the membership function with respect to the chosen parameter, at input point x.

Notes

Partial derivatives of fuzzy membership functions are only meaningful for continuous functions. Triangular, trapezoidal designs have no partial derivatives to calculate. The following

piecemf

skfuzzy.piecemf(x, abc)[source]

Piecewise linear membership function (particularly used in FIRE filters).

Parameters:

x : 1d array

Independent variable vector.

abc : 1d array, length 3

Defines the piecewise function. Important: if abc = [a, b, c] then a <= b <= c is REQUIRED!

Returns:

y : 1d array

Piecewise fuzzy membership function for x.

Notes

Piecewise definition:
y = 0, min(x) <= x <= a y = b(x - a)/c(b - a), a <= x <= b y = x/c, b <= x <= c

pimf

skfuzzy.pimf(x, a, b, c, d)[source]

Pi-function fuzzy membership generator.

Parameters:

x : 1d array

Independent variable.

a : float

Left ‘foot’, where the function begins to climb from zero.

b : float

Left ‘ceiling’, where the function levels off at 1.

c : float

Right ‘ceiling’, where the function begins falling from 1.

d : float

Right ‘foot’, where the function reattains zero.

Returns:

y : 1d array

Pi-function.

Notes

This is equivalently a product of smf and zmf.

psigmf

skfuzzy.psigmf(x, b1, c1, b2, c2)[source]

Product of two sigmoid membership functions.

Parameters:

x : 1d array

Data vector for independent variable.

b1 : float

Offset or bias for the first sigmoid. This is the center value of the sigmoid, where it equals 1/2.

c1 : float

Controls ‘width’ of the first sigmoidal region about b1 (magnitude), and also which side of the function is open (sign). A positive value of c1 means the left side approaches zero while the right side approaches one; a negative value of c1 means the opposite.

b2 : float

Offset or bias for the second sigmoid. This is the center value of the sigmoid, where it equals 1/2.

c2 : float

Controls ‘width’ of the second sigmoidal region about b2 (magnitude), and also which side of the function is open (sign). A positive value of c2 means the left side approaches zero while the right side approaches one; a negative value of c2 means the opposite.

Returns:

y : 1d array

Generated sigmoid values, defined as

y = f1(x) * f2(x)

f1(x) = 1 / (1. + exp[- c1 * (x - b1)]) f2(x) = 1 / (1. + exp[- c2 * (x - b2)])

Notes

For a smoothed rect-like function, c2 < 0 < c1. For its inverse (zero in middle, one at edges) c1 < 0 < c2.

relation_min

skfuzzy.relation_min(a, b)[source]

Determine fuzzy relation matrix R using Mamdani implication for the fuzzy antecedent a and consequent b inputs.

Parameters:

a : 1d array

Fuzzy antecedent variable of length M.

b : 1d array

Fuzzy consequent variable of length N.

Returns:

R : 2d array

Fuzzy relation between a and b, of shape (M, N).

relation_product

skfuzzy.relation_product(a, b)[source]

Determine the fuzzy relation matrix, R, using product implication for the fuzzy antecedent a and the fuzzy consequent b.

Parameters:

a : 1d array

Fuzzy antecedent variable of length M.

b : 1d array

Fuzzy consequent variable of length N.

Returns:

R : 2d array

Fuzzy relation between a and b, of shape (M, N).

scaleval

skfuzzy.scaleval(q, interval)[source]

Multiply scalar q with interval interval.

Parameters:

q : float

Scalar to multiply interval with.

interval : 1d array, length 2

Interval. Must have exactly two elements.

Returns:

z : 1d array, length 2

New interval; z = q x interval.

sigmf

skfuzzy.sigmf(x, b, c)[source]

The basic sigmoid membership function generator.

Parameters:

x : 1d array

Data vector for independent variable.

b : float

Offset or bias. This is the center value of the sigmoid, where it equals 1/2.

c : float

Controls ‘width’ of the sigmoidal region about b (magnitude); also which side of the function is open (sign). A positive value of a means the left side approaches 0.0 while the right side approaches 1.; a negative value of c means the opposite.

Returns:

y : 1d array

Generated sigmoid values, defined as y = 1 / (1. + exp[- c * (x - b)])

Notes

These are the same values, provided separately and in the opposite order compared to the publicly available MathWorks’ Fuzzy Logic Toolbox documentation. Pay close attention to above docstring!

sigmoid

skfuzzy.sigmoid(x, power, split=0.5)[source]

Intensify grayscale values in an array using a sigmoid function.

Parameters:

x : ndarray

Input vector or image array. Should be pre-normalized to range [0, 1]

p : float

Power of the intensification (p > 0). Experiment with small, decimal values and increase as necessary.

split : float

Threshold for intensification. Values above split will be intensified, while values below split will be deintensified. Note range for split is (0, 1). Default of 0.5 is reasonable for many well-exposed images.

Returns:

y : ndarray, same size as x

Output vector or image with contrast adjusted.

Notes

The sigmoid used herein is defined as:

y = 1 / (1 + exp(- exp(- power * (x-split))))

smf

skfuzzy.smf(x, a, b)[source]

S-function fuzzy membership generator.

Parameters:

x : 1d array

Independent variable.

a : float

‘foot’, where the function begins to climb from zero.

b : float

‘ceiling’, where the function levels off at 1.

Returns:

y : 1d array

S-function.

Notes

Named such because of its S-like shape.

subval

skfuzzy.subval(interval1, interval2)[source]

Subtract interval interval2 from interval interval1.

Parameters:

interval1 : 1d array, length 2

First interval.

interval2 : 1d array, length 2

Second interval.

Returns:

Z : 1d array, length 2

Resultant subtracted interval.

test

skfuzzy.test(doctest=False, verbose=False)

Run all unit tests.

trapmf

skfuzzy.trapmf(x, abcd)[source]

Trapezoidal membership function generator.

Parameters:

x : 1d array

Independent variable.

abcd : 1d array, length 4

Four-element vector. Ensure a <= b <= c <= d.

Returns:

y : 1d array

Trapezoidal membership function.

trimf

skfuzzy.trimf(x, abc)[source]

Triangular membership function generator.

Parameters:

x : 1d array

Independent variable.

abc : 1d array, length 3

Three-element vector controlling shape of triangular function. Requires a <= b <= c.

Returns:

y : 1d array

Triangular membership function.

view_as_blocks

skfuzzy.view_as_blocks(arr_in, block_shape)[source]

Block view of the input n-dimensional array (using re-striding).

Blocks are non-overlapping views of the input array.

Parameters:

arr_in: ndarray :

The n-dimensional input array.

block_shape: tuple :

The shape of the block. Each dimension must divide evenly into the corresponding dimensions of arr_in.

Returns:

arr_out: ndarray :

Block view of the input array.

Examples

>>> import numpy as np
>>> from skfuzzy import view_as_blocks
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> B = view_as_blocks(A, block_shape=(2, 2))
>>> B[0, 0]
array([[0, 1],
       [4, 5]])
>>> B[0, 1]
array([[2, 3],
       [6, 7]])
>>> B[1, 0, 1, 1]
13
>>> A = np.arange(4*4*6).reshape(4,4,6)
>>> A  
array([[[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11],
        [12, 13, 14, 15, 16, 17],
        [18, 19, 20, 21, 22, 23]],
       [[24, 25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34, 35],
        [36, 37, 38, 39, 40, 41],
        [42, 43, 44, 45, 46, 47]],
       [[48, 49, 50, 51, 52, 53],
        [54, 55, 56, 57, 58, 59],
        [60, 61, 62, 63, 64, 65],
        [66, 67, 68, 69, 70, 71]],
       [[72, 73, 74, 75, 76, 77],
        [78, 79, 80, 81, 82, 83],
        [84, 85, 86, 87, 88, 89],
        [90, 91, 92, 93, 94, 95]]])
>>> B = view_as_blocks(A, block_shape=(1, 2, 2))
>>> B.shape
(4, 2, 3, 1, 2, 2)
>>> B[2:, 0, 2]  
array([[[[52, 53],
         [58, 59]]],
       [[[76, 77],
         [82, 83]]]])

view_as_windows

skfuzzy.view_as_windows(arr_in, window_shape)[source]

Rolling window view of the input n-dimensional array.

Windows are overlapping views of the input array, with adjacent windows shifted by a single row or column (or an index of a higher dimension).

Parameters:

arr_in: ndarray :

The n-dimensional input array.

window_shape: tuple :

Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [R20]) of the rolling window view.

Returns:

arr_out: ndarray :

(rolling) window view of the input array.

Notes

One should be very careful with rolling views when it comes to memory usage. Indeed, although a ‘view’ has the same memory footprint as its base array, the actual array that emerges when this ‘view’ is used in a computation is generally a (much) larger array than the original, especially for 2-dimensional arrays and above.

For example, let us consider a 3 dimensional array of size (100, 100, 100) of float64. This array takes about 8*100**3 Bytes for storage which is just 8 MB. If one decides to build a rolling view on this array with a window of (3, 3, 3) the hypothetical size of the rolling view (if one was to reshape the view for example) would be 8*(100-3+1)**3*3**3 which is about 203 MB! The scaling becomes even worse as the dimension of the input array becomes larger.

References

[R20](1, 2) http://en.wikipedia.org/wiki/Hyperrectangle

Examples

>>> import numpy as np
>>> from skfuzzy import view_as_windows
>>> A = np.arange(4*4).reshape(4,4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> window_shape = (2, 2)
>>> B = view_as_windows(A, window_shape)
>>> B[0, 0]
array([[0, 1],
       [4, 5]])
>>> B[0, 1]
array([[1, 2],
       [5, 6]])
>>> A = np.arange(10)
>>> A
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(8, 3)
>>> B
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
>>> A = np.arange(5*4).reshape(5, 4)
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> window_shape = (4, 3)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(2, 2, 4, 3)
>>> B  
array([[[[ 0,  1,  2],
         [ 4,  5,  6],
         [ 8,  9, 10],
         [12, 13, 14]],
        [[ 1,  2,  3],
         [ 5,  6,  7],
         [ 9, 10, 11],
         [13, 14, 15]]],
       [[[ 4,  5,  6],
         [ 8,  9, 10],
         [12, 13, 14],
         [16, 17, 18]],
        [[ 5,  6,  7],
         [ 9, 10, 11],
         [13, 14, 15],
         [17, 18, 19]]]])

zmf

skfuzzy.zmf(x, a, b)[source]

Z-function fuzzy membership generator.

Parameters:

x : 1d array

Independent variable.

a : float

‘ceiling’, where the function begins falling from 1.

b : float

‘foot’, where the function reattains zero.

Returns:

y : 1d array

Z-function.

Notes

Named such because of its Z-like shape.