SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 1906.09525 · 2019

Defending Against Adversarial Examples with K-Nearest Neighbor

arXiv · PDF · Open in the Atlas

Code that ran

2 of 2 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 2 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 0 failures of our instrument; 0 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/1906.09525.json · badge: /api/ran/1906.09525.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
chawins/knn-defense canonical (classifier label)
classifier basis: classifier_2025
2 ran · 0 no recorded run
FunctionStatusWhere it lives
evaluate Ran
ran, honoured the contract we drafted
chawins/knn-defense/train_scripts/train_mnist.py
code served (permissive licence) · get_code("2f6237be378b4e1b")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

# Define a simple neural network
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(4, 8)
        self.fc2 = nn.Linear(8, 3)
    
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# Create network instance
net = SimpleNet()

# Create a simple dataloader (list of batches with inputs and targets)
dataloader = [
    (torch.randn(2, 4), torch.randint(0, 3, (2,))),
    (torch.randn(2, 4), torch.randint(0, 3, (2,))),
]

# Create loss criterion
criterion = nn.CrossEntropyLoss()

# Set device to CPU
device = torch.device('cpu')

ARGS = {
    'net': net,
    'dataloader': dataloader,
    'criterion': criterion,
    'device': device
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
train Ran
ran, honoured the contract we drafted
chawins/knn-defense/train_scripts/train_mnist.py
code served (permissive licence) · get_code("05daa04a69782bd6")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned float, ndim 0, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import logging

torch.manual_seed(0)

# Create a simple neural network
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(4, 8)
        self.fc2 = nn.Linear(8, 3)
    
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# Create train and validation dataloaders
def create_dataloader(num_batches=2, batch_size=2, input_dim=4, num_classes=3):
    data = []
    for _ in range(num_batches):
        inputs = torch.randn(batch_size, input_dim)
        targets = torch.randint(0, num_classes, (batch_size,))
        data.append((inputs, targets))
    return data

# Create logger
logger = logging.getLogger('test_logger')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Setup arguments
net = SimpleNet()
trainloader = create_dataloader(num_batches=2, batch_size=2, input_dim=4, num_classes=3)
validloader = create_dataloader(num_batches=2, batch_size=2, input_dim=4, num_classes=3)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
epoch = 1
device = 'cpu'
log = logger
save_best_only = True
best_acc = 0
model_path = './model.pt'

ARGS = {
    'net': net,
    'trainloader': trainloader,
    'validloader': validloader,
    'criterion': criterion,
    'optimizer': optimizer,
    'epoch': epoch,
    'device': device,
    'log': log,
    'save_best_only': save_best_only,
    'best_acc': best_acc,
    'model_path': model_path
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float — no output shape is stated: observe_signature.py could not observe it (call:RuntimeError)
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block

Also present in other papers' code

Of 2 samples lifted from this paper's linked repositories, 2 carry a function identity and 0 do not. Of the 2 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 2 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Robustness is an increasingly important property of machine learning models as they become more and more prevalent. We propose a defense against adversarial examples based on a k-nearest neighbor (kNN) on the intermediate activation of neural networks. Our scheme surpasses state-of-the-art defenses on MNIST and CIFAR-10 against l2-perturbation by a significant margin. With our models, the mean perturbation norm required to fool our MNIST model is 3.07 and 2.30 on CIFAR-10. Additionally, we propose a simple certifiable lower bound on the l2-norm of the adversarial perturbation using a more specific version of our scheme, a 1-NN on representations learned by a Lipschitz network. Our model provides a nontrivial average lower bound of the perturbation norm, comparable to other schemes on MNIST with similar clean accuracy.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("1906.09525")
get_code_for_paper("1906.09525")
have("1906.09525")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/1906.09525.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/1906.09525.svg)](https://syntology.ai/paper/1906.09525)

Connect an agent — have() is free.