ANFIS Meets Neural Networks: Explainable Inputs, Flexible Outputs

TL;DR

  • A neural network is flexible but opaque: its knowledge lives in weights that mean nothing to a human.
  • ANFIS is readable (“IF temperature is medium AND humidity is low THEN …”) but its output stage is a blend of straight lines, which is rigid.
  • The hybrid keeps the readable fuzzy layers of ANFIS and replaces the rigid output stage with a small neural network, trained end to end with backpropagation.
  • You get readable inputs and rule activations, more flexible outputs, and you give up part of the explanation: which rules fired is visible, how the network combined them is not.

The rest of the post builds that argument step by step, then traces one dew-point prediction through every layer in NumPy and trains the full model in about 40 lines of PyTorch.

1. The problem: accurate or explainable, pick one

Most modelling teams hit the same wall. A neural network fits the data well, but nobody can say why it predicted what it did. A fuzzy inference system like ANFIS gives readable IF–THEN rules, but it can struggle once the relationship gets curved or the variables interact.

Combining the two aims for a model that is flexible like a neural network, but whose inputs still speak human language: “warm”, “humid”, “low”.

A 60-second fuzzy logic primer

Classical logic says a temperature is either “warm” or not. Fuzzy logic1 says it is warm to a degree between 0 and 1. A membership function turns a number into that degree (illustrative values):

Temperature “cold” “mild” “warm”
10 °C 0.8 0.3 0.0
22 °C 0.0 0.9 0.2

A fuzzy rule combines those degrees, for example “IF temperature is mild AND humidity is low THEN dew point is low”. How strongly the rule applies (its firing strength) is computed from the degrees of its conditions, typically by multiplying them. That is all the background the rest of the post needs.

2. Where a plain neural network falls short

A neural network learns from raw numbers, so everything it knows is buried in weights that have no meaning on their own.

  • No built-in explanation. A weight of 0.73 between “temperature” and hidden unit 4 tells a domain expert nothing. Post-hoc tools like SHAP2 can attribute a prediction to inputs afterwards, but the model itself has no vocabulary.
  • No place for domain knowledge. A meteorologist knows that “high temperature and low humidity” is a distinct regime. A plain network has to rediscover that from data, which costs samples.
  • Inputs are unbounded. Raw values flow straight into the weights at whatever scale they arrive. Fuzzy membership grades, by contrast, are always between 0 and 1, which gives the downstream layers a well-behaved input.

3. Where standard ANFIS falls short

ANFIS3 is a five-layer network that implements a Takagi–Sugeno fuzzy system4 and learns its rules from data. Its weak point is the end of the pipeline.

The first three layers are the good part: they fuzzify each input into grades like “low / medium / high”, compute how strongly each rule fires, and normalise those strengths. The last two layers are where it gets rigid. Each rule outputs a linear function of the inputs, and the prediction is a weighted average of those lines:

That design has four consequences:

  1. Curves are approximated by stitched planes. Each rule contributes a flat surface; the model is only as curved as the blending between them.
  2. More curvature means more rules. To fit a sharper curve you add membership functions, and rules multiply: 3 functions on 3 inputs is already rules, each with its own linear consequent.
  3. Rules combine only by weighted averaging. The model cannot learn that two rules firing together means something different from either alone.
  4. Training depends on that linearity. Classic ANFIS uses a hybrid learning rule: least squares for the consequent parameters and gradient descent for the membership functions. Least squares only works because the consequents enter linearly. Change the output stage and that trick goes away.

4. The hybrid: keep the fuzzy front end, replace the back end

The hybrid keeps ANFIS layers 1–3 as a feature extractor and feeds their output into a small neural network instead of the linear rule formulas. Zhang et al.5 evaluate this kind of neural network–fuzzy integration on the same task used below, daily dew point temperature.

Hybrid ANFIS and neural network architecture with 3 membership functions per input and 9 rules

Amber boxes and purple circles are trainable; gray circles are fixed operations. Notation used below:

  • : the two inputs (temperature and humidity).
  • , : the low / medium / high terms of and .
  • : the sigmoid, written so it is not confused with the membership width .
Layer Role Trainable? Output
L1 Fuzzification Yes: centers , widths 3 grades per input
L2 Rule firing () No 9 firing strengths
L3 Normalisation () No 9 strengths summing to 1
L4 Hidden layer Yes: , 2 activations
L5 Output Yes: , prediction

L1, fuzzification. Each input passes through Gaussian membership functions with a learned center and width :

L2, rule firing. Each rule multiplies one grade per input, for example “temperature is medium AND humidity is low”. With 3 functions on 2 inputs there are rules:

L3, normalisation. Each rule’s strength is divided by the sum of all 9, so the outputs add up to 1:

L4, hidden layer. Two sigmoid neurons take the 9 normalised strengths. This is where the model learns how rules combine, which is exactly what standard ANFIS cannot do:

L5, output. One neuron produces the prediction , which is compared with the true value to compute the loss:

Because the output stage is no longer linear, the least-squares step from classic ANFIS is dropped. Instead the whole model trains end to end with backpropagation:6 the loss gradient flows back through the neural network and the fixed and layers into the membership functions, so the fuzzy categories and the network learn together.

5. Worked example: predicting dew point, layer by layer

Take one weather reading, 24 °C at 40 % relative humidity, and follow it through the model. Each step shows the numbers and the NumPy code that produces them; the snippets run in order.

Why dew point?

Dew point is a good test case because temperature and humidity interact: the effect of humidity is logarithmic, and its size depends on the temperature. The physical reference is the Magnus approximation,7 here with the coefficients used by the WMO:8

For our reading this gives a true dew point of about 9.6 °C. The model never sees this formula. It has to learn the relationship from data, which is exactly the situation for messier targets where no formula exists.

Step 1 (L1): fuzzify the inputs

Each input gets three Gaussian membership functions. The values below are illustrative starting points, spaced so that neighbouring functions cross at 0.5.

import numpy as np

def gaussian_mf(x, c, sigma):
    return np.exp(-(x - c) ** 2 / (2 * sigma ** 2))

T, RH = 24.0, 40.0
c_T, s_T = np.array([4.0, 20.0, 36.0]), 6.79      # temperature: low, medium, high
c_RH, s_RH = np.array([19.0, 55.0, 91.0]), 15.29  # humidity: low, medium, high

mu_T = gaussian_mf(T, c_T, s_T)      # [0.013 0.841 0.210]
mu_RH = gaussian_mf(RH, c_RH, s_RH)  # [0.389 0.618 0.004]
Input Low Medium High
Temperature (centers 4 / 20 / 36 °C, °C) 0.013 0.841 0.210
Humidity (centers 19 / 55 / 91 %, %) 0.389 0.618 0.004

Reading: 24 °C is “mostly medium, a bit high”; 40 % is “between low and medium”.

Step 2 (L2): fire the rules

Every pairing of a temperature term with a humidity term is one rule, so the outer product computes all 9 firing strengths at once.

w = np.outer(mu_T, mu_RH).ravel()  # R1 = T low·RH low, R2 = T low·RH medium, ..., R9 = T high·RH high
# [0.005 0.008 0.000 0.327 0.520 0.003 0.082 0.130 0.001]

Step 3 (L3): normalise

Divide by the total () so the 9 strengths sum to 1.

w_bar = w / w.sum()
# [0.005 0.008 0.000 0.304 0.483 0.003 0.076 0.121 0.001]

Four rules carry 98 % of the weight:

Rule IF temperature is AND humidity is Firing strength Normalised
R5 medium medium 0.520 0.483
R4 medium low 0.327 0.304
R8 high medium 0.130 0.121
R7 high low 0.082 0.076
Other 5 rules 0.017 combined 0.016 combined

This is the explainable part. Anyone can read off that the sample is about half “mild and moderately humid” and a third “mild and dry”, and check whether that matches intuition.

Step 4 (L4): hidden layer

A standard dense layer with sigmoid activation. The weights are random here, as they would be before training.

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

rng = np.random.default_rng(0)
Theta1 = rng.normal(0, 0.5, size=(2, 9))  # trainable, 2 hidden units x 9 rules
b1 = np.zeros(2)                           # trainable

a = sigmoid(Theta1 @ w_bar + b1)  # [0.498 0.384]

The difference from ANFIS: standard ANFIS would compute the output as a weighted blend of nine linear formulas (effectively four, given the weights above). The hidden layer can instead learn non-linear combinations, for example that “mild and dry” together with “warm and dry” should push the dew point down faster than a simple average of the two.

Step 5 (L5): output and loss

One sigmoid neuron gives a value in , which is mapped back to °C. The loss compares it with the true dew point on the same scale.

Theta2 = rng.normal(0, 0.5, size=2)  # trainable
b2 = 0.0                             # trainable

y_hat = sigmoid(Theta2 @ a + b2)            # 0.575
y_min, y_max = -20.0, 30.0                  # target range seen in training
td_pred = y_hat * (y_max - y_min) + y_min   # 8.8 °C before any training

y_true = 9.6
y_scaled = (y_true - y_min) / (y_max - y_min)  # 0.592
J = 0.5 * (y_hat - y_scaled) ** 2              # 0.0001

The untrained network lands at 8.8 °C only by luck of the random weights. Training is what makes it reliable across samples.

Step 6: training

Backpropagation pushes , , and back through all five layers. The membership-function gradients come from differentiating the Gaussian:

In practice this means the fuzzy categories themselves move during training, not just the network weights.

You do not have to derive any of this by hand. Each layer above is a differentiable tensor operation, so an autodiff library computes every gradient for you. Here is the complete model in PyTorch: L1–L3 are three lines in forward, and L4–L5 are an ordinary nn.Sequential.

import torch
import torch.nn as nn

class HybridANFIS(nn.Module):
    def __init__(self, centers, sigmas, n_hidden=2):
        super().__init__()
        self.c = nn.Parameter(torch.tensor(centers))  # L1 centers: (2 inputs, 3 MFs)
        self.s = nn.Parameter(torch.tensor(sigmas))   # L1 widths:  (2 inputs, 3 MFs)
        self.net = nn.Sequential(                     # L4 + L5
            nn.Linear(9, n_hidden), nn.Sigmoid(),
            nn.Linear(n_hidden, 1), nn.Sigmoid(),
        )

    def forward(self, x):                                                    # x: (batch, 2)
        mu = torch.exp(-(x[:, :, None] - self.c) ** 2 / (2 * self.s ** 2))  # L1: (batch, 2, 3)
        w = (mu[:, 0, :, None] * mu[:, 1, None, :]).flatten(1)              # L2: (batch, 9)
        w_bar = w / (w.sum(dim=1, keepdim=True) + 1e-8)                     # L3: (batch, 9)
        return self.net(w_bar).squeeze(1)                                    # L4–L5: (batch,)

To train it, generate 2,000 synthetic readings from the Magnus formula, hold out 400 for testing, and start from the same membership functions as the worked example:

def magnus(T, RH):
    g = torch.log(RH / 100) + 17.62 * T / (243.12 + T)
    return 243.12 * g / (17.62 - g)

torch.manual_seed(0)
T = torch.rand(2000) * 40          # 0–40 °C
RH = 10 + torch.rand(2000) * 90    # 10–100 %
X, y = torch.stack([T, RH], dim=1), magnus(T, RH)
y_min, y_max = y.min(), y.max()
y_scaled = (y - y_min) / (y_max - y_min)
train, test = slice(0, 1600), slice(1600, None)

model = HybridANFIS(
    centers=[[4.0, 20.0, 36.0], [19.0, 55.0, 91.0]],
    sigmas=[[6.79] * 3, [15.29] * 3],
)
opt = torch.optim.Adam(model.parameters(), lr=0.05)

for epoch in range(2000):
    loss = 0.5 * ((model(X[train]) - y_scaled[train]) ** 2).mean()  # J, averaged over the batch
    opt.zero_grad()
    loss.backward()   # autograd computes every ∂J/∂θ, ∂J/∂b, ∂J/∂c, ∂J/∂σ
    opt.step()

On my machine this trains in a few seconds and gives:

  • Test error: a mean absolute error of about 0.25 °C on the 400 held-out readings.
  • Our sample: 24 °C at 40 % now predicts 9.6 °C, against a true value of 9.6 °C (it was 8.8 °C, by luck, before training).
  • Learned membership functions, which you can read straight off model.c and model.s:
Center (°C or %) Low Medium High
Temperature, before → after 4 → 5.1 20 → 20.4 36 → 52.8
Humidity, before → after 19 → −4.5 55 → 46.3 91 → 92.1

The middle terms barely moved, so “medium temperature” still means about 20 °C and the rules stay readable. The two bold values are a warning, though: “high temperature” now sits at 52.8 °C, beyond the 40 °C maximum in the data, and “low humidity” is centred on an impossible −4.5 %. The model is still accurate, because those functions widened and act as soft “above” and “below” ramps, but the labels have lost their literal meaning. That leads to the practical tips.

Three practical tips from building it:

  1. Match the membership functions to each input’s scale. The example keeps raw units so the centers stay readable, which works because each input’s initial widths fit its own range. With many inputs on very different scales, it is simpler to standardise them first and convert the centers back to real units when reporting.
  2. Keep membership centers inside the data range if you care about readable labels, as the table above shows. Clamp them after each optimizer step (model.c.data.clamp_(lo, hi) per input), or add a penalty for leaving the range.
  3. Guard the normalisation layer. An outlier far from every center (a sensor glitch reading 900 °C) drives all firing strengths to zero, and L3 divides 0 by 0. Add a small to the denominator, or clip inputs to the training range.

6. Trade-offs and when not to use it

The hybrid is a middle ground, not a free lunch: you gain flexibility and keep readable inputs, but the final mapping is a small black box again.

Neural network Standard ANFIS Hybrid
Readable inputs and rules No Yes Yes
Explains how rules combine No Yes, a weighted average of linear rules Partly: which rules fired, not how the NN combined them
Output flexibility High Limited by linear consequents Higher, via the hidden layer
Training Backpropagation Least squares + gradient descent Backpropagation end to end
Scales to many inputs Yes Poorly, rules grow exponentially Poorly, same rule explosion

Pick something else when:

  • You have lots of data and no need to explain. A plain neural network or gradient-boosted trees will usually be simpler and at least as accurate.
  • You must justify every prediction end to end (regulated settings, safety cases). Standard ANFIS, whose output is a readable blend of rule formulas, is easier to defend.
  • You have more than 4–5 inputs. With grid-partitioned rules, 6 inputs at 3 membership functions each means rules. Reduce inputs first, or generate fewer rules from the data with clustering, such as subtractive clustering.9

Finally, whether the hybrid beats standard ANFIS is an empirical question for your data. Benchmark all three (plain neural network, standard ANFIS, hybrid) on the same train/validation/test split before claiming a win.

Notes

  1. Zadeh, L. A. (1965). Fuzzy sets. Information and Control, 8(3), 338–353. ↩

  2. Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. Advances in Neural Information Processing Systems 30 (NeurIPS 2017). ↩

  3. Jang, J.-S. R. (1993). ANFIS: Adaptive-network-based fuzzy inference system. IEEE Transactions on Systems, Man, and Cybernetics, 23(3), 665–685. ↩

  4. Takagi, T., & Sugeno, M. (1985). Fuzzy identification of systems and its applications to modeling and control. IEEE Transactions on Systems, Man, and Cybernetics, SMC-15(1), 116–132. ↩

  5. Zhang, G., Band, S. S., Ardabili, S., Chau, K.-W., & Mosavi, A. (2022). Integration of neural network and fuzzy logic decision making compared with bilayered neural network in the simulation of daily dew point temperature. Engineering Applications of Computational Fluid Mechanics, 16(1), 713–723. ↩

  6. Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323(6088), 533–536. ↩

  7. Lawrence, M. G. (2005). The relationship between relative humidity and the dewpoint temperature in moist air: A simple conversion and applications. Bulletin of the American Meteorological Society, 86(2), 225–234. ↩

  8. World Meteorological Organization. (2018). Guide to Instruments and Methods of Observation (WMO-No. 8), Volume I: Measurement of Meteorological Variables, Chapter 4: Measurement of humidity. Geneva: WMO. ↩

  9. Chiu, S. L. (1994). Fuzzy model identification based on cluster estimation. Journal of Intelligent & Fuzzy Systems, 2(3), 267–278. ↩

Citation

Please cite this work as:

Makonda, Barnabas, "ANFIS Meets Neural Networks: Explainable Inputs, Flexible Outputs", Barnabas Makonda's blog, Nov 2026.

Or use the BibTeX citation:

bibtex
@misc{makonda2026anfis,
  author = {Barnabas Makonda},
  title = {ANFIS Meets Neural Networks: Explainable Inputs, Flexible Outputs},
  howpublished = {Barnabas Makonda's blog},
  year = {2026},
  month = {nov},
  url = {https://blog.barnabasmakonda.workers.dev/posts/ansifs-neural-network/},
}