Elamur Research

Uninformed Students: Student-Teacher Anomaly Detection With Discriminative Latent Embeddings

Paper · 2020 · Paul Bergmann, Michael Fauser, David Sattlegger et al.

Summary

A product can look normal almost everywhere and still have a defect that matters. A capsule may have a fine scratch or be missing its imprint, and an inspection system needs to show where the problem is. Bergmann and colleagues ask how to make that judgment when the examples available for training show only acceptable products. Their method, Uninformed Students, uses a teacher network that already knows how to describe local image content. Student networks learn to reproduce those descriptions using defect-free images from the task at hand. At inspection time, the teacher and students describe each part of the new image, and the detector looks for places where the students have trouble with the assignment.

The paper uses two signs of trouble. The first is the distance between the teacher’s description and the students’ average prediction. The second is how much the students disagree with one another. The students all receive the same targets during training, but their separate starting points can lead them to make different predictions on unfamiliar image content. The teacher supplies the targets automatically, so training the students requires neither examples of defects nor outlines drawn around them. Running the networks densely gives an anomaly score at each pixel. Combining scores from networks that see different amounts of the surrounding image helps address defects of different sizes.

The authors test image-level detection on MNIST and CIFAR-10, where the students see a single category in training and must flag images from other categories at test time. The best reported category-averaged area under the ROC curve is 0.9935 on MNIST and 0.8196 on CIFAR-10. The more direct test of localization uses MVTec AD, an industrial inspection benchmark with object and texture images. At the common receptive field used for the main comparison, the students score 0.857 on the benchmark’s mean normalized area under the per-region overlap curve, compared with 0.790 for the strongest evaluated baseline. Combining receptive fields raises the reported mean to 0.914. Individual categories still favor different scales, which is visible in the capsule examples: the setting that picks up a fine scratch has trouble with an absent imprint.

Deep dive: Uninformed Students: Student-Teacher Anomaly Detection With Discriminative Latent Embeddings

Uninformed Students detects and locates image defects by measuring where networks trained on normal images fail to agree with a teacher. · about 37 minutes to read

The problem and its context

Recognizing a defect from examples of acceptable products

An inspection dataset can be much easier to assemble for acceptable products than for defective ones. A collection of normal images shows how the material, shape, surface, and markings usually appear. Examples of known defects would cover some of the ways a product can go wrong, and someone would need to mark their locations to train a detector directly for segmentation. The paper studies the setting in which the inspection system starts with images known to be anomaly-free. It must learn from those images and give a spatial account of what looks unfamiliar in future ones.

Here, detection and segmentation are different tasks. Detection can mean giving a single unusualness score to an entire image. Segmentation calls for a map that can distinguish the affected area from its surroundings. A detector that recognizes that a photograph contains the wrong kind of object could be effective at image-level detection and still have no way to mark a blemish on a familiar object. Conversely, a system could notice an unusual patch without having a rule for deciding whether the entire product must be rejected. The paper studies both forms of evaluation and reserves the industrial benchmark for the harder spatial problem.

The distinction also changes what counts as evidence. When an entire image belongs to another class, the unfamiliar content can dominate its visual description. In a defective product image, the anomaly may occupy very little of the view. The image can contain the expected product, with essentially its usual appearance outside the defect. A feature that summarizes the whole view may give little weight to the changed area. The authors therefore seek a local description that responds to the contents around a pixel while retaining enough context to identify a meaningful change.

The paper puts industrial inspection first and also points to active learning as a setting in which novelty can be informative. An active learning system can send unfamiliar examples for review and then use selected examples to improve its training set. This shares an interest in recognizing when an input lies outside familiar experience. The industrial experiments impose a different requirement: the system must provide useful defect locations directly from its training on normal appearances.

Why earlier approaches left room for improvement

In the literature the authors review, a common approach to anomaly segmentation is to learn to reconstruct normal images. An autoencoder compresses an input into an internal representation and attempts to reproduce it. Generative adversarial approaches also learn about normal appearance and can be used to produce a reconstruction for comparison with the input. An anomaly score can then be derived from the discrepancy between corresponding pixels. Some generative approaches instead use the probability assigned to an observation, treating low probability as evidence of novelty.

Both approaches depend on the quantity being measured. A reconstruction can deviate from an ordinary input because the reconstruction process loses detail. An error in pixel values can then highlight where the reconstruction is weak even on a normal example. Conversely, the ability to reproduce some unusual image content would reduce the error at a genuine anomaly. Approaches based on probabilities face another difficulty cited by the authors: the probabilities need to behave sensibly on unfamiliar inputs for them to be reliable indicators of novelty. The paper treats these issues as reasons to examine a different representation and decision rule.

An alternative was to start with features from an already trained network. Such features describe image content as a vector of numbers, frequently called an embedding. An embedding can encode similarities among patches that would be difficult to express through direct comparisons of their pixels. Earlier work discussed in the paper had applied pretrained features to novelty detection by learning which feature vectors were typical of normal inputs. The authors note evidence in that work that features from discriminative training, such as recognizing object categories, could be more effective for novelty detection than features learned by generative approaches.

The earlier methods differed in how much visual data they could use and where they could give a score. One image-classification approach used features from layers of VGG and fitted a one-class support vector machine. It judged whether an image was outside the known class. Work on surveillance video by Nazare and colleagues used a nearest-neighbor rule for patch descriptors and reduced their dimension before fitting the detector. A test patch was judged by its proximity to a normal training patch in the reduced feature space. Napoletano and colleagues used features from ResNet-18 and represented normal descriptors through clusters, again after reducing the dimension of the feature vectors.

When a feature extractor takes a crop and returns a single descriptor, overlapping test patches require repeated evaluations. Increasing the spacing between crop locations makes that procedure cheaper while giving scores on a coarser grid. The reviewed patch-based methods also selected subsets of the available patches during training. Their extraction and fitting procedures had to contend with the large collection of local features that even an ordinary set of inspection images can yield. The authors wanted a detector that could learn from those features with fewer restrictions on where and how densely they were sampled.

The paper discusses another precedent that computed features on whole images with earlier layers of AlexNet. This brought down the cost of extraction and allowed a Gaussian distribution to be fitted to all the normal descriptors. The authors identify two issues with that design. Pooling reduced the spatial resolution, especially for features deeper in the network. Also, fitting a unimodal Gaussian describes the feature distribution around a single center. The authors expected this to be inadequate when normal patches include multiple kinds of structure. A regular marking, a shadow near an edge, and a uniform surface can all be normal within the same product category while differing substantially in feature space.

What the paper takes from uncertainty estimation

A separate line of earlier work studied open-set recognition, in which a predictor may encounter inputs unlike those it learned to handle. Some methods obtained multiple predictions through repeated evaluations with dropout. Others used ensembles, groups of networks whose outputs can be examined individually or combined. The authors cite work that used uncertainty to flag unusual areas in retinal imagery, as well as work that used ensemble disagreement to choose images for active learning.

Those examples motivate a particular question for inspection: if several networks learn to do the same job on normal inputs, do they tend to give different answers when the input changes in a way they never encountered? Existing work cited for this purpose trained predictors on a supervised classification or segmentation task. Bergmann and colleagues instead take a fixed network’s descriptions as the common training targets. The students can learn a supervised regression objective on data that have no task-specific labels because the teacher itself provides a target at every location.

This choice changes what the system has to learn about normal appearance. A nearest-neighbor rule keeps examples of normal feature vectors and searches them. A clustering rule summarizes them by prototypes. The students learn a mapping from an image neighborhood to the feature vector that the teacher would produce there. The detector subsequently asks how the learned mapping behaves when it meets a new neighborhood. The authors expect that behavior to convey information about departures from normal appearance, and their experiments test that expectation against methods that use the same teacher’s descriptors more directly.

The method, step by step

A teacher that can describe a neighborhood

Consider a small part of a product image. The detector first needs a way to summarize the shapes and patterns around that location. The teacher produces a feature vector for this purpose. Its receptive field is the portion of the input that can influence the vector at a given location. The authors design this footprint to be square and choose its side length explicitly. In a dense feature map, each pixel has its own vector based on the corresponding local neighborhood.

The teacher learns about the appearance of natural image patches before it encounters the inspection task. The students are then trained with normal images specific to that task. Keeping these stages distinct gives the teacher and the students different experience with visual content, even though the dense networks share an architecture. The teacher retains the descriptions it learned during pretraining. The students receive only the descriptions that the teacher produces on the normal training images. Their assignment is to predict those descriptions from the image, including learning how the teacher’s outputs vary across the normal surfaces and structures they see.

From patch descriptors to a dense anomaly map

The steps in order.

From patch descriptors to a dense anomaly mapStep 1: Learn a teacher from natural image patches1. Learn a teacher from natural image patchesStep 2: Convert the teacher to dense feature extraction2. Convert the teacher to dense feature extractionStep 3: Compute descriptor statistics from normal training images3. Compute descriptor statistics from normal training imagesStep 4: Train independent students on normalized teacher targets4. Train independent students on normalized teacher targetsStep 5: Compare student predictions on a test image5. Compare student predictions on a test imageStep 6: Normalize both scores using normal validation images6. Normalize both scores using normal validation imagesStep 7: Average maps across receptive fields when using multiple scales7. Average maps across receptive fields when using multiple scales

The authors begin with a patch network, written as T̂, that accepts a crop and produces a single descriptor. They train this network using patches obtained from ImageNet. They then apply a deterministic architectural transformation, following prior work on dense feature extraction, to obtain the teacher T. The transformation allows the teacher to produce local descriptions over a whole image in one forward pass. The student networks have the resulting dense architecture too. In the classification experiments, where a whole image gets a single descriptor, the authors use the patch-sized networks instead.

Why does the transformation matter? Two crops centered on nearby pixels have much of their image content in common. Scoring them through separate calls to a patch classifier repeats work and creates a practical incentive to skip some locations. Dense evaluation shares computation and supplies a description at each location. It also lets the paper vary the area observed by each prediction while keeping the output on the input grid. The receptive field and the spacing of the resulting scores serve different purposes: the first determines which content can contribute to a score, and the second determines the resolution at which the system returns that score.

How the teacher learns its features

The teacher pretraining experiments use several objectives. One transfers visual knowledge from an existing network through knowledge distillation. Another learns distances among patches through self-supervision, which means that the training procedure constructs its own examples of similarity and dissimilarity. An additional term encourages the different coordinates of a descriptor to carry less redundant information.

In distillation, the starting network is an ImageNet-trained ResNet-18. The authors extract 512-dimensional descriptors from its fully connected layer. The smaller patch network has a descriptor size of 128, so a decoder translates its output to the space in which the larger network gives its answers. The patch network and decoder learn by comparing the translated result with the larger network’s descriptor for the same crop.

Lₖ(T̂) = ‖D(T̂(𝐩)) − P(𝐩)‖₂

Here Lₖ is the distillation loss, with the subscript identifying this objective. T̂ is the trainable patch feature extractor, 𝐩 is an image patch, and T̂(𝐩) is the descriptor it produces. D denotes the fully connected decoder in this equation. P denotes the pretrained source network, so P(𝐩) is the target descriptor for the same patch. The subtraction gives a vector of differences and ‖·‖₂ denotes its Euclidean norm. The descriptor itself is the output before decoding. The decoder gives a way to supervise this shorter representation using the larger network’s features.

The paper’s use of the word teacher refers to the network learned at this stage and subsequently held fixed. ResNet-18 supplies supervision when the patch network learns its descriptors. The transformed version of that patch network supplies supervision when the students learn normal appearances. There are thus two transfers with different purposes. The first gives the efficient, local descriptor a visual vocabulary learned from a broad collection of images. The second teaches the students how that descriptor behaves on the narrower collection of acceptable images used for anomaly detection.

Metric learning provides another way to construct the patch network. A training triplet contains an anchor crop, a positive crop made to resemble the anchor, and a negative crop taken from another image. Small translations, brightness changes, and noise can change the exact pixel values of a positive example while preserving much of the content. The feature extractor is trained to put the anchor and positive close together in its output space and to keep the negative farther away.

δ₊ = ‖T̂(𝐩) − T̂(𝐩⁺)‖₂

The distance δ₊ measures how far the two related patches lie from one another. The crop 𝐩 is the anchor, 𝐩⁺ is its positive counterpart, and T̂ maps each one to a descriptor. The subtraction is in descriptor space and the subscript on the norm specifies Euclidean distance.

δ₋ = min{‖T̂(𝐩) − T̂(𝐩⁻)‖₂, ‖T̂(𝐩⁺) − T̂(𝐩⁻)‖₂}

The distance δ₋ measures dissimilarity using whichever comparison is harder for the feature extractor. The crop 𝐩⁻ is the negative example, while 𝐩 and 𝐩⁺ are the two related examples. T̂ produces their descriptors and each norm measures a Euclidean distance. The minimum chooses the smaller of the negative crop’s distances from the anchor and from the positive. This allows the positive crop to take the anchor’s place in the negative comparison if it lies closer to the negative.

Lₘ(T̂) = max{0, δ + δ₊ − δ₋}

Here Lₘ is the metric learning loss for the patch network T̂. The positive margin δ specifies the desired gap between δ₊, the distance within the similar pair, and δ₋, the closer distance to the negative. The maximum with 0 makes the loss zero once the gap is large enough. If the negative is too close under either comparison, the term is positive and gives training a reason to separate the descriptors further.

For the reported triplet setup, the authors resize source images to square dimensions sampled from a range of 4p to 16p before choosing a crop, where p is the side length the patch network accepts. These changes in scale let crops take in different portions of the original image. The positive crop is shifted relative to the anchor, and the procedure adds Gaussian noise with standard deviation 0.1. Images in the triplet are randomly converted to grayscale with probability 0.1. The negative is another random crop, chosen from a different source image. The training signal comes from how the crops are constructed, with no need for category labels to assign the members of a triplet.

The redundancy term looks across a minibatch, the group of patches processed together in one training update. The author’s motivation is that coordinates moving together can repeat information. Discouraging correlations among coordinates encourages the network to make use of the available descriptor dimensions.

L꜀(T̂) = ∑ᵢ≠ⱼ cᵢⱼ

Here L꜀ is the descriptor compactness term for the patch network T̂. The value cᵢⱼ is the correlation matrix entry for feature dimensions i and j, computed across the descriptors from the current minibatch. The summation over i ≠ j uses entries for different dimensions, leaving out the diagonal entries that describe the correlation of each dimension with itself.

L(T̂) = λₖ Lₖ(T̂) + λₘ Lₘ(T̂) + λ꜀ L꜀(T̂)

The total pretraining objective is L evaluated for T̂, the patch feature extractor. The non-negative coefficients λₖ, λₘ, and λ꜀ control the contributions of distillation Lₖ, metric learning Lₘ, and descriptor compactness L꜀, respectively. A coefficient of 0 removes its term from the objective. The authors vary these coefficients in the classification study, then carry the teacher setting that uses distillation and compactness into their industrial inspection experiments.

What the networks see and what they return

The paper uses receptive fields with side lengths of 17, 33, and 65 pixels. The patch architectures are built from convolutions and, where used, max pooling. A convolution applies a learned filter across spatial locations. Max pooling keeps the strongest response from a local neighborhood and can reduce the size of an intermediate feature map. The patch architecture for the smallest field uses convolutions throughout. The larger variants use pooling as well as convolutions to reduce the spatial extent of the input patch before producing the final descriptor. The activation after a convolution is a leaky rectified linear unit, which retains a small slope for negative inputs. The slope used here is 5 × 10⁻³.

The patch teacher produces a descriptor of dimension d = 128 at each scale. In distillation, the decoder maps that descriptor to the 512-dimensional target. The authors train each teacher for 5 × 10⁴ iterations with Adam, an optimizer that adapts the updates to the network’s parameters using gradient information. The initial learning rate is 2 × 10⁻⁴, weight decay is 10⁻⁵, and the batch size is 64. The teacher used in student training is the dense form of the descriptor extractor, or its patch form in image-level experiments. Its weights stay fixed.

The paper formalizes the dense case by treating the image as a spatial array with channels and assigning a descriptor to each position. The spatial dimensions stay the same in the output array, while the channel count changes to the number of feature coordinates.

I ∈ ℝʷ×ʰ×ᶜ,     Sᵢ(I) ∈ ℝʷ×ʰ×ᵈ

I denotes the input image and Sᵢ is the student with index i. The set symbol ℝ indicates entries that are real numbers, and ∈ means that the array belongs to the indicated space. Its width is w and its height is h. The superscript c in the input shape denotes the image’s channel count, which the paper writes as capital C to distinguish it from a column index. The output has the same spatial dimensions and depth d. Thus a student predicts a d-dimensional vector at each row r and column c.

Each of those feature vectors concerns a neighborhood centered at the location that receives the score. A larger field can include several parts of a structure in the same prediction, so it may supply context needed to recognize whether they fit together. A smaller field gives a local change greater prominence in the pixels available to the feature extractor. At all the tested scales, the teacher’s description and the student’s prediction concern corresponding patches. Changing scale involves training another teacher and another student ensemble instead of interpreting a large-field descriptor as though it came from a small-field network.

Training students on normal images

The teacher runs on the dataset of anomaly-free images. Across the resulting descriptors, the authors compute the mean and standard deviation of each feature coordinate. These statistics define a rescaling of the targets. Subtracting the mean centers the coordinate, and dividing by the standard deviation expresses a departure in units of the normal training variation of that coordinate. Otherwise, feature coordinates that vary more in raw units could have a larger influence on a distance simply because of their scale.

zᵀ₍ᵣ,꜀₎ = (yᵀ₍ᵣ,꜀₎ − μ) diag(σ)⁻¹

Here zᵀ₍ᵣ,꜀₎ names the normalized target at row r and column c. The superscript T identifies the teacher. The vector yᵀ₍ᵣ,꜀₎ is its raw descriptor for that location, μ is the vector of coordinate-wise training means, and σ is the vector of coordinate-wise training standard deviations. The notation diag(σ) forms a diagonal matrix with those deviations as its diagonal entries. Its inverse, indicated by ⁻¹, divides each coordinate of the centered descriptor by the corresponding standard deviation.

The ensemble has M independently initialized students. The index i selects a network from the ensemble, and the authors allow M ≥ 1. Each student receives an image and predicts a descriptor around each pixel. The paper describes each prediction as the center of a Gaussian distribution with a fixed covariance. In this interpretation, the probability of a particular descriptor falls as it lies farther from the student’s prediction. The training objective for the predicted center then reduces to squared feature error.

Pr(y | p₍ᵣ,꜀₎) = 𝒩(y | μˢⁱ₍ᵣ,꜀₎, s)

Pr denotes the predictive distribution supplied by the student for a target vector y. The vertical bar on the left conditions the prediction on the patch p₍ᵣ,꜀₎, whose center is at row r and column c. The symbol 𝒩 denotes a Gaussian, μˢⁱ₍ᵣ,꜀₎ is the location predicted by student Sᵢ for that patch, and s is the fixed covariance parameter in the paper’s account. The subscript identifies the image position, while the student superscript identifies the member of the ensemble. The covariance is not a separate prediction made for each pixel.

L(Sᵢ) = (1/(wh)) ∑₍ᵣ,꜀₎ ‖μˢⁱ₍ᵣ,꜀₎ − zᵀ₍ᵣ,꜀₎‖₂²

The loss L(Sᵢ) is the training objective for student Sᵢ on an image of width w and height h. The sum runs over its row and column positions r and c. The vector μˢⁱ₍ᵣ,꜀₎ is the student’s prediction and zᵀ₍ᵣ,꜀₎ is the teacher’s normalized target at the same location. The squared Euclidean norm ‖·‖₂² adds the squared discrepancies across feature coordinates. The factor 1/(wh) averages the loss across the pixels.

Every student gets the same regression task. A normal example repeatedly constrains each network to match the teacher on the types of patches represented in the training set. On image content outside that experience, the training loss gives no direct instruction about what to predict. Different random initializations make it possible for the students to settle on functions that agree on the familiar patches and diverge elsewhere. The paper turns this possibility into a measurement. It also keeps a direct check against the teacher, since the students could make much the same mistake on a patch and display little disagreement.

For MVTec AD, the students train for 100 epochs using images resized to 256 pixels in width and height. The batch size is 1 image, but the loss for that image draws on local predictions across its spatial grid. The authors use Adam with initial learning rate 10⁻⁴ and weight decay 10⁻⁵. They train ensembles with M = 3 at the tested scales. In the image-level MNIST and CIFAR-10 study, the teacher and each of the five students produce a single descriptor from a resized image, with p = 33. The student’s regression objective in that setting concerns the feature vector for the whole input.

The two scores at inspection time

On a new image, the fixed teacher and each student are evaluated on the same input. At each position, the authors form an equally weighted mixture of the students’ predictive distributions. The mean of this mixture is the average of their predicted centers. The paper compares that average with the teacher to capture a shared deviation from the target, then measures how much the students spread out around their average.

μ₍ᵣ,꜀₎ = (1/M) ∑ᵢ₌₁ᴹ μˢⁱ₍ᵣ,꜀₎

The vector μ₍ᵣ,꜀₎ is the mixture mean for row r and column c. The unindexed μ in target normalization is a different quantity, namely the teacher’s training mean. Here M is the number of students, i indexes them from 1 through M, and μˢⁱ₍ᵣ,꜀₎ is the center predicted by the corresponding student. Dividing the sum by M gives each student equal weight.

e₍ᵣ,꜀₎ = ‖μ₍ᵣ,꜀₎ − zᵀ₍ᵣ,꜀₎‖₂²

The regression error e₍ᵣ,꜀₎ is the first anomaly score for row r and column c. The term μ₍ᵣ,꜀₎ is the ensemble’s mean prediction and zᵀ₍ᵣ,꜀₎ is the normalized teacher descriptor for the test image at that position. The squared norm measures how far those vectors are from one another. A single student can already supply an error score because its output can be compared directly with the teacher.

v₍ᵣ,꜀₎ = (1/M) ∑ᵢ₌₁ᴹ ‖μˢⁱ₍ᵣ,꜀₎‖₂² − ‖μ₍ᵣ,꜀₎‖₂²

The quantity v₍ᵣ,꜀₎ is the second anomaly score, the predictive disagreement at row r and column c. The sum averages the squared norms of the individual predictions μˢⁱ₍ᵣ,꜀₎ across M students indexed by i. The norm in the subtracted term is the squared norm of their average μ₍ᵣ,꜀₎. The difference measures how spread out the predictions are around that average. If the student vectors coincide, the difference is zero even if the common prediction is far from the teacher.

The two measurements can register different behaviors on the same patch. Several similar predictions can all miss the target, giving a high regression error alongside low disagreement. Student predictions can also spread out on either side of the teacher’s descriptor, in which case averaging them can leave a small error in spite of substantial disagreement. The combined score gives both patterns a way to register. The authors estimate the typical level and spread of each measurement on a separate collection of anomaly-free validation images before adding them.

ẽ₍ᵣ,꜀₎ + ṽ₍ᵣ,꜀₎ = (e₍ᵣ,꜀₎ − eμ)/eσ + (v₍ᵣ,꜀₎ − vμ)/vσ

The tilde marks the normalized forms ẽ₍ᵣ,꜀₎ and ṽ₍ᵣ,꜀₎ of the raw error e₍ᵣ,꜀₎ and disagreement v₍ᵣ,꜀₎ at row r and column c. The values eμ and vμ are their respective means across the normal validation images, and eσ and vσ are their respective standard deviations there. Each term subtracts its normal baseline and scales the remainder by its own spread. The sum on the left is the anomaly score at that location. This validation normalization serves a different purpose from the training normalization of the teacher descriptors. It puts the two final measurements on comparable scales after the students have been trained.

Combining receptive fields

A patch can cover a defect while describing mostly ordinary image content. This is particularly likely when a fine flaw occupies a small part of a large receptive field. The descriptor of the whole neighborhood may then stay close to something the students learned to predict. For a missing structure, the difficulty can run the other way. A patch with uniform material may look normal by itself, and the anomaly becomes visible when the field is large enough to show that a marking should have been present in that part of the object.

The authors handle both cases by training a teacher and a student ensemble for each selected receptive field. Each scale gives a dense anomaly map on the same input grid. They combine the maps after calibrating the regression error and disagreement at each scale on normal validation images. The approach changes the size of the viewed neighborhood while preserving image resolution within the dense scoring procedure.

(1/L) ∑ₗ₌₁ᴸ (ẽ⁽ˡ⁾₍ᵣ,꜀₎ + ṽ⁽ˡ⁾₍ᵣ,꜀₎)

This expression is the multiscale score for row r and column c. L is the number of teacher–ensemble pairs, and l indexes the scales from 1 through L. The superscript ⁽ˡ⁾ identifies the pair that supplied the normalized regression error ẽ and the normalized disagreement ṽ. The terms for all scales are added at the corresponding location and divided by L. The result remains a spatial score map, which can be thresholded to get a predicted defect region or evaluated across thresholds as in the paper.

Experiments and results

One-class detection on MNIST and CIFAR-10

The classification experiments give the method an initial test in a setting where normality has a straightforward definition. For each run, the students train on images from a single category. At evaluation, images from the other categories are anomalous relative to that run. In MNIST, training on one digit means learning how the teacher describes instances of that digit, then trying to rank the other digits as unfamiliar. In CIFAR-10, the same procedure uses object categories. The authors resize each image to the patch input size and obtain one teacher descriptor and one prediction per student. The anomaly score therefore belongs to the whole image.

The metric is the area under the receiver operating characteristic curve, reported as ROC AUC. To trace the curve, the evaluator varies the score threshold used to flag an image and measures how frequently it flags anomalous images and how frequently it raises false alarms on normal images. The paper computes the area for each choice of normal category and reports the average across those choices. These averages summarize test performance over several distinct normality tasks. They do not supply a single operating threshold shared across the categories.

The authors compare the students with methods fitted to the teacher’s descriptors. The nearest-neighbor baseline uses distance to the closest normal training feature. K-Means learns centers of clusters of normal features and uses distance to the nearest center, with 10 centers in these experiments. The one-class support vector machine uses a radial basis function kernel to learn a boundary for familiar features. The shallow methods use features after principal component analysis, or PCA, a projection that reduces the number of coordinates needed to represent the training variation. The image-level experiment allows the nearest-neighbor method to retain a feature from every training image.

The other feature-based baselines use autoencoders. The deterministic autoencoder assigns higher anomaly scores when it reconstructs a teacher descriptor poorly. The variational autoencoder scores using reconstruction probability, which the authors estimate with five passes through the network. The paper also reports OCGAN, which learns directly from input images. These comparisons therefore include both alternatives to student regression given teacher features and an approach that learns its own representation of normal images.

One-class methods on CIFAR-10 by category-averaged ROC AUC

The strongest student configuration leads the comparison, with nearest-neighbor scoring close behind.

One-class methods on CIFAR-10 by category-averaged ROC AUCStudent ensemble with distillation and compactness (this paper): 0.8196Student ensemble with distillation andcompactness (this paper)0.81961-NN: 0.81891-NN0.8189Deterministic feature autoencoder: 0.7898Deterministic feature autoencoder0.7898K-Means: 0.7592K-Means0.7592Variational feature autoencoder: 0.7502Variational feature autoencoder0.7502One-class SVM: 0.7388One-class SVM0.7388OCGAN: 0.6566OCGAN0.6566
The numbers
System or settingROC AUC
Student ensemble with distillation and compactness (this paper)0.8196
1-NN0.8189
Deterministic feature autoencoder0.7898
K-Means0.7592
Variational feature autoencoder0.7502
One-class SVM0.7388
OCGAN0.6566

On CIFAR-10, the strongest student setting records a category-average ROC AUC of 0.8196. The nearest-neighbor result of 0.8189 is close enough to make this a different comparison from the later industrial benchmark. The scores also vary by normal category. For frog, the same student setting gives a per-category ROC AUC of 0.892, compared with 0.876 for nearest neighbor. For truck, it gives 0.848, compared with 0.882 for nearest neighbor. With dog as the normal category, the student setting gives 0.793 and nearest neighbor gives 0.797. The higher student average holds across the set of category tasks, while the preferred detector depends on the task in an individual category.

On MNIST, the best category-average ROC AUC for the students is 0.9935, reached by more than one choice of teacher objective. The deterministic feature autoencoder scores 0.9832, nearest neighbor scores 0.9753, and OCGAN scores 0.9750 on the same category-averaged metric. The per-digit results help explain the high overall scores. When the normal digit is 1, the best reported student configurations give 0.999 per-category ROC AUC, and the deterministic feature autoencoder and OCGAN both also reach 0.999. The student advantage on the mean is easier to understand by looking at categories with more room for a ranking to improve. When 8 is normal, for example, the student configuration subsequently selected for MVTec AD scores 0.986, against 0.978 for the deterministic feature autoencoder and 0.968 for nearest neighbor.

The paper’s visualization illustrates what the two scores might respond to. The students in that example train on MNIST images labeled 0. The authors project selected teacher descriptors and student predictions into 2D with multidimensional scaling, which tries to retain relative distances from the original feature space. They show the teacher’s descriptor, the average student prediction, and a circle that grows with disagreement. For displayed normal examples, the average lies near the teacher and the students tend to cluster. Displayed examples from other digits can show both a larger gap from the teacher and a wider spread among the students. A histogram accompanies the selected examples with scores for the dataset. The quantitative classification results use the anomaly scores themselves, while the projection helps make their ingredients visible.

How MVTec AD tests localization

MVTec AD contains over 5000 high-resolution images across ten object categories and five texture categories. In this setting the students train on acceptable images, and test performance depends on where the method assigns high scores within an image. A normal texture may contain variation across its surface without a defect, and a normal object may have edges and markings that differ markedly from the surrounding material. For a localization system, those variations are part of what it has to learn before it can sensibly highlight a deviation.

The paper evaluates images resized to 256 pixels along each axis. The teacher pretraining remains independent of the evaluation datasets. For the main comparison on MVTec AD, the authors use the teacher trained with distillation and descriptor compactness, and compare methods at p = 65. A separate experiment then asks how the result changes with receptive field size and when the scores from all tested sizes are combined.

The localization measure starts with per-region overlap, abbreviated PRO. At a given threshold, every pixel with a high enough anomaly score is flagged. For each connected defect region in the ground truth, the evaluator measures the fraction of that region covered by flagged pixels. The fractions are averaged with equal weight per region. This matters when a large defect has many more pixels than a small one. With a pixel-weighted measure, getting a single large region right can overshadow a series of small missed defects. PRO gives a small region the same influence as a large one in the overlap calculation.

To stop a detector from getting credit for covering every defect simply by marking most of the image, the procedure also measures the rate at which normal pixels are flagged. The threshold is varied to trace overlap as a function of the average false-positive rate per pixel. The paper integrates the curve up to 30% false positives and normalizes the area to a maximum of 1. Its comparison reports the normalized area for each category and the mean over categories. A high area means useful overlap over the scored range of false-positive rates. A fixed threshold for a particular inspection station would be a separate choice.

What the baselines test on industrial images

Some comparisons keep the teacher’s descriptor and change the way the detector learns what is typical. The nearest-neighbor baseline on MVTec AD uses a dictionary of 5000 normal vectors. For K-Means and the one-class support vector machine, the authors sample 50,000 training vectors from the teacher’s maps. PCA retains 95% of the variance in the feature reduction for the shallow approaches. Those choices reflect a practical difference from the small image-level benchmarks. Dense feature extraction yields many positions per image, so keeping every training vector and testing it against every new patch is a different proposition from keeping one vector per training image.

The feature autoencoders are trained using the full pool of teacher descriptors. Each training batch contains 512 sampled vectors, and the autoencoders are trained for 100 epochs. They use fully connected layers and judge anomalies through reconstruction of a descriptor. This gives another point of comparison for the student approach. Both can use the teacher’s dense representation throughout training, while their predictions answer different questions. The autoencoder attempts to reconstruct a feature vector presented as its input. The students try to infer that vector directly from the image patch. The authors also compare with a CNN-Feature Dictionary, an autoencoder that uses structural similarity, and AnoGAN from the benchmark literature. The dictionary uses overlapping patches evaluated with a stride of 4 pixels in this experiment.

MVTec AD methods at receptive field 65 by mean normalized PRO area

Student regression leads the evaluated systems, followed by the deterministic feature autoencoder.

MVTec AD methods at receptive field 65 by mean normalized PRO areaStudent ensemble (this paper): 0.857Student ensemble (this paper)0.857Deterministic feature autoencoder: 0.790Deterministic feature autoencoder0.790SSIM autoencoder: 0.694SSIM autoencoder0.6941-NN: 0.6401-NN0.640Variational feature autoencoder: 0.639Variational feature autoencoder0.639CNN-Feature Dictionary: 0.515CNN-Feature Dictionary0.515One-class SVM: 0.479One-class SVM0.479AnoGAN: 0.443AnoGAN0.443K-Means: 0.423K-Means0.423
The numbers
System or settingNormalized PRO area up to 30% false positives
Student ensemble (this paper)0.857
Deterministic feature autoencoder0.790
SSIM autoencoder0.694
1-NN0.640
Variational feature autoencoder0.639
CNN-Feature Dictionary0.515
One-class SVM0.479
AnoGAN0.443
K-Means0.423

The student ensemble achieves the highest mean normalized PRO area at p = 65, with 0.857 against 0.790 for the deterministic autoencoder. Nearest neighbor, at 0.640, has the strongest mean among the shallow methods. The result differs from its near tie with the students on CIFAR-10. Here the comparison involves a much larger supply of local descriptors and a dictionary of sampled features. The paper attributes the weaker shallow results to the difficulty of representing the normal distribution in this setting. The scores describe the full pipelines tested, including their sampling and reduction choices.

The average has some clear exceptions at the category level. On grid, the structural similarity autoencoder reaches 0.849 normalized PRO area against 0.819 for the students. On transistor, the deterministic feature autoencoder has 0.728 and the students have 0.701. The student ensemble and deterministic feature autoencoder both achieve 0.819 on leather. Other categories show why the student mean leads. The students score 0.928 on screw, where the deterministic feature autoencoder gives 0.754 and the structural similarity autoencoder gives 0.887. For zipper, the students reach 0.933 and the deterministic feature autoencoder gives 0.839. Each figure is the category’s normalized PRO area under the same false-positive cap.

The visual results show how maps behind these numbers look on selected examples. The paper places an input, a ground-truth defect mask, and a map of anomaly scores alongside one another. Its additional examples span object and texture categories and include discoloration, contamination, and structural defects. Such figures allow a reader to inspect whether high scores follow a defect, spread into nearby normal areas, or pick up scattered responses elsewhere. The normalized PRO area aggregates performance over regions and thresholds. The individual maps supply the spatial detail behind that aggregation for the examples shown.

What the ablations show

The training objective changes the teacher’s usefulness

The classification experiment varies the terms used to learn the teacher descriptor. The goal is to test what type of pretraining produces useful targets for the students once they learn the normal category. This is a comparison between teacher objectives within the student framework. The same image-level setup provides the downstream test, and the resulting measure is the student detector’s category-average ROC AUC.

The authors report that distilling the pretrained ResNet-18 tends to work better than learning patch features by triplets alone, and that the descriptor compactness term can improve results. The configuration selected for MVTec AD sets the distillation and compactness weights to 1 and the metric learning weight to 0. It has the highest reported mean ROC AUC on CIFAR-10, at 0.8196, and shares the best reported MNIST mean, at 0.9935. The remaining teacher settings give CIFAR-10 means of 0.8035, 0.7940, and 0.8021. On MNIST the corresponding reported means are 0.9926, 0.9935, and 0.9917. The choices have more room to matter in the CIFAR-10 comparison, where the performance of the different configurations is spread across a broader range.

These results concern the type of visual representation that makes the prediction task informative. If two patches differ in a way that the teacher scarcely represents, the students have little reason to produce a large teacher-relative error. If a teacher spreads the available feature dimensions across useful visual distinctions, the regression task can expose changes that would otherwise be difficult to register. The experiments support the authors’ choice of objective for the later benchmark. They also show that other objectives can yield competitive results in the image-level setting, especially on MNIST. The choice remains a result for the tested data and training procedure.

The useful receptive field depends on the defect

The MVTec AD scale study holds onto the teacher and student scoring design and changes their receptive field. Each single-scale system produces its own dense map. The multiscale system averages the anomaly scores from the tested fields. Because the paper applies the same regional overlap measure to the four configurations, this experiment shows how the spatial extent of the input to each local descriptor affects the resulting maps.

Receptive-field settings on MVTec AD by mean normalized PRO area

Combining scales gives the highest mean, and the middle field leads the individual scales.

Receptive-field settings on MVTec AD by mean normalized PRO areaReceptive field 17: 0.866Receptive field 170.866Receptive field 33: 0.900Receptive field 330.900Receptive field 65: 0.857Receptive field 650.857Multiscale ensemble (this paper): 0.914Multiscale ensemble (this paper)0.914
The numbers
System or settingNormalized PRO area up to 30% false positives
Receptive field 170.866
Receptive field 330.900
Receptive field 650.857
Multiscale ensemble (this paper)0.914

The middle field of 33 gives the best single-scale mean, 0.900 normalized PRO area. The multiscale score reaches 0.914 on the same metric. The mean result matters because one combination can accommodate a range of patterns across categories. The category results matter because they show which observations that average represents. Consider cable, where normalized PRO area goes from 0.671 at p = 17 to 0.865 at p = 65, with the multiscale result at 0.818. On wood, the smallest field gives 0.943, the largest gives 0.725, and the multiscale system gives 0.911. Those opposite patterns are consistent with the authors’ account of local detail and broader context.

Several categories show the practical appeal of combining fields. On bottle, the multiscale normalized PRO area is 0.931 and the strongest single-scale result is 0.918 at p = 65. On capsule, the combined result is 0.968, while the strongest single-scale value is 0.963 at p = 33. On grid, combining fields yields 0.952, compared with 0.949 for the best single field of p = 33. The gains are reported on the category metric, which aggregates over the defects and thresholds evaluated in each case. Some categories favor a single field, as cable and wood demonstrate.

The capsule illustration gives a closer view because it shows two kinds of defects within the same category. A field of 17 pixels makes the scratch conspicuous in the predicted map. As the receptive field gets larger, more ordinary surface contributes to each descriptor and the scratch becomes harder to distinguish. The missing imprint presents a different pattern. A very local view can see ordinary-looking material where some fragment of the imprint is absent. A wider view gives the descriptor access to more of the expected structure and improves the response to the omission. The combined map brings information from those different descriptions to corresponding pixel locations.

The scale results establish a tradeoff for the implemented systems. Receptive field size changes together with the network architecture used to produce that field, and the combined setting has access to several trained pairs. The comparison measures what happens when those settings are used as designed. It also explains why selecting a scale using only a category average can mask important differences among defect types within the category.

The analyses give different evidence about the scores

The plotted MNIST examples explain why teacher-relative error and disagreement can appear together. Projected predictions for an unfamiliar digit can lie both farther from the teacher and farther apart from one another. The capsule example explains a different mechanism: the descriptor can represent a defect strongly or weakly depending on the field it observes. The classification visualization concerns the students’ output behavior, while the scale experiment directly compares changes in localization performance.

The paper derives the error and disagreement scores separately and gives a reason to combine them, then evaluates the combined detector in the main benchmark comparisons. It does not report a benchmark-wide comparison of error alone, disagreement alone, and the sum under otherwise identical settings. The quantitative ablations therefore establish the effects of the tested teacher objectives and scale choices. The separate contribution of disagreement to the reported segmentation results remains unmeasured by those comparisons.

Limitations

Limits identified by the authors

The authors point out that a defect can be too small in relation to a network’s receptive field. If ordinary content dominates the neighborhood, the teacher may describe it in a way that is still familiar to the students. The analysis of scale and the capsule examples show how this can affect localization even when a map contains a score at every pixel. Increasing spatial detail in the output grid alone does not give the feature extractor a stronger response to a small input change. The multiscale design addresses this issue by changing what the descriptor sees, and the category results show why the choice still matters.

The authors also describe a limit of the evaluation measure. At high false-positive rates, even excellent overlap with the annotated defect regions can be obtained by flagging broad areas that should have been left alone. They therefore restrict the normalized PRO area to the portion of the curve up to a 30% average per-pixel false-positive rate. This restriction is part of what the metric measures. Its score reflects performance across a defined range of thresholds and normal-pixel error rates.

The training setup itself places a condition on what the detector can learn. The students receive normal images and are expected to generalize in a particular way when the image contains something else. The authors present this behavior as the motivation for the method. They test it with different one-class tasks and with annotated test defects. The premise remains an empirical expectation about the learned predictions. How sharply the students react depends partly on whether the appearance of a new patch was constrained by what they saw in training.

Limits visible in the experimental design

A careful reading of the setup distinguishes the lack of defect annotation in student training from the prior information used elsewhere. Normal examples have to be selected for the task. The teacher is pretrained on natural image patches, and the teacher selected for MVTec AD inherits features from an ImageNet classification network through distillation. The normalization of the anomaly scores also uses anomaly-free validation images. The paper studies learning an inspection task without labeled defect examples. It does not evaluate what would happen if the training or validation data contained undetected defects, or if normal appearance shifted after training.

Anomaly evidence is also tied to the information the teacher retains. The students predict a feature vector describing a local patch, so an unusual change that the teacher maps to a familiar representation can escape detection. The scale study shows a concrete version of this problem. A small scratch can have little influence on a descriptor for a broad neighborhood even when the pixels with the scratch are inside the field. Conversely, a harmless appearance absent from the normal training set can pose a difficult regression problem. The anomaly score measures a departure from the behavior learned on normal examples, while the connection between that departure and a defect is evaluated through the benchmark labels and masks.

The variance term should be read as disagreement in feature prediction. A fixed covariance is used in the account of each student’s output, and the reported disagreement depends on the dispersion of the student predictions. This gives the system a practical numerical signal. The experiments do not establish that a given variance corresponds to a calibrated probability of a defect. In the single-student case, the comparison with the teacher remains available, whereas the disagreement vanishes. A constant disagreement score supplies no spread for the validation normalization used in the ensemble detector.

The comparison with shallow methods combines effects of their scoring rules and the constraints of their implementations. On MVTec AD they use PCA and sampled features, while the students train densely. The reported comparison is meaningful for those complete procedures. It does not identify how much of the difference would come from student regression if all alternatives were given identical full-resolution, unreduced training descriptors. The deterministic feature autoencoder comparison narrows part of that gap by using all available descriptors, but still changes the architecture and the objective along with the anomaly score.

The paper uses a threshold-independent ranking measure for classification and a threshold-integrated overlap measure for segmentation. Both are useful for comparing methods before a decision threshold has been picked. The experiments do not specify a fixed operating threshold for deciding where a factory should draw a defect mask or when it should reject a product. Even within MVTec AD, categories and receptive fields show different score behavior. The preferred operating point would depend on the importance of missed defects and false alarms in the particular application, a tradeoff the benchmark metrics summarize only over their stated ranges.

Finally, the experiments evaluate a resized representation of MVTec AD. A dense map preserves the grid of that resized input, and receptive fields are measured in pixels on that grid. The reported results therefore measure localization at the resolution used in the study. They do not measure what the same configurations would achieve on the original images at their native dimensions or how accuracy and computation change when those dimensions are retained. The dense transformation provides the architectural means to avoid separately evaluating overlapping crops. The benchmark scores provide evidence about detection and localization, with no direct measurement of an inspection system’s runtime under operating conditions.

What came after

Later papers cite Uninformed Students in both visual anomaly detection and knowledge distillation. The original method gives teacher-derived targets two roles. First, distillation transfers visual features into a smaller extractor. Later, a fixed extractor provides a reference against which the students’ performance on new images is measured. Work about finding anomalies and work about transferring behavior between networks both have a point of contact with the paper, through different stages of its method.

EfficientAD is the closest of these later works in subject. Its focus on efficient and accurate visual anomaly detection returns to a practical question already present in Uninformed Students. A local detector needs to compute enough evidence to localize a defect at useful resolution, and repeated feature extraction over overlapping crops can make dense scoring expensive. Bergmann and colleagues addressed that issue by converting a patch descriptor into a dense teacher and by predicting its features with dense students. The citation places EfficientAD in the same line of work on the accuracy and cost of visual inspection. EfficientAD

The work on robust temporal feature magnitude treats anomaly detection in video and makes weak supervision part of its formulation. Its title identifies a different source of evidence, the magnitude of features over time. Uninformed Students assesses spatial neighborhoods in still images and trains on examples selected as normal. This later citation connects the paper to a setting in which the time dimension is part of the anomaly signal and the task is framed around a different kind of supervision. Weakly-supervised Video Anomaly Detection

The design-space exploration of pretraining distillation cites the paper in connection with the other use of a teacher. Its subject is distillation during pretraining for large language systems. In the visual paper, the comparable stage is learning what an efficient patch extractor should represent through the outputs of a separately pretrained network. Student disagreement enters the inspection method only after that extractor has been fixed. The relation here concerns the choice of how to transfer behavior from a source network to a learner. Pre-training Distillation

Sparse Logit Sampling also addresses knowledge distillation and specifies speed as its aim. Its title identifies the part of the transfer process it studies: sampling logits, the numerical scores used as a training signal, sparsely. The corresponding transfer in Uninformed Students matches decoded patch descriptors to visual features from ResNet-18. The two problems share a question about how to supply useful teacher information efficiently, while the kind of output that carries that information differs. The citation connects the visual paper’s pretraining stage to later work on the cost of providing distillation targets. Sparse Logit Sampling

Cite

Cite as Paul Bergmann, Michael Fauser, David Sattlegger and Carsten T. Steger. 2020. Uninformed Students: Student-Teacher Anomaly Detection With Discriminative Latent Embeddings. IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1109/cvpr42600.2020.00424 · arXiv 1911.02357

@inproceedings{bergmann2020uninformed,
  title = {{Uninformed Students: Student-Teacher Anomaly Detection With Discriminative Latent Embeddings}},
  author = {Paul Bergmann, Michael Fauser, David Sattlegger and Carsten T. Steger},
  booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings},
  year = {2020},
  doi = {10.1109/cvpr42600.2020.00424},
  eprint = {1911.02357},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1109/cvpr42600.2020.00424}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bergmann-2020-uninformed-students-student-teacher-anomaly/