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.
>>> import skfuzzy as fuzz
skfuzzy.
addval
(interval1, interval2)[source]¶Add intervals interval1 and interval2.
First interval set.
Second interval set.
Sum of interval1 and interval2, defined as:
Z = interval1 + interval2 = [a + c, b + d]
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.
Fuzzy membership sequence.
Value used for lambda cutting.
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]
skfuzzy.
cartadd
(x, y)[source]¶Cartesian addition of fuzzy membership vectors using the algebraic method.
First fuzzy membership vector, of length M.
Second fuzzy membership vector, of length N.
Cartesian addition of x
and y
, of shape (M, N).
skfuzzy.
cartprod
(x, y)[source]¶Cartesian product of two fuzzy membership vectors. Uses min()
.
First fuzzy membership vector, of length M.
Second fuzzy membership vector, of length N.
Cartesian product of x
and y
, of shape (M, N).
skfuzzy.
centroid
(x, mfx)[source]¶Defuzzification using centroid (center of gravity) method.
Independent variable
Fuzzy membership function
Defuzzified result
See also
skfuzzy.defuzzify.defuzz
, skfuzzy.defuzzify.dcentroid
skfuzzy.
classic_relation
(a, b)[source]¶Determine the classic relation matrix, R
, between two fuzzy sets.
First fuzzy membership vector, of length M.
Second fuzzy membership vector, of length N.
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
).
skfuzzy.
cmeans
(data, c, m, error, maxiter, metric='euclidean', init=None, seed=None)[source]¶Fuzzy c-means clustering algorithm [1].
Data to be clustered. N is the number of data sets; S is the number of features within each sample vector.
Desired number of clusters or classes.
Array exponentiation applied to the membership function u_old at each iteration, where U_new = u_old ** m.
Stopping criterion; stop early if the norm of (u[p] - u[p-1]) < error.
Maximum number of iterations allowed.
By default is set to euclidean. Passes any option accepted by
scipy.spatial.distance.cdist
.
Initial fuzzy c-partitioned matrix. If none provided, algorithm is randomly initialized.
If provided, sets random seed of init. No effect if init is provided. Mainly for debug/testing purposes.
Cluster centers. Data for each center along each feature provided for every cluster (of the c requested clusters).
Final fuzzy c-partitioned matrix.
Initial guess at fuzzy c-partitioned matrix (either provided init or random guess used if init was not provided).
Final Euclidian distance matrix.
Objective function history.
Number of iterations run.
Final fuzzy partition coefficient.
Notes
The algorithm implemented is from Ross et al. [1].
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. [2].
References
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.
Winkler, R., Klawonn, F., & Kruse, R. Fuzzy c-means in high dimensional spaces. 2012. Contemporary Theory and Pragmatic Approaches in Fuzzy Computing Utilization, 1.
skfuzzy.
cmeans_predict
(test_data, cntr_trained, m, error, maxiter, metric='euclidean', init=None, seed=None)[source]¶Prediction of new data in given a trained fuzzy c-means framework [1].
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.
Location of trained centers from prior training c-means.
Array exponentiation applied to the membership function u_old at each iteration, where U_new = u_old ** m.
Stopping criterion; stop early if the norm of (u[p] - u[p-1]) < error.
Maximum number of iterations allowed.
By default is set to euclidean. Passes any option accepted by
scipy.spatial.distance.cdist
.
Initial fuzzy c-partitioned matrix. If none provided, algorithm is randomly initialized.
If provided, sets random seed of init. No effect if init is provided. Mainly for debug/testing purposes.
Final fuzzy c-partitioned matrix.
Initial guess at fuzzy c-partitioned matrix (either provided init or random guess used if init was not provided).
Final Euclidian distance matrix.
Objective function history.
Number of iterations run.
Final fuzzy partition coefficient.
Notes
Ross et al. [1] 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
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.
skfuzzy.
continuous_to_discrete
(a, b, sampling_rate)[source]¶Converts a continuous-time system to its equivalent discrete-time version.
State variable coefficients describing the continuous-time system.
Constant coefficients describing the continuous-time system. Can be either a rank-1 array or a rank-2 array of shape (N, 1).
Rate in Hz at which the continuous-time system is to be sampled.
Variable coefficients describing the discrete-time system.
Constant coefficients describing the discrete-time system. Shape of this output maintains the shape passed as b.
skfuzzy.
contrast
(arr, amount=0.2, split=0.5, normalize=True)[source]¶General contrast booster or diffuser of normalized array-like data.
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.
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.
Positive scalar, on range [0, 1], determining the midpoint of the exponential contrast. Default of 0.5 is reasonable for well-exposed images.
Controls normalization to the range [0, 1].
Contrast adjusted, normalized, floating-point image on range [0, 1].
See also
skfuzzy.fuzzymath.sigmoid
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
skfuzzy.
dcentroid
(x, mfx, x0)[source]¶Defuzzification using a differential centroidal method about x0.
Independent variable.
Fuzzy membership function.
Central value to calculate differential centroid about.
Defuzzified result.
See also
skfuzzy.defuzzify.defuzz
, skfuzzy.defuzzify.centroid
skfuzzy.
defocus_local_means
(im)[source]¶Defocusing non-normalized image im
using local arithmatic mean.
Input image, normalization not required. NaN values unsupported.
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)
skfuzzy.
defuzz
(x, mfx, mode)[source]¶Defuzzification of a membership function, returning a defuzzified value of the function at x, using various defuzzification methods.
Independent variable.
Fuzzy membership function.
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
Defuzzified result.
membership function arrays are not equal.
See also
skfuzzy.defuzzify.centroid
, skfuzzy.defuzzify.dcentroid
skfuzzy.
divval
(interval1, interval2)[source]¶Divide interval2
into interval1
, by inversion and multiplication.
First interval set.
Second interval set.
Interval result of interval1 / interval2.
skfuzzy.
dsigmf
(x, b1, c1, b2, c2)[source]¶Difference of two fuzzy sigmoid membership functions.
Independent variable.
Midpoint of first sigmoid; f1(b1) = 0.5
Width and sign of first sigmoid.
Midpoint of second sigmoid; f2(b2) = 0.5
Width and sign of second sigmoid.
y = f1 - f2 f1(x) = 1 / (1. + exp[- c1 * (x - b1)]) f2(x) = 1 / (1. + exp[- c2 * (x - b2)])
skfuzzy.
dsw_add
(x, mfx, y, mfy, n)[source]¶Add two fuzzy variables together using the restricted DSW method [1].
Universe for first fuzzy variable.
Fuzzy membership for universe x
. Must be convex.
Universe for second fuzzy variable.
Fuzzy membership for universe y
. Must be convex.
Number of lambda-cuts to use; a higher number will have greater
resolution toward the limit imposed by input sets x
and y
.
Output universe variable.
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
W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.
skfuzzy.
dsw_div
(x, mfx, y, mfy, n)[source]¶Divide one fuzzy variable by another using the restricted DSW method [1].
Universe for first fuzzy variable.
Fuzzy membership for universe x
. Must be convex.
Universe for second fuzzy variable.
Fuzzy membership for universe y
. Must be convex.
Number of lambda-cuts to use; a higher number will have greater
resolution toward the limit imposed by input sets x
and y
.
Output universe variable.
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
W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.
skfuzzy.
dsw_mult
(x, mfx, y, mfy, n)[source]¶Multiply two fuzzy variables using the restricted DSW method [1].
Universe for first fuzzy variable.
Fuzzy membership for universe x
. Must be convex.
Universe for second fuzzy variable.
Fuzzy membership for universe y
. Must be convex.
Number of lambda-cuts to use; a higher number will have greater
resolution toward the limit imposed by input sets x
and y
.
Output universe variable.
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
W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.
skfuzzy.
dsw_sub
(x, mfx, y, mfy, n)[source]¶Subtract a fuzzy variable from another by the restricted DSW method [1].
Universe for first fuzzy variable.
Fuzzy membership for universe x
. Must be convex.
Universe for second fuzzy variable, which will be subtracted from
x
.
Fuzzy membership for universe y
. Must be convex.
Number of lambda-cuts to use; a higher number will have greater
resolution toward the limit imposed by input sets x
and y
.
Output universe variable.
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
W. Dong and H. Shah and F. Wong, Fuzzy computations in risk and decision analysis, Civ Eng Syst, 2, 1985, pp 201-208.
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.
Input sequence, filtered range limited by l1
and l2
.
Lower input range limit for x
.
Upper input range limit for x
.
FIRE filtered sequence.
Notes
Filtering occurs for l1 < |x| < l2
; for |x| < l1
there is no
effect.
References
Fabrizio Russo, Fuzzy Filtering of Noisy Sensor Data, IEEE Instrumentation and Measurement Technology Conference, Brussels, Belgium, June 4 - 6, 1996, pp 1281 - 1285.
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.
Input image.
Lower limit of filtering range.
Upper limit of filtering range.
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.
FIRE filtered image.
Notes
Filtering occurs for l1 < |x| < l2
; outside this range the data is
unaffected.
References
Fabrizio Russo, Fuzzy Filtering of Noisy Sensor Data, IEEE Instrumentation and Measurement Technology Conference, Brussels, Belgium, June 4 - 6, 1996, pp 1281 - 1285.
skfuzzy.
fuzzy_add
(x, a, y, b)[source]¶Add fuzzy set a
to fuzzy set b
.
Universe variable for fuzzy set a
.
Fuzzy set for universe x
.
Universe variable for fuzzy set b
.
Fuzzy set for universe y
.
Output variable.
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.
skfuzzy.
fuzzy_and
(x, mfx, y, mfy)[source]¶Fuzzy AND operator, a.k.a. the intersection of two fuzzy sets.
Universe variable for fuzzy membership function mfx.
Fuzzy membership function for universe variable x.
Universe variable for fuzzy membership function mfy.
Fuzzy membership function for universe variable y.
Universe variable for union of the two provided fuzzy sets.
Fuzzy AND (intersection) of mfx and mfy.
skfuzzy.
fuzzy_compare
(q)[source]¶Determine the comparison matrix, c
, based on the fuzzy pairwise
comparison matrix, q
, using Shimura’s special relativity formula.
Fuzzy pairwise comparison matrix.
Comparison matrix.
skfuzzy.
fuzzy_div
(x, a, y, b)[source]¶Divide fuzzy set b
into fuzzy set a
.
Universe variable for fuzzy set a
.
Fuzzy set for universe x
.
Universe variable for fuzzy set b
.
Fuzzy set for universe y
.
Output variable.
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.
skfuzzy.
fuzzy_min
(x, a, y, b)[source]¶Find minimum between fuzzy set a
fuzzy set b
.
Universe variable for fuzzy set a
.
Fuzzy set for universe x
.
Universe variable for fuzzy set b
.
Fuzzy set for universe y
.
Output variable.
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.
skfuzzy.
fuzzy_mult
(x, a, y, b)[source]¶Multiplies fuzzy set a
and fuzzy set b
.
Universe variable for fuzzy set a
.
Fuzzy set for universe x
.
Universe variable for fuzzy set b
.
Fuzzy set for universe y
.
Output variable.
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.
skfuzzy.
fuzzy_not
(mfx)[source]¶Fuzzy NOT operator, a.k.a. complement of a fuzzy set.
Fuzzy membership function.
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.
skfuzzy.
fuzzy_or
(x, mfx, y, mfy)[source]¶Fuzzy OR operator, a.k.a. union of two fuzzy sets.
Universe variable for fuzzy membership function mfx.
Fuzzy membership function for universe variable x.
Universe variable for fuzzy membership function mfy.
Fuzzy membership function for universe variable y.
Universe variable for intersection of the two provided fuzzy sets.
Fuzzy OR (union) of mfx and mfy.
skfuzzy.
fuzzy_similarity
(ai, b, mode='min')[source]¶The fuzzy similarity between set ai
and observation set b
.
Fuzzy membership function of set ai
.
Fuzzy membership function of set b
.
Controls the method of similarity calculation.
* 'min'
: Computed by array minimum operation.
* 'avg'
: Computed by taking the array average.
Fuzzy similarity.
skfuzzy.
fuzzy_sub
(x, a, y, b)[source]¶Subtract fuzzy set b
from fuzzy set a
.
Universe variable for fuzzy set a
.
Fuzzy set for universe x
.
Universe variable for fuzzy set b
.
Fuzzy set for universe y
.
Output variable.
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.
skfuzzy.
gauss2mf
(x, mean1, sigma1, mean2, sigma2)[source]¶Gaussian fuzzy membership function of two combined Gaussians.
Independent variable.
Gaussian parameter for center (mean) value of left-side Gaussian. Note mean1 <= mean2 reqiured.
Standard deviation of left Gaussian.
Gaussian parameter for center (mean) value of right-side Gaussian. Note mean2 >= mean1 required.
Standard deviation of right Gaussian.
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.
skfuzzy.
gaussmf
(x, mean, sigma)[source]¶Gaussian fuzzy membership function.
Independent variable.
Gaussian parameter for center (mean) value.
Gaussian parameter for standard deviation.
Gaussian membership function for x.
skfuzzy.
gbellmf
(x, a, b, c)[source]¶Generalized Bell function fuzzy membership generator.
Independent variable.
Bell function parameter controlling width. See Note for definition.
Bell function parameter controlling slope. See Note for definition.
Bell function parameter defining the center. See Note for definition.
Generalized Bell fuzzy membership function.
Notes
Definition of Generalized Bell function is:
y(x) = 1 / (1 + abs([x - c] / a) ** [2 * b])
skfuzzy.
inner_product
(a, b)[source]¶Inner product (dot product) of two fuzzy sets.
Fuzzy membership function.
Fuzzy membership function.
Fuzzy inner product value, on range [0, 1]
skfuzzy.
interp10
(x)[source]¶Utility function which conducts linear interpolation of any rank-1 array. Result will have 10x resolution.
Input array to be interpolated.
Linearly interpolated output.
skfuzzy.
interp_membership
(x, xmf, xx, zero_outside_x=True)[source]¶Find the degree of membership u(xx)
for a given value of x = xx
.
Independent discrete variable vector.
Fuzzy membership function for x
. Same length as x
.
Value(s) on universe x
where the interpolated membership is
desired.
Defines the behavior if xx
contains value(s) which are outside the
universe range as defined by x
. If True (default), all
extrapolated values will be zero. If False, the first or last value
in x
will be what is returned to the left or right of the range,
respectively.
Membership function value at xx
, u(xx)
. If xx
is a single
value, this will be a single value; if it is an array or iterable the
result will be returned as a NumPy array of like shape.
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.
skfuzzy.
interp_universe
(x, xmf, y)[source]¶Find interpolated universe value(s) for a given fuzzy membership value.
Independent discrete variable vector.
Fuzzy membership function for x
. Same length as x
.
Specific fuzzy membership value.
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.
skfuzzy.
lambda_cut
(ms, lcut)[source]¶The crisp (binary) lambda-cut set of the membership sequence ms with membership >= lcut.
Fuzzy membership set.
Value used for lambda-cut, on range [0, 1.0].
Lambda-cut set of ms: ones if ms[i] >= lcut, zeros otherwise.
skfuzzy.
lambda_cut_boundaries
(x, mfx, lambdacut)[source]¶Find exact boundaries where mfx crosses lambdacut using interpolation.
Universe variable
Fuzzy membership function
Floating point value on range [0, 1].
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
.
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.
Universe function for fuzzy membership function mfx.
Fuzzy membership function for x.
Number of steps.
Lambda cut intevals.
skfuzzy.
maxmin_composition
(s, r)[source]¶The max-min composition t
of two fuzzy relation matrices.
Fuzzy relation matrix #1.
Fuzzy relation matrix #2.
Max-min composition, defined by T = s o r
.
skfuzzy.
maxprod_composition
(s, r)[source]¶The max-product composition t
of two fuzzy relation matrices.
Fuzzy relation matrix #1.
Fuzzy relation matrix #2.
Max-product composition matrix.
skfuzzy.
modus_ponens
(a, b, ap, c=None)[source]¶Generalized modus ponens deduction to make approximate reasoning in a rules-base system.
Fuzzy set a
on universe x
Fuzzy set b
on universe y
New fuzzy fact a’ (a prime, not transpose)
Keyword argument representing fuzzy set c
on universe y
.
Default = None, which will use np.ones()
instead.
Full fuzzy relation.
Fuzzy conclusion b’ (b prime)
skfuzzy.
multval
(interval1, interval2)[source]¶Multiply intervals interval1 and interval2.
First interval.
Second interval.
Interval resulting from multiplication of interval1 and interval2.
skfuzzy.
nmse
(known, degraded)[source]¶Computes the percent normalized mean square error (NMSE %) between known and degraded arrays.
Known array of arbitrary size and shape. Must be convertible to float.
Degraded version of known, must have same shape as known.
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.
skfuzzy.
outer_product
(a, b)[source]¶Outer product of two fuzzy sets.
Fuzzy membership function.
Fuzzy membership function.
Fuzzy outer product value, on range [0, 1]
skfuzzy.
pad
(array, pad_width, mode='constant', **kwargs)¶Pad an array.
The array to pad.
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.
One of the following string values or a user supplied function.
Pads with a constant value.
Pads with the edge values of array.
Pads with the linear ramp between end_value and the array edge value.
Pads with the maximum value of all or part of the vector along each axis.
Pads with the mean value of all or part of the vector along each axis.
Pads with the median value of all or part of the vector along each axis.
Pads with the minimum value of all or part of the vector along each axis.
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
Pads with the reflection of the vector mirrored along the edge of the array.
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.
Pads with undefined values.
New in version 1.17.
Padding function, see Notes.
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.
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 constant
is a shortcut for before = after = constant
for
all axes.
Default is 0.
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 constant
is a shortcut for before = after = constant
for
all axes.
Default is 0.
Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.
Padded array of rank equal to array with shape increased according to pad_width.
Notes
New in version 1.7.0.
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 modify a rank 1 array in-place. It has the following signature:
padding_func(vector, iaxis_pad_width, iaxis, kwargs)
where
- vectorndarray
A rank 1 array already padded with zeros. Padded values are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].
- iaxis_pad_widthtuple
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.
- iaxisint
The axis currently being calculated.
- kwargsdict
Any keyword arguments the function requires.
Examples
>>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
array([4, 4, 1, ..., 6, 6, 6])
>>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, ..., 5, 5, 5])
>>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4])
>>> np.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
>>> np.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> np.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
>>> a = [[1, 2], [3, 4]]
>>> np.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]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
>>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
>>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
>>> np.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
>>> def pad_with(vector, pad_width, iaxis, kwargs):
... pad_value = kwargs.get('padder', 10)
... vector[:pad_width[0]] = pad_value
... vector[-pad_width[1]:] = pad_value
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, 2, pad_with)
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]])
>>> np.pad(a, 2, pad_with, padder=100)
array([[100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100],
[100, 100, 0, 1, 2, 100, 100],
[100, 100, 3, 4, 5, 100, 100],
[100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100]])
skfuzzy.
partial_dmf
(x, mf_name, mf_parameter_dict, partial_parameter)[source]¶Calculate the partial derivative of a specified membership function.
input variable.
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'
A dictionary of {param : key-value, ...}
pairs for a particular
membership function as defined above.
Name of the parameter against which we take the partial derivative.
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
skfuzzy.
piecemf
(x, abc)[source]¶Piecewise linear membership function (particularly used in FIRE filters).
Independent variable vector.
Defines the piecewise function. Important: if abc = [a, b, c] then a <= b <= c is REQUIRED!
Piecewise fuzzy membership function for x.
Notes
y = 0, min(x) <= x <= a y = b(x - a)/c(b - a), a <= x <= b y = x/c, b <= x <= c
skfuzzy.
pimf
(x, a, b, c, d)[source]¶Pi-function fuzzy membership generator.
Independent variable.
Left ‘foot’, where the function begins to climb from zero.
Left ‘ceiling’, where the function levels off at 1.
Right ‘ceiling’, where the function begins falling from 1.
Right ‘foot’, where the function reattains zero.
Pi-function.
Notes
This is equivalently a product of smf and zmf.
skfuzzy.
psigmf
(x, b1, c1, b2, c2)[source]¶Product of two sigmoid membership functions.
Data vector for independent variable.
Offset or bias for the first sigmoid. This is the center value of the sigmoid, where it equals 1/2.
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.
Offset or bias for the second sigmoid. This is the center value of the sigmoid, where it equals 1/2.
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.
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.
skfuzzy.
relation_min
(a, b)[source]¶Determine fuzzy relation matrix R
using Mamdani implication for the
fuzzy antecedent a
and consequent b
inputs.
Fuzzy antecedent variable of length M.
Fuzzy consequent variable of length N.
Fuzzy relation between a
and b
, of shape (M, N).
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
.
Fuzzy antecedent variable of length M.
Fuzzy consequent variable of length N.
Fuzzy relation between a
and b
, of shape (M, N).
skfuzzy.
scaleval
(q, interval)[source]¶Multiply scalar q with interval interval
.
Scalar to multiply interval with.
Interval. Must have exactly two elements.
New interval; z = q x interval.
skfuzzy.
sigmf
(x, b, c)[source]¶The basic sigmoid membership function generator.
Data vector for independent variable.
Offset or bias. This is the center value of the sigmoid, where it equals 1/2.
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.
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!
skfuzzy.
sigmoid
(x, power, split=0.5)[source]¶Intensify grayscale values in an array using a sigmoid function.
Input vector or image array. Should be pre-normalized to range [0, 1]
Power of the intensification (p > 0). Experiment with small, decimal values and increase as necessary.
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.
Output vector or image with contrast adjusted.
See also
skfuzzy.fuzzymath.contrast
Notes
The sigmoid used herein is defined as:
y = 1 / (1 + exp(- exp(- power * (x-split))))
skfuzzy.
smf
(x, a, b)[source]¶S-function fuzzy membership generator.
Independent variable.
‘foot’, where the function begins to climb from zero.
‘ceiling’, where the function levels off at 1.
S-function.
Notes
Named such because of its S-like shape.
skfuzzy.
subval
(interval1, interval2)[source]¶Subtract interval interval2 from interval interval1.
First interval.
Second interval.
Resultant subtracted interval.
skfuzzy.
trapmf
(x, abcd)[source]¶Trapezoidal membership function generator.
Independent variable.
Four-element vector. Ensure a <= b <= c <= d.
Trapezoidal membership function.
skfuzzy.
trimf
(x, abc)[source]¶Triangular membership function generator.
Independent variable.
Three-element vector controlling shape of triangular function. Requires a <= b <= c.
Triangular membership function.
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.
The n-dimensional input array.
The shape of the block. Each dimension must divide evenly into the corresponding dimensions of arr_in.
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]]]])
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).
The n-dimensional input array.
Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [1]) of the rolling window view.
(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
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]]]])