Visual Inspection Project
Classify four families of parts from top-view images and send unfamiliar shapes to inspection, step by step.
Learning goals: build and evaluate an image classifier without leaking the test set, and add and evaluate a rejection decision for unknown shapes.
Context and objectives
The inspection problem
On a production line, a camera looks at small parts from above and produces $224\times224$ grayscale images. Each image must be assigned to one of four known families: washer, disk, bar or bracket. The images vary in rotation, position, size, background, contrast, uneven illumination, dust and noise, so the task is not trivial.
New shapes sometimes appear on the line: a part from another product, a damaged piece. A softmax classifier will still answer with one of the four families, with deceptively high confidence. The system must therefore also be able to say “I do not recognise this: send it to inspection”. Your project builds and evaluates both decisions on synthetic data generated by the code of this page.

The page assumes the course Neural networks with Keras (Dense models, convolution, pooling, MNIST). Every data generator and helper function is included here.
Objectives to carry out
- Generate a reproducible dataset of four part families, with separate training, validation and test partitions (Part 1).
- Compare an MLP and a small CNN on the same validation partition, then freeze one model before looking at the test set (Part 2).
- Report accuracy, macro F1, a confusion matrix and examples of errors (Parts 2 and 4).
- Add a rejection decision for unfamiliar shapes: compare two novelty scores calibrated with the same 5% false-rejection budget (Part 3).
- Evaluate the decision on unknown families and on a change of acquisition conditions, reporting both sides of the decision (Part 4).
- Deliver a rerunnable notebook, a short results table, figures and a discussion of limitations (Part 5).
Each part below starts with a short explanation, then proposes small exercises. An exercise gives a very light Python starting code with TO DO lines; its correction is folded just after it. Try the exercise before opening the correction.
How to work: environment and test discipline
Install tensorflow==2.21.0 numpy matplotlib scikit-learn in an isolated Python environment (checked with Python 3.12 and TensorFlow CPU 2.21). The synthetic data need no download.
Run the blocks in order in one notebook or session: later exercises reuse earlier variables. Keep the test populations untouched while choosing models and thresholds. They are used once, in Part 4, after every choice is frozen; do not tune from those results. Random seeds make runs reproducible, but hardware and library versions can change exact scores.
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, ConfusionMatrixDisplay, roc_auc_scorefrom sklearn.neighbors import NearestNeighbors# Seed for reproducibility: the same data and the same initial weights at each run.SEED = 42# Images are SIZE x SIZE pixels.SIZE = 224 # images are SIZE x SIZE pixels# Fixes the seeds of Python, NumPy and TensorFlow at once.keras.utils.set_random_seed(SEED)# Safety switch: the final test populations are used only in Part 4, when it is set to True.RUN_FINAL_TEST = False # Set True only after freezing every model and rejection choice.# Wrap NumPy arrays in a tf.data pipeline: shuffling (training only), batches and prefetching.def dataset(x, y, training=False, batch_size=128): ds = tf.data.Dataset.from_tensor_slices((x, y)) if training: # Reshuffle every epoch with a fixed seed: reproducible but not always in the same order. ds = ds.shuffle(len(y), seed=SEED, reshuffle_each_iteration=True) options = tf.data.Options() # One private thread: keeps the order of operations, hence the reproducibility. options.threading.private_threadpool_size = 1 return ds.batch(batch_size).with_options(options).prefetch(1)# Train a classifier that outputs logits and select the epoch on the validation loss.def fit_classifier(model, xtr, ytr, xval, yval, epochs, rate=0.001): # Adam optimizer; sparse cross-entropy on integer labels; from_logits=True because the last layer has no softmax. model.compile(optimizer=keras.optimizers.Adam(learning_rate=rate), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"]) # Stop when the validation loss has not improved for 3 epochs and restore the best weights. stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, restore_best_weights=True) # Training data shuffled, validation data in order; the history keeps the losses of each epoch. history = model.fit(dataset(xtr, ytr, True), validation_data=dataset(xval, yval), epochs=epochs, callbacks=[stop], verbose=0) return history# Plot the training and validation losses (left) and the validation accuracy (right) of one or several models.def draw_history(histories, title): fig, axes = plt.subplots(1, 2, figsize=(10, 4)) for name, history in histories.items(): for key, style in [("loss", "-"), ("val_loss", "--")]: axes[0].plot(np.arange(1, len(history.history[key])+1), history.history[key], style, label=name+" "+key) axes[1].plot(np.arange(1, len(history.history["val_accuracy"])+1), history.history["val_accuracy"], label=name) axes[0].set(xlabel="Epoch", ylabel="Cross-entropy") axes[1].set(xlabel="Epoch", ylabel="Validation accuracy") for ax in axes: ax.legend() fig.suptitle(title) fig.tight_layout() plt.show()
Part 1 · Generate the four-family inspection data
Washers, disks, bars and brackets
Each family is a binary mask on a $224\times224$ grid, computed from coordinates $(u,v)$ in the part’s own frame. The acquisition then rotates, shifts and scales the part, draws a background level, a contrast and an illumination tilt, adds a speck of dust and Gaussian noise. Generate 240 images per class, then split them with stratified 60/20/20 partitions: 576 training, 192 validation and 192 test images.
The same generator also defines five unknown families used later for the rejection experiments. Never train the four-class classifier on them. A new random seed gives new realizations, not a new industrial acquisition domain.

Exercise 1.1 · draw the four masks
- Build the $224\times224$ coordinate grid (
SIZEis defined in the provided code) and the squared radius $r^2=u^2+v^2$. - Complete
shape_maskfor the four known families with comparisons on $u$, $v$ and $r^2$. - Display the four masks side by side.
yy, xx = np.mgrid[-1:1:SIZE*1j, -1:1:SIZE*1j] # a SIZE x SIZE grid covering [-1, 1] x [-1, 1]u, v = xx, yy # coordinates of each pixelr2 = u**2 + v**2 # squared distance to the centredef shape_mask(family, u, v): r2 = u**2 + v**2 if family == "washer": return ... # TO DO: ring, 0.25 < r < 0.55 if family == "disk": return ... # TO DO: disc, r < 0.5 if family == "bar": return ... # TO DO: |u| < 0.7 and |v| < 0.18 if family == "bracket": return ... # TO DO: an L shape inside |u|, |v| < 0.55 raise ValueError(family)# TO DO: draw the four masks side by side with plt.imshow
Show the correction
# The four families the classifier must recognise.KNOWN = ("washer", "disk", "bar", "bracket")# Unfamiliar shapes used to choose a rejection score (Part 3).DEVELOPMENT_UNKNOWN = ("triangle", "perforated_plate") # used from Part 3 only# Other unfamiliar shapes, kept for the final evaluation (Part 4): never used to make a choice.FINAL_UNKNOWN = ("cross", "hexagon", "double_disk") # used in Part 4 only# A SIZE x SIZE grid of coordinates covering [-1, 1] x [-1, 1]; each pixel gets its own (x, y).yy, xx = np.mgrid[-1:1:SIZE*1j, -1:1:SIZE*1j]# (u, v) are the coordinates in the part's own frame; the acquisition step will rotate and shift them (Exercise 1.2).u, v = xx, yy# Squared distance to the centre: comparing r2 with a squared radius avoids a square root.r2 = u**2 + v**2# A mask is a boolean image: True where the part is, False elsewhere. It is computed from comparisons only.def shape_mask(family, u, v): r2 = u*u + v*v # Ring: between an inner radius 0.25 and an outer radius 0.55 (two comparisons on r2, combined with &). if family == "washer": return (r2 < .55**2) & (r2 > .25**2) # Disc of radius 0.5. if family == "disk": return r2 < .5**2 # Thin rectangle: |u| < 0.7 and |v| < 0.18. if family == "bar": return (abs(u) < .7) & (abs(v) < .18) # L shape: a square of half-side 0.55 from which the upper right quadrant (u > -0.15 and v > -0.15) is removed. if family == "bracket": return (abs(u) < .55) & (abs(v) < .55) & ((u < -.15) | (v < -.15)) # The five unfamiliar families are defined here once, with the same code. # Unfamiliar families, needed later for the rejection experiments: # Triangle: its half-width grows linearly from the top (v = -0.65, a point) down to v = 0.5. if family == "triangle": return (v >= -.65) & (v <= .5) & (abs(u) <= (v+.65)*.65/1.15) # Rectangle with a hole: the condition r2 > 0.2**2 removes the centre. if family == "perforated_plate": return (abs(u) < .65) & (abs(v) < .4) & (r2 > .2**2) # Union (|) of a vertical bar and a horizontal bar. if family == "cross": return ((abs(u) < .18) & (abs(v) < .65)) | ((abs(u) < .65) & (abs(v) < .18)) # The maximum of three projections on axes 60 degrees apart is smaller than 0.55 exactly inside a regular hexagon. if family == "hexagon": return np.maximum.reduce([abs(u), abs(.5*u+.866*v), abs(.5*u-.866*v)]) < .55 # Union of two discs of radius 0.3 centred at u = +/-0.32. if family == "double_disk": return ((u-.32)**2 + v*v < .3**2) | ((u+.32)**2 + v*v < .3**2) # A misspelled family name fails loudly instead of returning a wrong image. raise ValueError("Unknown family: " + family)# Display the four known masks side by side to check them visually.fig, axes = plt.subplots(1, 4, figsize=(8, 2.2))for ax, name in zip(axes, KNOWN): ax.imshow(shape_mask(name, u, v), cmap="gray") ax.set_title(name); ax.axis("off")plt.show()
The washer is a ring ($0.25<r<0.55$), the disk a disc, the bar a thin rectangle and the bracket an L shape obtained by removing one quadrant of a square. The correction also defines the five unknown families (triangle, perforated plate, cross, hexagon, double disk); you will use them only from Part 3.
Exercise 1.2 · add the acquisition effects
- In
part_images, draw a rotation angle, a small shift and a scale withrng.uniform, and rotate the grid accordingly. - Compute the mask, then draw a background, a contrast and an illumination tilt; add a small speck of dust and Gaussian noise; clip the image to $[0,1]$.
- Generate 240 images per family and display one example of each.
def part_images(families=KNOWN, n_per_class=240, seed=SEED): rng = np.random.default_rng(seed) yy, xx = np.mgrid[-1:1:SIZE*1j, -1:1:SIZE*1j] images, labels = [], [] for label, family in enumerate(families): for _ in range(n_per_class): # TO DO: draw an angle, a shift (dx, dy) and a scale with rng.uniform # TO DO: rotate and shift the grid to get u, v, then mask = shape_mask(family, u, v) # TO DO: draw a background level, a contrast and a slight illumination tilt (linear in xx, yy) # TO DO: optionally add a small bright speck of dust at a random place # TO DO: add Gaussian noise (standard deviation 0.07) and clip the image to [0, 1] image = ... images.append(image.astype("float32")); labels.append(label) return np.stack(images)[..., None], np.array(labels, dtype=np.int64)
Show the correction
# Generate n_per_class random images for each family; the seed makes the dataset reproducible.def part_images(families=KNOWN, n_per_class=240, seed=SEED): # A random generator with its own seed: calling the function twice gives the same images. rng = np.random.default_rng(seed) yy, xx = np.mgrid[-1:1:SIZE*1j, -1:1:SIZE*1j] images, labels = [], [] for label, family in enumerate(families): for _ in range(n_per_class): # Random pose of the part: rotation in [-pi, pi], shift up to 20% of the half-width, scale between 0.75 and 1.10. angle = rng.uniform(-np.pi, np.pi) dx, dy = rng.uniform(-0.20, 0.20, 2) scale = rng.uniform(0.75, 1.10) # The grid, not the mask, is rotated and shifted: the shape is then evaluated on the transformed grid, so its edges stay sharp. u = ((xx-dx)*np.cos(angle)+(yy-dy)*np.sin(angle))/scale v = (-(xx-dx)*np.sin(angle)+(yy-dy)*np.cos(angle))/scale # The mask of the part in its own frame, seen through the random pose. mask = shape_mask(family, u, v) # Random acquisition conditions: background level in [0.05, 0.25] and contrast of the part in [0.35, 0.60]. background, contrast = rng.uniform(.05, .25), rng.uniform(.35, .60) tilt = rng.uniform(-.08, .08, 2) # uneven illumination # An illumination gradient: the brightness changes linearly across the image. light = background + tilt[0]*xx + tilt[1]*yy cx, cy = rng.uniform(-.9, .9, 2) # a bright speck of dust # A small bright disc of dust at a random place (a nuisance that must not change the family). speck = .30*(((xx-cx)**2 + (yy-cy)**2) < .06**2) # Image = lighting + contrast * mask + dust + Gaussian noise (standard deviation 0.07), clipped to [0, 1], the range of a gray-level camera. image = np.clip(light + contrast*mask + speck + rng.normal(0, .07, (SIZE, SIZE)), 0, 1) images.append(image.astype("float32")); labels.append(label) # Add a channel axis (None) because Keras expects (batch, height, width, channels); labels are the family indices. return np.stack(images)[..., None], np.array(labels, dtype=np.int64)
Rotation and translation are applied to the grid, not to the mask, so the shape stays sharp at $224\times224$ pixels. The seed passed to default_rng makes the dataset reproducible; changing it produces new realizations of the same acquisition process.
Exercise 1.3 · split without leakage
- Split the images 60/40 with
train_test_split, stratified by label, then split the 40% in two equal halves (validation and test). - Print the sizes and compare them with 576, 192 and 192.
- Display two training examples of each family.
images, labels = part_images() # 240 images per family# TO DO: first split: 60 % training, 40 % rest, stratified by label (train_test_split)# TO DO: second split: the rest into 50 % validation and 50 % test, stratified# TO DO: print the sizes and compare them with 576 / 192 / 192# TO DO: show two training images of each family
Show the correction
# The full set: 240 images per family, 960 in all.images, labels = part_images()# First split: 60% for training; stratify=labels keeps the same number of each family.p_train, p_rest, t_train, t_rest = train_test_split(images, labels, test_size=.4, stratify=labels, random_state=SEED)# Second split of the remaining 40%: half for validation (choices) and half for the test (reported once).p_val, p_test, t_val, t_test = train_test_split(p_rest, t_rest, test_size=.5, stratify=t_rest, random_state=SEED)# Check the sizes: 576, 192 and 192 images (144, 48 and 48 per family).print("sizes:", len(t_train), len(t_val), len(t_test), "(expected 576 192 192)")# Look at two training examples of each family: always check the data before training.fig, axes = plt.subplots(2, 4, figsize=(8, 4))for k, name in enumerate(KNOWN): for ax, idx in zip(axes[:, k], np.flatnonzero(t_train == k)[:2]): ax.imshow(p_train[idx, ..., 0], cmap="gray", vmin=0, vmax=1) ax.set_title(name); ax.axis("off")fig.tight_layout()plt.show()
Stratification keeps 144, 48 and 48 images of each family in the three partitions. From now on p_test is not used until Part 4.
Part 2 · Compare an MLP and a CNN on parts
Recalculate dimensions for 224×224 inputs
An image has $224\times224=50{,}176$ pixels. The MLP is $50176\to32\to4$ with $(50176+1)\cdot32+(32+1)\cdot4=1{,}605{,}796$ parameters. The CNN alternates two blocks, a $3\times3$ convolution with same padding and ReLU followed by $4\times4$ max pooling: $224\times224\times1\to224\times224\times8\to56\times56\times8\to56\times56\times16\to14\times14\times16$. This flattens to 3,136 values, followed by a Dense layer of 32 units named features and four outputs: $80+1{,}168+100{,}384+132=101{,}764$ parameters.
Compare both models on the same validation partition and freeze the one with the lower validation loss before examining the test. Classification only assigns a family: it does not provide object location, orientation, a grasp point or a collision-free motion.
Exercise 2.1 · count before you build
- Compute by hand the shapes and the number of parameters of the MLP and of the CNN.
- Complete the two model builders. Give the name
"features"to the last layer before the classifier: Part 3 uses it as the representation. - Check your counts with
count_params()and look at the CNN summary.
# By hand first (shapes, then parameters):# MLP: 224x224x1 -> flatten -> Dense 32 (ReLU) -> Dense 4# CNN: 224x224x1 -> [Conv 8 filters 3x3 "same" + ReLU -> MaxPool 4] -> [Conv 16 filters 3x3 "same" + ReLU -> MaxPool 4]# -> flatten -> Dense 32 "features" (ReLU) -> Dense 4mlp_params_by_hand = ... # TO DOcnn_params_by_hand = ... # TO DOdef parts_mlp(): inputs = keras.Input((SIZE, SIZE, 1)) ... # TO DO: Flatten, then Dense(32, activation="relu", name="features") return keras.Model(inputs, ...) # TO DO: the output layer returns 4 logitsdef parts_cnn(): inputs = keras.Input((SIZE, SIZE, 1)) ... # TO DO: two Conv2D + MaxPooling2D(4) blocks, Flatten, Dense(32, name="features") return keras.Model(inputs, ...)# TO DO: compare count_params() with your hand calculations
Show the correction
# Parameters counted by hand before building anything: a Dense layer has (inputs + 1) * units weights, a convolution (kh * kw * channels_in + 1) * filters.# MLP: (50,176+1)*32 + (32+1)*4 = 1,605,664 + 132 = 1,605,796 parameters# CNN: conv1 (3*3*1+1)*8 = 80 -> 224x224x8, pool 4 -> 56x56x8# conv2 (3*3*8+1)*16 = 1,168 -> 56x56x16, pool 4 -> 14x14x16# flatten 3,136, Dense (3,136+1)*32 = 100,384, output (32+1)*4 = 132 -> 101,764# The two counts to compare with count_params().mlp_params_by_hand, cnn_params_by_hand = 1605796, 101764# Baseline: flatten the 224 x 224 image into 50,176 numbers and use one hidden layer.def parts_mlp(): inputs = keras.Input((SIZE, SIZE, 1)) h = layers.Flatten()(inputs) # The layer is named "features": Part 3 reads it as the representation of an image. h = layers.Dense(32, activation="relu", name="features")(h) # The last Dense layer has 4 outputs, one logit per family (no softmax: the loss uses from_logits=True). return keras.Model(inputs, layers.Dense(4)(h))# Two blocks "convolution + pooling": the first looks for local patterns, the second combines them.def parts_cnn(): inputs = keras.Input((SIZE, SIZE, 1)) # A 3 x 3 convolution with same padding keeps the 224 x 224 size; its 8 filters share their weights over all positions. h = layers.Conv2D(8, 3, padding="same", activation="relu")(inputs) # Max-pooling by 4 divides the height and the width by 4 and keeps the strongest response: 224 -> 56 (then 56 -> 14). h = layers.MaxPooling2D(4)(h) h = layers.Conv2D(16, 3, padding="same", activation="relu")(h) h = layers.MaxPooling2D(4)(h) # 14 x 14 x 16 = 3,136 numbers feed the Dense layer: it holds most of the 101,764 parameters. h = layers.Flatten()(h) h = layers.Dense(32, activation="relu", name="features")(h) return keras.Model(inputs, layers.Dense(4)(h))# Compare with the hand counts: the CNN has about sixteen times fewer parameters than the MLP.print("MLP:", parts_mlp().count_params(), "hand:", mlp_params_by_hand)print("CNN:", parts_cnn().count_params(), "hand:", cnn_params_by_hand)parts_cnn().summary()
The convolution has $(3\cdot3\cdot1+1)\cdot8=80$ parameters whatever the image size; the first Dense layer of the CNN dominates with 100,384 parameters. The CNN has about sixteen times fewer parameters than the MLP, because convolutions share their weights across the image.
Exercise 2.2 · train and select on validation
- Train each model with
fit_classifier(45 epochs at most, learning rate 0.001), with the same seed. - Store each history and the validation loss of the restored weights.
- Freeze the model with the lowest validation loss and plot the curves.
parts_models, parts_histories, parts_validation = {}, {}, {}for name, builder in [("MLP", parts_mlp), ("CNN", parts_cnn)]: keras.utils.set_random_seed(SEED) # same seed for a fair comparison candidate = builder() # TO DO: fit_classifier(candidate, p_train, t_train, p_val, t_val, epochs=45, rate=.001) # TO DO: store the history and the validation loss of the restored weights ...# TO DO: freeze the model with the lowest validation loss in parts_selected# TO DO: draw_history(parts_histories, "...")
Show the correction
# Dictionaries that store each trained model, its history and its validation loss.parts_models, parts_histories, parts_validation = {}, {}, {}for name, builder in [("MLP", parts_mlp), ("CNN", parts_cnn)]: # The same seed before each model: the comparison between MLP and CNN is fair. keras.utils.set_random_seed(SEED) candidate = builder() # fit_classifier trains with Adam (rate 0.001), stops early on the validation loss and restores the best weights. parts_histories[name] = fit_classifier(candidate, p_train, t_train, p_val, t_val, epochs=45, rate=.001) # The validation loss of the restored weights: this number alone chooses the model. parts_validation[name] = float(candidate.evaluate(dataset(p_val, t_val), verbose=0)[0]) parts_models[name] = candidate print(name, "parameters:", candidate.count_params(), "validation loss:", parts_validation[name])# The model with the smaller validation loss is frozen; the test set has not been used.parts_choice = min(parts_validation, key=parts_validation.get)parts_selected = parts_models[parts_choice]print("Frozen parts model:", parts_choice)# The curves show training and validation loss: a gap means over-fitting.draw_history(parts_histories, "Synthetic parts: model selection")
Early stopping restores the best validation-loss weights, so the validation loss is measured on them. The test partition has not been used. In the reference run the CNN reaches a validation loss of about 0.29, against about 0.86 for the MLP: with 576 images the MLP, which has sixteen times more parameters and no notion of translation, generalizes poorly. A different seed changes the numbers; report the seed.
Exercise 2.3 · write the classification report
- Complete
classification_report: predictions, accuracy and macro F1. - Add the confusion matrix (true classes in rows) and a gallery of up to six mistakes with their maximum probability.
- Apply it to the validation set for now.
def classification_report(model, x, y, labels, title): probabilities = tf.nn.softmax(model.predict(x, batch_size=64, verbose=0), axis=1).numpy() predicted = ... # TO DO: class with the largest probability report = {"accuracy": ..., "macro_f1": ...} # TO DO: accuracy_score and f1_score(average="macro") print(title, report) # TO DO: confusion matrix (true classes in rows) with ConfusionMatrixDisplay # TO DO: show up to six misclassified images with true label, prediction and max probability return report# Validation only for now: the test set stays untouched until Part 4.classification_report(parts_selected, p_val, t_val, list(KNOWN), "Parts, validation")
Show the correction
# A reusable report: used on validation here and on the test set in Part 4.def classification_report(model, x, y, labels, title): # The model outputs logits; softmax turns them into probabilities that sum to 1 for each image. probabilities = tf.nn.softmax(model.predict(x, batch_size=64, verbose=0), axis=1).numpy() # The predicted family is the most probable one. predicted = probabilities.argmax(axis=1) # Accuracy counts the right answers; macro F1 averages the F1 score of each family, so that no family is forgotten. report = {"accuracy": float(accuracy_score(y, predicted)), "macro_f1": float(f1_score(y, predicted, labels=np.arange(len(labels)), average="macro", zero_division=0))} print(title, report) # Confusion matrix: rows are the true families, columns the predicted ones. ConfusionMatrixDisplay(confusion_matrix(y, predicted, labels=np.arange(len(labels))), display_labels=labels).plot(cmap="Greys") plt.title(title) plt.show() # The first six mistakes: look at them with their probability. A confidently wrong prediction is still an error. errors = np.flatnonzero(predicted != y)[:6] if len(errors): fig, axes = plt.subplots(1, len(errors), figsize=(2.5*len(errors), 3.3), squeeze=False) for ax, i in zip(axes.ravel(), errors): ax.imshow(x[i, ..., 0], cmap="gray", vmin=0, vmax=1) ax.set_title(f"True {labels[y[i]]}\nPred {labels[predicted[i]]}\np={probabilities[i].max():.2f}") ax.axis("off") fig.tight_layout() plt.show() return reportclassification_report(parts_selected, p_val, t_val, list(KNOWN), "Parts, validation")
View mistakes with their probabilities: a confidently wrong prediction is still an error. The same function is applied to the test partition in Part 4.
Part 3 · Detect shapes the classifier does not know
Softmax does not detect membership in the catalogue
Softmax always distributes probability mass over the four known classes, even for an unfamiliar shape. Compare two novelty scores, larger meaning more novel:
\[s_{MSP}(x)=1-\max_c p_c(x),\qquad s_{kNN}(x)=\frac15\sum_{i\in\mathcal N_5(x)}\|\widetilde h(x)-\widetilde h(x_i)\|_2.\]The representation $h$ is the layer named features, just before the classifier. Standardize its coordinates with training means and standard deviations only, with a floor of $10^{-3}$. The neighbours are training observations, not calibration or unknown images. Neither score guarantees the detection of every unknown family.
Exercise 3.1 · is confidence evidence of membership?
- Generate the development unknowns (triangles and perforated plates).
- Compute the maximum probability of the frozen classifier on known validation images and on these unknowns.
- Plot the two histograms and comment: can a high maximum probability be trusted?
# Generate unfamiliar shapes that the network never saw: development families only.unknown_dev, dev_labels = part_images(DEVELOPMENT_UNKNOWN, n_per_class=60, seed=111)# TO DO: probabilities of the selected model on unknown_dev and on p_val (softmax of the logits; use model.predict(x, batch_size=64) for large arrays)# TO DO: compare the largest probability max_c p_c(x) for known and unknown images# TO DO: plot the two histograms. Is a high maximum probability proof of a known part?
Show the correction
# Development unknowns: triangles and perforated plates, never seen by the classifier.unknown_dev, dev_labels = part_images(DEVELOPMENT_UNKNOWN, n_per_class=60, seed=111)# Softmax probabilities of the frozen classifier on known validation images...p_known = tf.nn.softmax(parts_selected.predict(p_val, batch_size=64, verbose=0), axis=1).numpy()# ...and on the unknown ones: softmax must give a family to every image.p_unknown = tf.nn.softmax(parts_selected.predict(unknown_dev, batch_size=64, verbose=0), axis=1).numpy()# If the medians are close, the maximum probability does not tell known from unknown images.print("median max probability: known", np.median(p_known.max(axis=1)), "unknown", np.median(p_unknown.max(axis=1)))# Two overlapping histograms show that a threshold on the maximum probability rejects both kinds of images.plt.hist(p_known.max(axis=1), bins=20, alpha=.6, label="known (validation)")plt.hist(p_unknown.max(axis=1), bins=20, alpha=.6, label="unknown (development)")plt.xlabel("max probability"); plt.legend(); plt.show()
Unknown images are somewhat less confident on average, but the histograms overlap: a threshold on the maximum probability will reject some unknowns and some known images.
Exercise 3.2 · build the two novelty scores
Methodology of Part 3. The classifier is frozen. Each image receives two novelty scores, both larger when the image is more unusual: the confidence of the softmax (MSP) and the distance, in the learned feature space, to the nearest training images (kNN). A threshold $\tau$ turns each score into a decision. The three populations of the project play different roles: the training images give the reference of the kNN score, new known images calibrate the threshold, and the development unknowns choose the score.
- Extract the
featureslayer and standardize it with training statistics. - Fit a five-neighbour search on the standardized training features.
- Write
novelty_scores(x)returning both scores and the predicted class.
# The representation h is the layer named "features", just before the classifier.extractor = keras.Model(parts_selected.input, parts_selected.get_layer("features").output)h_train = ... # TO DO: features of the training images (extractor.predict, batch_size=64)h_mean, h_scale = ..., ... # TO DO: training means and standard deviations (floor 1e-3)neighbors = ... # TO DO: NearestNeighbors(n_neighbors=5) fitted on standardized h_traindef novelty_scores(x): p = ... # TO DO: softmax probabilities h = ... # TO DO: standardized features of x distances = ... # TO DO: distances to the 5 nearest training neighbours return {"MSP": ..., "kNN": ...}, p.argmax(axis=1) # TO DO: 1 - max probability, mean distance
Show the correction
# A sub-model that stops at the layer named "features": its output is the representation of the image.extractor = keras.Model(parts_selected.input, parts_selected.get_layer("features").output)# Features of the training images, the reference set.h_train = extractor.predict(p_train, batch_size=64, verbose=0)# Standardize each coordinate with TRAINING statistics only...h_mean = h_train.mean(axis=0)# ...with a floor of 1e-3 so that a nearly constant coordinate is not blown up.h_scale = np.maximum(h_train.std(axis=0), 1e-3)# Search of the 5 nearest training features for any new image.neighbors = NearestNeighbors(n_neighbors=5).fit((h_train-h_mean)/h_scale)# Two scores, both larger when an image is more unusual.def novelty_scores(x): p = tf.nn.softmax(parts_selected.predict(x, batch_size=64, verbose=0), axis=1).numpy() h = (extractor.predict(x, batch_size=64, verbose=0)-h_mean)/h_scale distances = neighbors.kneighbors(h, return_distance=True)[0] # MSP = 1 - maximum probability; kNN = average distance to the 5 nearest training features. The predicted family is returned too. return {"MSP": 1-p.max(axis=1), "kNN": distances.mean(axis=1)}, p.argmax(axis=1)
The statistics and the reference features come from training images only, so the scores of any other image are computed with a frozen reference.
Exercise 3.3 · calibrate and choose a score
- Generate 160 new known images (seed 110) and compute their scores.
- For each score, set the threshold at the 95th percentile of the known calibration scores.
- Measure the recall on the development unknowns at this common budget, and keep the score with the highest recall.
calibration, _ = part_images(n_per_class=40, seed=110) # new known imagescal_scores, _ = novelty_scores(calibration)dev_scores, _ = novelty_scores(unknown_dev)alpha = .05thresholds = ... # TO DO: for each score, the 95th percentile of the calibration scoresdev_recall = ... # TO DO: fraction of development unknowns with score > thresholdrejection_choice = ... # TO DO: the score with the highest development recallprint(thresholds, dev_recall, rejection_choice)
Show the correction
# New known images (seed 110), different from training, validation and test: they calibrate the thresholds.calibration, _ = part_images(n_per_class=40, seed=110)cal_scores, _ = novelty_scores(calibration)dev_scores, _ = novelty_scores(unknown_dev)# The false-rejection budget: we accept to reject 5% of the known images.alpha = .05# The 95th percentile of the known scores for each method: the same budget makes the two scores comparable.thresholds = {name: float(np.quantile(s, 1-alpha, method="higher")) for name, s in cal_scores.items()}# Fraction of the development unknowns whose score exceeds the threshold.dev_recall = {name: float(np.mean(dev_scores[name] > thresholds[name])) for name in thresholds}# The method that rejects the most unknowns at this budget is frozen.rejection_choice = max(dev_recall, key=dev_recall.get)# Report the threshold, the achieved false rejection and the unknown recall.for name in thresholds: print(name, "threshold:", thresholds[name], "known calibration rejection:", np.mean(cal_scores[name] > thresholds[name]), "development unknown recall:", dev_recall[name])print("Frozen rejection method:", rejection_choice)
Reject only when $s>\tau$. The empirical 95th percentile targets about 5% rejection on the calibration sample; it is not a guarantee for the future. Choose the score on development recall at this common budget, then freeze its representation, neighbour count and threshold before testing.
In the reference run, the two scores reject only about a quarter of the development unknowns at this budget (27% and 21%): noise, illumination and dust blur the difference between a known and an unknown shape. Your numbers may differ with the seed, the hardware and the library version: report the ones you obtain.
Part 4 · Evaluate rejection and acquisition shift
Report both sides of the decision
Four independent populations are now used once:
| Population | Purpose |
|---|---|
| Test partition of the four known families | Final classification report |
| New known images, seed 210 | False rejection, coverage, selective accuracy |
| Crosses, hexagons, double disks, seed 211 | Unknown families excluded from development |
| Known families with changed acquisition, seeds 212–213 | Sensitivity to illumination and noise |

Report known false rejection, unknown recall, unknown acceptance, known coverage and the accuracy among accepted known images. Selective accuracy must come with the coverage: rejecting everything is not a solution. For the AUROC, unknown examples are the positive class and increasing scores mean more novelty. Also report the recall by unknown family and the rejection rate of known images under changed acquisition: those images are not new semantic classes.
Exercise 4.1 · generate the final populations
- Report the four-class performance on the test partition with your
classification_report. - Generate the new known images, the three unknown families and the shifted known images (
.65*image+.12plus Gaussian noise). - Compute the novelty scores of the three populations.
RUN_FINAL_TEST = True # every choice is frozen: the test populations may now be used once# TO DO: report the four-class test performance with classification_report(parts_selected, p_test, t_test, ...)known_test, known_labels = part_images(n_per_class=40, seed=210)# TO DO: unknown_test from FINAL_UNKNOWN (60 per family, seed 211)# TO DO: shifted known images, seed 212: .65*image + .12 + Gaussian noise (std .10, seed 213), clipped to [0, 1]# TO DO: novelty scores of the three populations
Show the correction
# From here on the test populations are read: nothing will be tuned.RUN_FINAL_TEST = True# Final report of the classifier on the test partition.parts_test_report = classification_report(parts_selected, p_test, t_test, list(KNOWN), "Parts final test")# New known images (seed 210): they measure false rejection and selective accuracy.known_test, known_labels = part_images(n_per_class=40, seed=210)# Three unknown families excluded from every earlier choice (seed 211).unknown_test, unknown_labels = part_images(FINAL_UNKNOWN, n_per_class=60, seed=211)# Known families again (seed 212), then degraded below: an acquisition shift.shifted, shifted_labels = part_images(n_per_class=40, seed=212)# Lower contrast (0.65 x), brighter background (+0.12) and extra noise: a change of the acquisition conditions.shifted = np.clip(.65*shifted+.12+np.random.default_rng(213).normal(0, .10, shifted.shape), 0, 1).astype("float32")# Scores and predictions computed with the frozen network, reference features and standardization: nothing is refitted.scores_known, pred_known = novelty_scores(known_test)scores_unknown, pred_unknown = novelty_scores(unknown_test)scores_shift, _ = novelty_scores(shifted)
The scores are computed with the frozen network, reference features, standardization and neighbours. Nothing is refitted.
Exercise 4.2 · measure both sides of the decision
- For each score, apply its calibrated threshold to the three populations.
- Compute the false rejection of known images, the recall on unknowns, coverage, selective accuracy, AUROC and the shifted-known rejection.
- Add the recall of each unknown family.
rejection_report = {}for name, threshold in thresholds.items(): rejected_known = scores_known[name] > threshold rejected_unknown = ... # TO DO accepted = ~rejected_known rejection_report[name] = { "known_false_rejection": ..., # TO DO: fraction of known images rejected "unknown_recall": ..., # TO DO: fraction of unknown images rejected "known_coverage": ..., # TO DO: fraction of known images accepted "selective_accuracy": ..., # TO DO: accuracy among accepted known images "unknown_positive_auroc": ..., # TO DO: roc_auc_score, unknowns are the positive class "shifted_known_rejection": ..., # TO DO "recall_by_family": ..., # TO DO: one recall per unknown family } print(name, rejection_report[name])
Show the correction
# One report per score.rejection_report = {}for name, threshold in thresholds.items(): # Rejected = score above the calibrated threshold. rejected_known = scores_known[name] > threshold rejected_unknown = scores_unknown[name] > threshold # Accepted known images: the ones we would let through. accepted = ~rejected_known rejection_report[name] = { "selected": name == rejection_choice, # Known images wrongly rejected (the cost of inspection). "known_false_rejection": float(rejected_known.mean()), # Unknown images correctly rejected; "unknown_acceptance" is the complement (unknowns that pass). "unknown_recall": float(rejected_unknown.mean()), "unknown_acceptance": float(1-rejected_unknown.mean()), # Share of known images accepted; selective accuracy must be read together with this coverage. "known_coverage": float(accepted.mean()), # Accuracy among the accepted known images only. "selective_accuracy": float(np.mean(pred_known[accepted] == known_labels[accepted])) if accepted.any() else None, # AUROC: how well the score separates unknown (positive) from known images, whatever the threshold. "unknown_positive_auroc": float(roc_auc_score(np.r_[np.zeros(len(known_test)), np.ones(len(unknown_test))], np.r_[scores_known[name], scores_unknown[name]])), # Sensitivity to the change of acquisition: known images that are now rejected. "shifted_known_rejection": float(np.mean(scores_shift[name] > threshold)), # Recall of each unknown family: some shapes are closer to a known one and are rejected less often. "recall_by_family": {f: float(rejected_unknown[unknown_labels == k].mean()) for k, f in enumerate(FINAL_UNKNOWN)} } print(name, rejection_report[name])
Keep the method selected on development, even if the other score has a better final test result. In the reference run the hexagons are the least often rejected family: a regular hexagon is close to a disk in the learned features. With such image variability, neither score detects most unknown shapes: say so in your report instead of choosing a threshold that hides it. Selective accuracy can look excellent while many unknowns are accepted: read it together with coverage and unknown recall.
Exercise 4.3 · inspect mistakes and save the system
- Build the final decisions: a rejected image gets the code −1 (“send to inspection”).
- Display one accepted unknown and one rejected known image with their score and the threshold.
- Save the classifier and everything the rejection needs, then reload the classifier and check it.
decisions = pred_known.copy()# TO DO: set decisions to -1 ("send to inspection") where the selected score exceeds its threshold# TO DO: show one unknown image that was accepted (score <= threshold), with its score and the threshold# TO DO: show one known image that was rejected, if any# TO DO: save the classifier AND everything the rejection needs (h_mean, h_scale, neighbours, score, k, threshold)
Show the correction
# Final decisions on the known test images...decisions = pred_known.copy()# ...with -1 for the rejected ones.decisions[scores_known[rejection_choice] > thresholds[rejection_choice]] = -1# -1 requests inspection; it is not a fifth learned class.# Two kinds of mistakes to look at: an unknown that was accepted, and a known image that was rejected.error_sets = [ (unknown_test, np.flatnonzero(scores_unknown[rejection_choice] <= thresholds[rejection_choice]), "Unknown accepted", scores_unknown), (known_test, np.flatnonzero(scores_known[rejection_choice] > thresholds[rejection_choice]), "Known rejected", scores_known)]for data, indices, title, scores in error_sets: if len(indices): i = indices[0] plt.imshow(data[i, ..., 0], cmap="gray", vmin=0, vmax=1) plt.title(f"{title}: score={scores[rejection_choice][i]:.3f}, threshold={thresholds[rejection_choice]:.3f}") plt.axis("off"); plt.show()# Save the classifier...parts_selected.save("parts_classifier.keras")# ...reload it and check that it gives the same outputs: a saved file must be tested.reloaded = keras.models.load_model("parts_classifier.keras", compile=False)print("reloaded classifier gives the same outputs:", np.allclose(reloaded(p_val[:4]).numpy(), parts_selected(p_val[:4]).numpy(), atol=1e-5))# A deployed rejection system also needs h_mean, h_scale, the reference features,# the chosen score, k and the frozen threshold. Saving the classifier alone is insufficient.# Everything the rejection needs, saved next to the network: normalization, reference features, score, k and threshold.np.savez("parts_rejection.npz", h_mean=h_mean, h_scale=h_scale, h_reference=h_train, k=5, score=rejection_choice, threshold=thresholds[rejection_choice])
The code −1 requests an inspection; it is not a fifth learned class. A checkpoint of the classifier alone cannot reproduce the rejection decision: keep the feature normalization, reference features, score definition, neighbour count and threshold too.
Part 5 · Deliverables and limits
Build a defensible experiment
- Check the parameter counts of the MLP and the CNN against
count_params(). - Compare training and validation curves; explain how the selected model and epoch were chosen.
- Report the final confusion matrix, macro F1 and examples of errors.
- Compare MSP and feature-neighbour rejection with the same calibration budget.
- Explain one accepted unknown, one rejected known image and the effect of acquisition shift.
- Design a real-data study with acquisition lots separated across partitions and meaningful costs for false acceptance and for inspection.
Deliver a rerunnable notebook, a short results table, figures and a discussion of limitations.
What the results do not show
A hexagon can be close to a disk in the learned features. Synthetic performance does not demonstrate transfer to real cameras, materials or production lots, and a new random seed is not a new acquisition domain. The classifier gives a family, not a position, an orientation, a grasp point or a collision-free robot motion.
References and related learning
Primary documentation and research
- TensorFlow/Keras Sequential models
- Conv2D: shapes and padding
- EarlyStopping and restored weights
- Hendrycks and Gimpel: maximum-softmax baseline
- Sun et al.: out-of-distribution detection with deep nearest neighbors
The standardized five-neighbor score is a teaching adaptation, not a reproduction of the latter paper. For the shared training mechanism and MNIST, see Neural networks with Keras.