Res-WG-KNN Pneumonia Model on Chest X-rays, Audited

Analysis by Adnan Saeed  ·  AI for medical imaging and healthcare  ·  Source paper peer reviewed in Intelligent Systems with Applications, 2025  ·  Explains published research, not medical advice  ·  No medical reviewer has checked this article  ·  2 December 2026
  • Pneumonia detection
  • Chest X-ray
  • Wavelet texture
  • GLCM
  • KNN
  • ResNet50
  • Soft voting
  • Data leakage
  • PyTorch
Res-WG-KNN pipeline for pneumonia on chest X-rays, with Haar wavelet sub bands feeding a GLCM texture KNN, a modified ResNet50, a soft vote, and an AUC panel comparing the reported 0.97 with a 0.88 ceiling
A radiograph is split into four wavelet sub bands for the texture branch while ResNet50 reads the whole image, and the two probability outputs are averaged. The panel on the right sets the reported RSNA result beside the best case for two branches of that strength. Synthetic image and schematic by aitrendblend.

A night shift in a busy emergency department. Twenty chest films are waiting, some from older adults with a cough and fever, some from small children brought in wheezing. A tool that flags the likely pneumonia cases first would let the radiologist read those films sooner. That is the promise behind almost every pneumonia classifier published in the last eight years, and it is why the numbers in this one deserve a close look.

Asmaa Shati, Ghulam Mubashar Hassan and Amitava Datta, working at the University of Western Australia and King Khalid University, take an unusual route. Instead of stacking more convolutional networks, they pair a modern ResNet50 with an old fashioned texture pipeline built from a wavelet transform, co occurrence statistics and a K nearest neighbours vote. Neither branch is impressive alone. Each scores around 82 percent accuracy on the adult RSNA dataset. Averaged together, the paper reports 97 percent. This piece explains how the model works, then tests whether that jump is arithmetically possible.

Key points

  • Res-WG-KNN averages the probabilities of a wavelet texture KNN and a modified ResNet50, a simple soft vote with equal weights.
  • On RSNA the branches score 0.79 and 0.80 AUC, and the fusion is reported at 0.97. On the pediatric Kermany set the branches score 0.60 and 0.94, and the fusion 0.99.
  • Under the standard binormal model, two branches of that strength with fully independent errors top out near 0.88 AUC on RSNA and 0.94 on Kermany.
  • The paper’s 30,227 RSNA images are label rows, which include 3,543 extra rows for radiographs already counted, and the data were split at random by image.
  • Weighted averages in the results tables imply different test sets for different models, and two reported F1 scores fall outside the range F1 can take.
Please read. This article explains a published research paper about automated pneumonia classification. It is not medical advice, diagnosis or treatment. Anyone with symptoms such as fever, cough or difficulty breathing, or a child with these symptoms, should be assessed by a qualified clinician.

Two modest models and one very strong vote

Most recent pneumonia papers chase accuracy with bigger backbones, attention modules or ensembles of three or four deep networks. This paper argues the opposite direction. Hand crafted texture features see something different from a convolutional network, the authors say, so a cheap classifier on those features should cover the network’s blind spots. The fusion rule is the simplest one available, the mean of two probability vectors.

That framing is interesting, and it is not new in spirit. Radiomics has used co occurrence texture for decades, and we covered a closely related design on this site, a texture descriptor joined to a DenseNet for tuberculosis, in our analysis of ETDHDNet on chest radiographs. What makes Res-WG-KNN different is that the texture branch is not fused at the feature level or fed into a trained head. It votes as an equal partner, with its own complete probability estimate, and nothing learns how much to trust it.

That design choice turns out to matter a great deal when we read the results. An equal vote between two weak and correlated models usually lands somewhere between them, sometimes a little above. A vote that leaps fifteen points past both is rare enough that the reason for it should be found and explained. The paper does not explain it. For readers who want a map of other medical classification work we have covered, the Medical AI category collects them in one place.

How the texture branch reads a radiograph

A single Haar split into four sub bands

Each image is resized to 224 by 224 pixels and passed through a one level two dimensional discrete wavelet transform with the Haar filter. The Haar wavelet is the simplest one there is. For every block of two by two pixels it computes one average and three differences. The average forms a half resolution copy of the image called LL. The differences form three detail images. LH responds to changes across columns, HL to changes across rows, and HH to diagonal change.

One level Haar transform on a two by two block with pixels a, b, c and d $$\mathrm{LL}=\tfrac{1}{2}(a+b+c+d),\quad \mathrm{LH}=\tfrac{1}{2}(a-b+c-d),\quad \mathrm{HL}=\tfrac{1}{2}(a+b-c-d),\quad \mathrm{HH}=\tfrac{1}{2}(a-b-c+d)$$

On a chest film, consolidation tends to show as a hazy bright region that blurs the fine vascular markings of a healthy lung. In principle the detail bands should carry less high frequency energy over those regions. That is the intuition. Whether a single level of decomposition at 224 pixels keeps enough fine structure to see it is a separate question, and the paper does not test deeper decompositions or other wavelets.

Four texture statistics per band

For each of the four sub bands the authors build a gray level co occurrence matrix. The matrix counts how often a pixel of intensity i sits next to a pixel of intensity j. After normalising the counts into probabilities \(p(i,j)\), four classic Haralick style statistics summarise the texture.

GLCM properties computed on every sub band $$\text{contrast}=\sum_{i,j}p(i,j)(i-j)^2,\qquad \text{energy}=\sqrt{\sum_{i,j}p(i,j)^2}$$ $$\text{homogeneity}=\sum_{i,j}\frac{p(i,j)}{1+(i-j)^2},\qquad \text{dissimilarity}=\sum_{i,j}p(i,j)\,\lvert i-j\rvert$$

Four bands times four statistics gives a feature vector of only 16 numbers per radiograph. The paper does not report the pixel offset or the angle used for the co occurrence matrix, nor how the wavelet coefficients, which can be negative and fractional, were quantised into integer gray levels. Those choices change the features. Our implementation states its assumptions in the code comments so a reader can change them.

The paper’s own t-SNE plot of these 16 features on RSNA shows the pneumonia and non pneumonia points largely overlapping. That is an honest figure, and it matches the branch’s modest score. Texture summaries this compact simply cannot separate the two classes well on their own.

A distance weighted vote among 75 neighbours

The texture vectors go to a K nearest neighbours classifier. A two fold grid search over odd values of K from 25 to 75 picked K equal to 75, with neighbours weighted by the inverse of their distance and the neighbour search algorithm left on automatic. The predicted probability for a class is the weighted share of neighbours that belong to it.

Distance weighted KNN probability for class c $$P_{\text{KNN}}(c\mid x)=\frac{\sum_{k\in\mathcal{N}_{75}(x)} w_k\,\mathbb{1}[y_k=c]}{\sum_{k\in\mathcal{N}_{75}(x)} w_k},\qquad w_k=\frac{1}{\lVert x-x_k\rVert}$$

One detail matters later. The grid search chose the largest K it was allowed to try. When the best setting sits on the edge of a search range, the honest next step is to widen the range, because the optimum may lie beyond it.

The deep branch and the averaging rule

The second branch is an ImageNet pretrained ResNet50 whose classifier is replaced by five regularised fully connected blocks. Each block applies a dense layer, batch normalisation, ReLU, dropout at 0.3 and L2 weight regularisation, with the width shrinking from block to block before a two way output. Training used Adam at a learning rate of 0.01 for 100 epochs with batches of 256, on an NVIDIA Tesla P100 with TensorFlow. The description of the backbone is ambiguous. One passage says its layers were fine tuned, another says the top layers were frozen in order to fine tune them, and the paper does not list which layers were trainable. It does not mention data augmentation.

A learning rate of 0.01 is high for Adam on a pretrained ResNet. If much of the backbone was trainable, that setting can wash out what ImageNet pretraining provides, which might explain why the network reaches only 82 percent on RSNA. If most of it was frozen, 82 percent is a reasonable result for features never trained on chest films. Either reading is plausible, and without the layer list a reader cannot tell which applies.

The fusion step is soft voting. Each branch outputs a probability for pneumonia and for non pneumonia, the two vectors are averaged, and the class with the larger average wins.

Soft vote used by Res-WG-KNN $$P(c\mid x)=\tfrac{1}{2}\big(P_{\text{KNN}}(c\mid x)+P_{\text{ResNet}}(c\mid x)\big),\qquad \hat{y}=\arg\max_c P(c\mid x)$$
Key takeaway

Res-WG-KNN is a fixed average of two independently trained models. No parameter learns how to combine them, so the fusion cannot discover a cleverer rule than the mean. Everything it achieves must come from the two branches disagreeing in useful ways.

The results as reported

The study uses two public collections. The RSNA Pneumonia Detection Challenge set holds adult frontal radiographs in DICOM format, labelled by radiologists. The Kermany set holds 5,856 pediatric chest films in JPEG format from Guangzhou Women and Children’s Medical Center, with 4,273 labelled pneumonia and 1,583 normal. Both were split at random, 80 percent of images for training, 10 for validation and 10 for testing. The full numbers are in the open access paper in Intelligent Systems with Applications.

DatasetModelAccuracyMacro F1AUC
RSNA, adultsWG-KNN texture branch83.0%79.0%0.79
RSNA, adultsModified ResNet5082.0%79.5%0.80
RSNA, adultsRes-WG-KNN fusion97.0%97.0%0.97
Kermany, childrenWG-KNN texture branch73.0%64.0%0.60
Kermany, childrenModified ResNet5096.0%95.0%0.94
Kermany, childrenRes-WG-KNN fusion99.0%98.5%0.99
Test set results from Tables 4 and 5 of the paper. Macro F1 is the unweighted mean of the two class F1 scores.

Against outside baselines trained by the authors on RSNA, MobileNetV2 reached 76 percent test accuracy, EfficientNetB3 79 percent, an ensemble of MobileNetV2 and InceptionV3 80 percent, and a standard ResNet50 82 percent. The paper also lists published RSNA results from other groups, with accuracies between 72 and 88.67 percent. Those earlier studies used different splits, different label definitions and in one case a detection task rather than classification, so a row by row comparison with Res-WG-KNN says little about which method is better.

Look at the pattern in the table. On RSNA, two models within one point of each other combine into a model fifteen points better than either. On Kermany, a texture branch with an AUC of 0.60, barely above a coin toss in ranking terms, lifts a 0.94 network to 0.99. Both claims are possible in principle. Neither is usual. So we checked them.

Why 0.97 is hard to reach from two 0.80 models

An averaging vote cannot rescue a case both branches get wrong

Start with a fact about soft voting on two classes. If both branches give the true class a probability below one half, their average is also below one half, and the fusion is wrong. The fused model can only be right on images where at least one branch was already right. So the fused error rate can never fall below the share of images that both branches misclassify.

On RSNA the branches miss 17 and 18 percent of test images. If their mistakes were completely unrelated, the share both miss would be about 0.17 times 0.18, a little over 3 percent. That caps fused accuracy near 97 percent, and reaching the cap needs every disagreement, roughly a third of the test set, to be settled in favour of whichever branch happens to be right. In real data the two branches share hard cases, such as faint opacities, rotated films and portable views, so their errors overlap more than chance and the cap drops.

The same limit expressed through AUC

AUC gives a cleaner view because it does not depend on a threshold. Under the binormal model that radiology evaluation has long used, a classifier’s AUC equals \(\Phi(d/\sqrt{2})\), where \(d\) measures how far apart the two classes sit in score space. For two branches with independent errors, the best possible linear combination adds their separations in quadrature.

Best case AUC for two branches with independent errors $$d=\sqrt{2}\,\Phi^{-1}(\text{AUC}),\qquad d_{\text{fused}}=\sqrt{d_1^2+d_2^2},\qquad \text{AUC}_{\text{fused}}=\Phi\!\left(d_{\text{fused}}/\sqrt{2}\right)$$

Plug in RSNA. Branch AUCs of 0.79 and 0.80 give a ceiling of 0.878. Our simulation with 4,000 synthetic cases returns the same 0.878, and with a modest error correlation of 0.5 the figure drops to 0.827. The reported 0.97 is far beyond either. On Kermany, 0.60 and 0.94 give a ceiling of 0.942, almost exactly the ResNet50 branch alone, because a 0.60 branch carries very little extra signal. The paper reports 0.99.

The binormal model is an approximation, and real score distributions can be skewed. Getting past the ceiling by fifteen points would still require the two branches to make negatively correlated mistakes, with the texture model reliably right on exactly the images where the network is wrong. The authors show no analysis of that kind, and the t-SNE figure suggests the texture features do not separate the classes well enough to play that role.

The use of a soft voting technique in the proposed model effectively enhances classification performance.Shati, Hassan and Datta, abstract, Intelligent Systems with Applications 2025

A claim like that needs a mechanism. When a result breaks a bound this simple, the usual explanation is not a better model but an evaluation that lets information from the test set leak into training or into the fused prediction.

What the tables reveal when the arithmetic is checked

The RSNA counts describe label rows, not images

The paper describes RSNA as 30,227 images with 20,672 pneumonia cases and 9,555 non pneumonia cases. The challenge’s label file does have 30,227 rows, but the official data page states that one patient can have several rows, one per bounding box. The paper itself, in its review of earlier work, mentions 26,684 RSNA instances. That gap of 3,543 rows consists entirely of second and third boxes on pneumonia positive films. In the challenge labels, 9,555 is the number of rows marked positive, and 20,672 is the number of negative films. The class names in the paper’s text are swapped.

The swap may be a writing slip. The duplication is not. If the authors split 30,227 rows at random, many positive radiographs with two or three boxes will have one copy in training and another, pixel identical, in the test set. A KNN with a distance weighting rule gives an exact match all of the weight. A ResNet trained for 100 epochs memorises its training images. Both would score those duplicate test images perfectly, and the effect would be concentrated in the pneumonia class.

Weighted averages expose the class mix of the test set

A weighted average over classes weights each class by its share of the test set. That makes it possible to solve for the share. Weighted recall also has to equal overall accuracy, because both count correct predictions divided by all predictions. Our audit function applies both rules to the paper’s tables.

Table rowImplied pneumonia share of test setRule broken
RSNA, WG-KNN0.32Weighted recall 82.3 versus accuracy 83.0, likely rounding
RSNA, ResNet500.27Non pneumonia F1 of 87 above both precision 85 and recall 86
Kermany, WG-KNN0.37Pneumonia F1 of 45 below both precision 50 and recall 48
Kermany, ResNet500.46Weighted recall 94.8 versus accuracy 96.0
Computed by our code from Tables 4 and 5 of the paper. F1 is the harmonic mean of precision and recall, so it must lie between them.

Three things stand out. First, both models were tested on the same split, yet the RSNA rows imply 32 and 27 percent pneumonia, and the Kermany rows imply 37 and 46 percent. A single test set has one class mix. Second, Kermany is 73 percent pneumonia by the paper’s own count, and a random 10 percent sample of it should be close to that, not 37 or 46 percent. Either the class labels in the Kermany table are reversed, or the averages were computed in a way that does not match the test data. Third, an F1 score outside the range set by its own precision and recall cannot come from any confusion matrix.

None of these slips proves the fused numbers are wrong. Each one does lower confidence that the tables were produced by one consistent evaluation script run once on one held out set.

The timing table has a unit problem

Table 9 lists inference time per image as 0.047 milliseconds for ResNet50 on RSNA, alongside a total inference time of 143 seconds. A 10 percent test split of 30,227 rows is about 3,000 images, and 143 seconds over 3,000 images is about 47 milliseconds each. The per image column appears to be in seconds, not milliseconds, which is a thousandfold difference for anyone planning deployment. The same table reports 646.56 seconds to train the ResNet50 branch on Kermany but 67.2 seconds to train the full fusion model, which contains that branch, and the row labels mix the names WG-KKN and Sub Fusion in ways that suggest rows were assigned to the wrong models.

Key takeaway

The fusion results exceed what two branches of the reported strength can reach together, and the supporting tables fail several consistency checks. The most likely explanation is an evaluation issue, with duplicate RSNA rows split across training and testing as the leading candidate, rather than a model that is fifteen points better.

Where leakage hides in these two datasets

Chest X-ray benchmarks have a long history of inflated scores from splits that ignore who the image belongs to. RSNA labels repeat a film for every bounding box, and the RSNA challenge negatives include not only normal films but also films with other abnormalities that are not pneumonia, which makes the task harder than a clean normal versus pneumonia problem. Kermany images are named with patient and study identifiers, and the same child can appear more than once. A random split by file treats two radiographs of one child, taken a day apart, as independent evidence, when a model can match them on rib shape, positioning and the scanner’s own artefacts.

The Kermany release also comes with an official held out test folder of 624 images, which many studies use so results can be compared. This paper merged everything and drew its own random 10 percent, so its 99 percent cannot be set beside studies that used the official folder.

There is a broader pattern worth knowing. Models trained on one hospital’s films often learn to recognise the hospital, the scanner or the patient population, and their accuracy drops on films from elsewhere. Our article on teaching a model to ignore which scanner took the picture covers that problem in breast imaging, and the lesson transfers directly to chest radiography. An adult dataset from one source and a pediatric dataset from one Chinese hospital, each split at random, cannot tell us how Res-WG-KNN behaves anywhere else.

Clinical translation gap

The paper closes with a sensible list of what deployment would require. Integration with radiology information systems, prospective validation, clinician feedback on ambiguous cases, and regulatory approval. All of that is right. The gap is that none of it can start from the current evidence, because the evidence has not yet shown the model works on a population it was not trained and tested on.

Real workflows differ from either dataset in ways that matter. Emergency films include portable anteroposterior views, patients with lines and tubes, and lungs with several overlapping conditions at once. Pneumonia is a clinical diagnosis that combines imaging with symptoms, examination and laboratory results, so a binary image label is a proxy with its own error. A pediatric model trained on children aged one to five from one centre says nothing about infants or teenagers, and an adult model trained on one American public dataset says nothing about settings where tuberculosis or other infections change what an opacity means.

Thresholds are another missing piece. A triage tool needs an operating point chosen for high sensitivity, with a known false positive rate at that point. The paper reports macro and weighted averages at the default threshold of one half and gives no sensitivity at fixed specificity, no calibration analysis and no confidence intervals. For a screening use, the number that matters most, how many true pneumonia cases the tool misses, is not available in a form a clinician could act on.

Clinical limitations

Sample size first. The RSNA test split holds roughly 3,000 rows and the Kermany test split roughly 586 images. One random split each, with no repeated runs, means no measure of how much the figures would move with a different shuffle. On a test set of 586 images, one percentage point is about six images.

Dataset bias next. RSNA labels came from radiologists reading films originally drawn from the NIH collection, whose earlier labels were mined from reports by language processing. Kermany labels were graded by expert physicians after quality control removed unreadable films, which makes its images cleaner than a typical night shift. Neither set reports age, sex or ethnicity breakdowns in the paper, so subgroup performance is unknown.

Generalisation last. There is no external test set, no cross dataset experiment such as training on RSNA and testing on Kermany, and no patient level split. The authors acknowledge the need for external validation in their limitations section. Until that exists, the safest reading is that the branch level results, around 82 percent on RSNA and 96 percent on Kermany, are the more trustworthy figures, and even those carry the leakage risk described above.

What would make the result convincing

The fix is not complicated, and anyone reproducing this work can do it in an afternoon. Collapse the RSNA label rows to one label per radiograph. Split by patient on both datasets. Use the official Kermany test folder or a patient disjoint equivalent. Run five or more random seeds and report a mean with a confidence interval. Report the AUC of each branch and of the fusion on that clean split, along with the share of test images both branches miss, which is the floor on fused error. If the fusion then still sits well above both branches, the authors would have something genuinely surprising, and an error correlation analysis would show why.

Two further tests would sharpen the story. Learn the fusion weight on the validation set instead of fixing it at one half, and see whether the texture branch earns any weight at all. Then train on one dataset and test on the other, which is the quickest way to learn whether texture features survive a change of hospital better than deep features do. That last question is the most interesting idea in the paper, and it deserves a fair test. Readers interested in why equal weights in fusion tend to disappoint may enjoy our breakdown of equal weighted descriptor fusion in hyperspectral anomaly detection, a different field with the same lesson.

Reference implementation in PyTorch

The authors used TensorFlow and did not release code. The implementation below is ours, written from the paper’s description. It covers the Haar transform, GLCM features, the distance weighted KNN with a grid search, the modified ResNet50 with five regularised blocks, the soft vote and a full metrics report. We added duplicate removal, a patient level split, a table audit function and the fusion ceiling calculation used above. The smoke test runs on synthetic radiographs in about ten seconds on a CPU and prints the audit of the paper’s own tables.

"""
Res-WG-KNN, soft voting fusion of wavelet GLCM texture features with KNN and a modified ResNet50.
Educational PyTorch reimplementation written from the description in
Shati, Hassan and Datta, Intelligent Systems with Applications 26 (2025) 200492.
The authors used TensorFlow and did not release code. This is not their implementation.

Two additions that are not in the paper are marked "our addition". They guard against
the evaluation problems discussed in the article: duplicate images and patient overlap.
"""
import hashlib
import random
from collections import defaultdict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet50


# ----------------------------------------------------------------------------
# Engineered features. One level Haar 2D DWT, then GLCM texture on each sub band
# ----------------------------------------------------------------------------
def haar_dwt2(img):
    """One level 2D Haar transform (Eq. 3 and 4). Returns LL, LH, HL, HH at half resolution."""
    img = np.asarray(img, dtype=np.float64)
    h, w = img.shape[0] // 2 * 2, img.shape[1] // 2 * 2
    x = img[:h, :w]
    a, b = x[0::2, 0::2], x[0::2, 1::2]
    c, d = x[1::2, 0::2], x[1::2, 1::2]
    ll = (a + b + c + d) / 2.0
    lh = (a - b + c - d) / 2.0
    hl = (a + b - c - d) / 2.0
    hh = (a - b - c + d) / 2.0
    return ll, lh, hl, hh


def quantize(band, levels=32):
    """GLCM needs integer gray levels. Each band is min max scaled to the given number of levels."""
    lo, hi = band.min(), band.max()
    if hi - lo < 1e-12:
        return np.zeros_like(band, dtype=np.int64)
    q = ((band - lo) / (hi - lo) * (levels - 1)).round()
    return q.astype(np.int64)


def glcm(q, levels=32, dx=1, dy=0):
    """Symmetric, normalised co occurrence matrix for one pixel offset (default, right neighbour).
    The paper does not report distance or angle, so offset 1 at 0 degrees is assumed."""
    h, w = q.shape
    a = q[0:h - dy, 0:w - dx].ravel()
    b = q[dy:h, dx:w].ravel()
    m = np.zeros((levels, levels), dtype=np.float64)
    np.add.at(m, (a, b), 1.0)
    m = m + m.T
    return m / max(m.sum(), 1.0)


def glcm_props(p):
    """Contrast, energy, homogeneity and dissimilarity, as computed by graycoprops."""
    L = p.shape[0]
    i, j = np.meshgrid(np.arange(L), np.arange(L), indexing="ij")
    diff = i - j
    contrast = (p * diff ** 2).sum()
    energy = np.sqrt((p ** 2).sum())
    homogeneity = (p / (1.0 + diff ** 2)).sum()
    dissimilarity = (p * np.abs(diff)).sum()
    return [contrast, energy, homogeneity, dissimilarity]


def wavelet_glcm_features(gray, levels=32):
    """16 features per image. Four sub bands times four GLCM properties."""
    feats = []
    for band in haar_dwt2(gray):
        feats.extend(glcm_props(glcm(quantize(band, levels), levels)))
    return np.array(feats, dtype=np.float64)


# ----------------------------------------------------------------------------
# WG-KNN sub model. Distance weighted KNN with a grid search over odd K and weighting
# ----------------------------------------------------------------------------
class KNN:
    def __init__(self, k=75, weights="distance"):
        self.k, self.weights = k, weights

    def fit(self, X, y):
        self.mu, self.sd = X.mean(0), X.std(0) + 1e-8      # standardise features
        self.X = torch.tensor((X - self.mu) / self.sd)
        self.y = torch.tensor(y, dtype=torch.long)
        return self

    def predict_proba(self, X):
        Q = torch.tensor((X - self.mu) / self.sd)
        d = torch.cdist(Q, self.X)
        k = min(self.k, len(self.y))
        dist, idx = d.topk(k, largest=False)
        lab = self.y[idx]
        if self.weights == "distance":
            w = 1.0 / dist.clamp_min(1e-12)
            exact = dist < 1e-12                     # like scikit learn, an exact match takes all the weight
            w = torch.where(exact.any(1, keepdim=True), exact.double(), w)
        else:
            w = torch.ones_like(dist)
        proba = torch.zeros(len(Q), 2, dtype=torch.float64)
        proba.scatter_add_(1, lab, w)
        return (proba / proba.sum(1, keepdim=True)).numpy()


def grid_search_knn(X, y, ks=range(25, 76, 2), folds=2, seed=0):
    """Two fold cross validation over odd K from 25 to 75 and both weightings."""
    rng = np.random.default_rng(seed)
    order = rng.permutation(len(y))
    parts = np.array_split(order, folds)
    best, best_cfg = -1.0, None
    for k in ks:
        for wt in ("uniform", "distance"):
            accs = []
            for f in range(folds):
                te = parts[f]
                tr = np.concatenate([parts[g] for g in range(folds) if g != f])
                p = KNN(k, wt).fit(X[tr], y[tr]).predict_proba(X[te])
                accs.append((p.argmax(1) == y[te]).mean())
            if np.mean(accs) > best:
                best, best_cfg = float(np.mean(accs)), (k, wt)
    return KNN(*best_cfg).fit(X, y), best_cfg, best


# ----------------------------------------------------------------------------
# Modified ResNet50 sub model. Backbone plus five regularised fully connected blocks
# ----------------------------------------------------------------------------
class RFCBlock(nn.Module):
    """Dense, batch norm, ReLU and dropout 0.3. L2 regularisation is applied through weight decay."""
    def __init__(self, cin, cout, p=0.3):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(cin, cout), nn.BatchNorm1d(cout), nn.ReLU(inplace=True), nn.Dropout(p))

    def forward(self, x):
        return self.net(x)


class ModifiedResNet50(nn.Module):
    def __init__(self, pretrained=False, widths=(512, 256, 128, 64, 32), freeze_backbone=True):
        super().__init__()
        weights = "IMAGENET1K_V2" if pretrained else None
        backbone = resnet50(weights=weights)
        backbone.fc = nn.Identity()
        if freeze_backbone:
            for p in backbone.parameters():
                p.requires_grad_(False)
        self.backbone = backbone
        layers, cin = [], 2048
        for w in widths:                               # gradual decrease in units, five blocks
            layers.append(RFCBlock(cin, w))
            cin = w
        self.head = nn.Sequential(*layers, nn.Linear(cin, 2))

    def forward(self, x):                              # x: (B, 3, 224, 224)
        return self.head(self.backbone(x))


def train_resnet(model, x, y, epochs=100, lr=0.01, batch_size=256, weight_decay=1e-4):
    """Adam at learning rate 0.01, batch 256 and 100 epochs, as in Table 2 of the paper."""
    opt = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=lr, weight_decay=weight_decay)
    n = len(y)
    for ep in range(epochs):
        model.train()
        perm = torch.randperm(n)
        for i in range(0, n, batch_size):
            idx = perm[i:i + batch_size]
            if len(idx) < 2:
                continue                               # batch norm needs two samples
            loss = F.cross_entropy(model(x[idx]), y[idx])
            opt.zero_grad()
            loss.backward()
            opt.step()
    return model


@torch.no_grad()
def resnet_proba(model, x, batch_size=64):
    model.eval()
    return torch.cat([model(x[i:i + batch_size]).softmax(1) for i in range(0, len(x), batch_size)]).numpy()


# ----------------------------------------------------------------------------
# Soft voting
# ----------------------------------------------------------------------------
def soft_vote(p1, p2):
    """P = (P1 + P2) / 2, then the class with the higher averaged probability wins."""
    p = (np.asarray(p1) + np.asarray(p2)) / 2.0
    return p, p.argmax(1)


# ----------------------------------------------------------------------------
# Metrics. Per class, macro and weighted averages, plus a rank based AUC
# ----------------------------------------------------------------------------
def auc_score(y, score):
    """Probability that a random positive outranks a random negative (ties count half)."""
    y = np.asarray(y)
    pos, neg = score[y == 1], score[y == 0]
    if len(pos) == 0 or len(neg) == 0:
        return float("nan")
    gt = (pos[:, None] > neg[None, :]).sum()
    eq = (pos[:, None] == neg[None, :]).sum()
    return float((gt + 0.5 * eq) / (len(pos) * len(neg)))


def fusion_auc_ceiling(auc_a, auc_b):
    """Binormal equal variance model. AUC = Phi(d / sqrt 2). With independent errors the best
    linear fusion reaches d = sqrt(d_a^2 + d_b^2). Positively correlated errors only lower it."""
    from statistics import NormalDist
    N = NormalDist()
    d = lambda auc: 2 ** 0.5 * N.inv_cdf(auc)
    return N.cdf((d(auc_a) ** 2 + d(auc_b) ** 2) ** 0.5 / 2 ** 0.5)


def simulate_fusion(auc_a, auc_b, rho=0.0, n=200000, seed=0):
    """Monte Carlo check of the ceiling. Scores are Gaussian, error correlation rho, then averaged."""
    from statistics import NormalDist
    rng = np.random.default_rng(seed)
    d = lambda auc: 2 ** 0.5 * NormalDist().inv_cdf(auc)
    y = rng.integers(0, 2, n)
    e = rng.multivariate_normal([0, 0], [[1, rho], [rho, 1]], n)
    sa, sb = d(auc_a) * y + e[:, 0], d(auc_b) * y + e[:, 1]
    fused = sa * d(auc_a) + sb * d(auc_b)        # optimal weights for independent errors
    return auc_score(y, fused)


def report(y, pred, prob_pos):
    y, pred = np.asarray(y), np.asarray(pred)
    out, support = {}, {}
    for c, name in ((1, "pneumonia"), (0, "non_pneumonia")):
        tp = np.sum((pred == c) & (y == c)); fp = np.sum((pred == c) & (y != c)); fn = np.sum((pred != c) & (y == c))
        p = tp / (tp + fp) if tp + fp else 0.0
        r = tp / (tp + fn) if tp + fn else 0.0
        f = 2 * p * r / (p + r) if p + r else 0.0
        out[name] = {"precision": p, "recall": r, "f1": f}
        support[name] = int(np.sum(y == c))
    tot = sum(support.values())
    for avg in ("macro", "weighted"):
        w = {k: (0.5 if avg == "macro" else support[k] / tot) for k in support}
        out[avg] = {m: sum(w[k] * out[k][m] for k in support) for m in ("precision", "recall", "f1")}
    out["accuracy"] = float((y == pred).mean())
    out["auc"] = auc_score(y, prob_pos)
    return out


def check_report(r, tol=0.006):
    """Consistency rules any reported table must satisfy. Our addition, used in the article.
    F1 is a harmonic mean, so it sits between precision and recall. Weighted recall equals accuracy.
    Weighted averages reveal the class share of the test set, which must be the same for every model."""
    problems = []
    for cls in ("pneumonia", "non_pneumonia"):
        p, rc, f = r[cls]["precision"], r[cls]["recall"], r[cls]["f1"]
        if not (min(p, rc) - tol <= f <= max(p, rc) + tol):
            problems.append(f"{cls}: F1 {f:.3f} outside [{min(p, rc):.2f}, {max(p, rc):.2f}]")
    if "accuracy" in r and abs(r["weighted"]["recall"] - r["accuracy"]) > tol:
        problems.append(f"weighted recall {r['weighted']['recall']:.3f} differs from accuracy {r['accuracy']:.3f}")
    return problems


def implied_positive_share(r):
    """Solve weighted recall = s * recall_pos + (1 - s) * recall_neg for the positive share s."""
    rp, rn = r["pneumonia"]["recall"], r["non_pneumonia"]["recall"]
    return (rn - r["weighted"]["recall"]) / (rn - rp) if abs(rn - rp) > 1e-9 else float("nan")


# ----------------------------------------------------------------------------
# Leakage guards. Our addition
# ----------------------------------------------------------------------------
def image_hash(arr):
    return hashlib.sha1(np.ascontiguousarray(arr).tobytes()).hexdigest()


def deduplicate(images, labels, ids):
    """Keep one copy of each pixel identical image, for example several label rows per radiograph."""
    seen, keep = set(), []
    for i, img in enumerate(images):
        h = image_hash(img)
        if h not in seen:
            seen.add(h)
            keep.append(i)
    return keep


def patient_split(ids, fractions=(0.8, 0.1, 0.1), seed=0):
    """80, 10 and 10 percent split by patient, so no patient appears in two partitions."""
    groups = defaultdict(list)
    for i, pid in enumerate(ids):
        groups[pid].append(i)
    pids = sorted(groups)
    random.Random(seed).shuffle(pids)
    n = len(pids)
    a, b = int(fractions[0] * n), int((fractions[0] + fractions[1]) * n)
    pick = lambda ps: [i for p in ps for i in groups[p]]
    return pick(pids[:a]), pick(pids[a:b]), pick(pids[b:])


# ----------------------------------------------------------------------------
# Smoke test on synthetic radiographs
# ----------------------------------------------------------------------------
def synthetic_cxr(pneumonia, size=64, rng=None):
    """Two dark lung fields. Pneumonia adds a bright, textured patch of consolidation."""
    rng = rng or np.random.default_rng()
    yy, xx = np.mgrid[0:size, 0:size] / size
    img = 0.8 - 0.4 * (np.exp(-((xx - 0.3) ** 2 + (yy - 0.5) ** 2) / 0.02) +
                       np.exp(-((xx - 0.7) ** 2 + (yy - 0.5) ** 2) / 0.02))
    img += rng.normal(0, 0.03, (size, size))
    if pneumonia:
        cx, cy = rng.uniform(0.25, 0.75), rng.uniform(0.35, 0.65)
        blob = np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / 0.006)
        img += 0.35 * blob * (1 + 0.5 * rng.standard_normal((size, size)))
    return np.clip(img, 0, 1)


if __name__ == "__main__":
    torch.manual_seed(0); np.random.seed(0); random.seed(0)
    rng = np.random.default_rng(0)
    n_pat, imgs, labels, pids = 60, [], [], []
    for p in range(n_pat):
        y = int(p % 3 == 0)                          # about a third positive, like RSNA
        for _ in range(rng.integers(1, 3)):          # some patients have two films
            imgs.append(synthetic_cxr(y, rng=rng)); labels.append(y); pids.append(p)
    imgs.append(imgs[0].copy()); labels.append(labels[0]); pids.append(pids[0])   # a duplicate label row
    keep = deduplicate(imgs, labels, pids)
    print(f"images {len(imgs)}, after removing exact duplicates {len(keep)}")
    imgs = [imgs[i] for i in keep]; labels = np.array([labels[i] for i in keep]); pids = [pids[i] for i in keep]

    tr, va, te = patient_split(pids)
    assert not ({pids[i] for i in tr} & {pids[i] for i in te}), "patient overlap"
    X = np.stack([wavelet_glcm_features(im) for im in imgs])
    knn, cfg, cv = grid_search_knn(X[tr], labels[tr], ks=range(5, 16, 2))
    p_knn = knn.predict_proba(X[te])
    print("KNN config", cfg, "cv accuracy", round(cv, 3))

    to_rgb = lambda ims: torch.tensor(np.stack(ims), dtype=torch.float32).unsqueeze(1).repeat(1, 3, 1, 1)
    x_tr, x_te = to_rgb([imgs[i] for i in tr]), to_rgb([imgs[i] for i in te])
    net = ModifiedResNet50(pretrained=False, freeze_backbone=False)
    net = train_resnet(net, x_tr, torch.tensor(labels[tr]), epochs=3, lr=1e-3, batch_size=32)
    p_res = resnet_proba(net, x_te)

    p, pred = soft_vote(p_knn, p_res)
    for name, pp in (("WG-KNN", p_knn), ("ResNet50", p_res), ("Res-WG-KNN", p)):
        r = report(labels[te], pp.argmax(1), pp[:, 1])
        print(f"{name:10s} accuracy {r['accuracy']:.3f}  AUC {r['auc']:.3f}  checks {check_report(r) or 'ok'}")

    # audit the paper's own Tables 4 and 5 with the same rules
    row = lambda p, r, f: {"precision": p, "recall": r, "f1": f}
    tables = {
        "RSNA WG-KNN":      {"pneumonia": row(.73, .70, .71), "non_pneumonia": row(.86, .88, .87), "weighted": row(.818, .823, .818), "accuracy": .83},
        "RSNA ResNet50":    {"pneumonia": row(.74, .71, .72), "non_pneumonia": row(.85, .86, .87), "weighted": row(.817, .82, .819), "accuracy": .82},
        "Kermany WG-KNN":   {"pneumonia": row(.50, .48, .45), "non_pneumonia": row(.78, .88, .83), "weighted": row(.695, .733, .704), "accuracy": .73},
        "Kermany ResNet50": {"pneumonia": row(.95, .91, .93), "non_pneumonia": row(.96, .98, .97), "weighted": row(.963, .948, .954), "accuracy": .96},
    }
    for name, t in tables.items():
        print(f"{name:17s} implied pneumonia share {implied_positive_share(t):.2f}  issues {check_report(t) or 'none'}")
    for name, a, b, rep in (("RSNA", .79, .80, .97), ("Kermany", .60, .94, .99)):
        print(f"{name:8s} ceiling with independent errors {fusion_auc_ceiling(a, b):.3f}  "
              f"simulated {simulate_fusion(a, b, n=4000):.3f}  with rho 0.5 {simulate_fusion(a, b, .5, n=4000):.3f}  reported {rep}")
    print("smoke test passed")

Where this leaves texture plus CNN fusion

Res-WG-KNN starts from a reasonable idea. Hand crafted texture statistics and learned convolutional features describe an image in different ways, and a combination might be more stable than either. The model itself is easy to build, cheap to run and transparent about its parts. Those are real virtues in a field that often reaches for complexity first.

The reported fusion results do not survive a simple check. Two branches near 0.80 AUC cannot reach 0.97 by averaging unless their mistakes are almost perfectly complementary, and nothing in the paper shows that. The more likely story is in the data handling. A label file with several rows per positive radiograph, split at random by row, would put identical images on both sides of the split and reward the two components that memorise best.

The idea still transfers. Texture descriptors remain useful in pathology, dermatology and retinal imaging, where fine patterns carry diagnostic weight and data are limited. The right way to combine them with a deep network is to measure how correlated the two models’ errors are, learn the fusion weight on held out data, and test across sites. Our analysis of LaDiNE, an ensemble approach to robust medical image classification, shows one route that takes robustness seriously.

The limitations that remain are mostly about evidence rather than architecture. No patient level split, no repeated runs, no confidence intervals, no external data, and tables whose internal arithmetic does not hold together. Each is fixable, and the authors’ own limitations section points toward several of them.

Future work should rerun the model on a deduplicated, patient disjoint RSNA split and on the official Kermany test folder, then report the branch error overlap. If the texture branch genuinely adds signal, that experiment will show it in a way no single headline number can. Until then, Res-WG-KNN is best read as a clean, reproducible baseline for texture and CNN fusion, and as a reminder that a result better than its own parts should send us first to the split.

Frequently asked questions

What is Res-WG-KNN?

Res-WG-KNN is a pneumonia classifier for chest X-rays published by Shati, Hassan and Datta in 2025. It averages the class probabilities of two models. One is a K nearest neighbours classifier that reads 16 texture features taken from a one level Haar wavelet split of the image. The other is a pretrained ResNet50 with five regularised dense blocks on top.

How accurate is Res-WG-KNN for pneumonia detection?

The paper reports 97 percent accuracy and an AUC of 0.97 on the adult RSNA dataset, and 99 percent accuracy with an AUC of 0.99 on the pediatric Kermany dataset. Each branch alone scored between 0.60 and 0.94 AUC. Those fused numbers come from one random image level split with no confidence intervals and no external test set, so they should be treated as unconfirmed.

Why do the fusion results look too good?

Averaging two probability outputs can only fix a case when at least one branch already gets it right. On RSNA the two branches score 0.79 and 0.80 AUC. Under the standard binormal model, even perfectly independent errors and optimal weights give a ceiling near 0.88, not 0.97. Several reported tables also break basic arithmetic rules, which points to an evaluation problem rather than a better model.

Can Res-WG-KNN be used to diagnose pneumonia in patients?

No. It is a research prototype tested on two public datasets with random splits. It has not been validated on an independent hospital population, has no regulatory clearance, and should not be used to diagnose anyone. Pneumonia is diagnosed by clinicians using examination, history, imaging and tests together.

What is data leakage in chest X-ray datasets?

Leakage happens when the test set shares information with the training set. In RSNA several label rows point to the same radiograph, and in Kermany several images can come from the same child. A random split by row or by image can place near copies of one patient on both sides, which inflates test scores. Splitting by patient and removing duplicate rows prevents it.

Is there code for Res-WG-KNN?

The authors did not release code. This article includes an independent PyTorch reimplementation of the wavelet texture features, the distance weighted KNN, the modified ResNet50 head and the soft vote. It also adds duplicate removal, a patient level split, and functions that audit a results table and estimate the best AUC two models can reach together.

Read the open access paper by Shati, Hassan and Datta in Intelligent Systems with Applications, or explore the RSNA challenge data used for the adult experiments.

Read the paper RSNA dataset

Shati A., Hassan G. M., Datta A. A comprehensive fusion model for improved pneumonia prediction based on KNN wavelet GLCM and a residual network. Intelligent Systems with Applications 26 (2025) 200492. Open access under a CC BY-NC-ND licence. doi.org/10.1016/j.iswa.2025.200492

This analysis is based on the published paper and an independent evaluation of its claims.

Related reading on aitrendblend

Leave a Comment

Your email address will not be published. Required fields are marked *