AI Wiki中文/EN

Image classification

图像分类

Train a tiny classifier, expose a 100%-to-0% distribution-shift failure, and compare it with explicit nonlearned baselines.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with an experiment

A classifier scores 100% on training images and 100% on fresh validation images. Move the objects to another part of the frame and it gets every test image wrong. Did training fail? In the experiment below, training did exactly what its data and representation encouraged.

The task is deliberately small: label an eight-by-eight image as a horizontal stripe or a vertical stripe. Training and validation use stripe positions one and two; a separate shifted test uses positions five and six. Each split contains 48 independently noised observations of these underlying patterns. Fresh noise at familiar positions is not evidence that a model has learned the whole concept of orientation.

Image classification assigns labels to images. Before choosing a network, define what a label means, what counts as one example, and which changes should preserve that label. A product type, a scene category and the presence of several objects are different prediction problems, even if all begin with an RGB array.

Four stripe images: horizontal and vertical stripes are correctly classified at a familiar position and reversed at a shifted position.

A/B use a familiar stripe position; C/D move the stripe while preserving its orientation label. Here y is the true label, the hatted y is the prediction, and p₁ is the model’s vertical-stripe probability. These four displayed images omit noise for clarity and use the same fitted model; the program’s split statistics use independently noised images.

The model and its assumptions

An image array has a coordinate convention, dimensions, channels, numeric range and label mapping. These are part of the model’s input contract. For example, the official CIFAR description specifies 32-by-32 color images and a 50,000/10,000 training/test split for CIFAR-10. Its automobile/truck definitions even exclude pickup trucks. A label is an annotation rule, not an exhaustive definition of the world. We use no CIFAR images in this experiment. CIFAR dataset description

For our binary problem, flatten each image into xi∈R64x_i\in\mathbb R^{64} and let yi=1y_i=1 mean vertical. Logistic regression computes a score and probability:

zi=wTxi+b,pi=11+e−zi.z_i=w^Tx_i+b,\qquad p_i=\frac{1}{1+e^{-z_i}}.

The mean binary cross-entropy can be written in a numerically stable form:

L=1N∑i=1N[log⁡(1+ezi)−yizi].L=\frac1N\sum_{i=1}^N\left[\log(1+e^{z_i})-y_i z_i\right].

Differentiating the log term gives the sigmoid, so the gradients used in the program are:

∇wL=1N∑i(pi−yi)xi,∂L∂b=1N∑i(pi−yi).\nabla_wL=\frac1N\sum_i(p_i-y_i)x_i,\qquad \frac{\partial L}{\partial b}=\frac1N\sum_i(p_i-y_i).

A weight attached to one pixel always refers to that location. Nothing in this linear representation requires the learned rule to follow a stripe when it moves. Convolution shares local filters, but even a convolutional model needs a suitable architecture, data and evaluation; the word CNN is not a guarantee of invariance.

The decision rule here predicts vertical when p is at least 0.5. Its confusion matrix has true labels in rows and predicted labels in columns. Accuracy is the fraction of correct decisions, not a measure of how well calibrated probabilities are.

For mutually exclusive multiclass labels, a softmax can replace the binary sigmoid. Multiple independent presence labels require a different output/loss contract. The ILSVRC protocol described by Russakovsky and colleagues assigns one annotated class to each image, although other objects can be present. Top-five evaluation accepts a prediction when that annotated class appears among five candidates; top-one asks whether it ranks first. Those metrics answer different questions. ILSVRC evaluation report

A complete small program

This complete NumPy program trains a model rather than calling a remote service. Run it with Python 3.12 and NumPy 1.26.4. It uses 400 full-batch gradient steps with learning rate 0.5 and Gaussian pixel noise with standard deviation 0.02. The split positions and seeds are fixed before training; validation and test images never enter fit.

There are two nonlearned comparisons. A constant-label rule measures the balanced-class baseline. The orientation rule compares absolute horizontal and vertical differences; it encodes the task’s stated geometry directly. Neither comparison is claimed to recognize arbitrary photographs.

import numpy as np

def stripes(positions, repeats=12, seed=0, noise=.02):
    positions=tuple(positions)
    if not positions or any(type(p) is not int or not 0<=p<8 for p in positions):
        raise ValueError('positions must be nonempty integers from 0 through 7')
    if type(repeats) is not int or repeats<1 or not np.isfinite(noise) or noise<0:
        raise ValueError('need positive repeats and finite nonnegative noise')
    rng=np.random.default_rng(seed);images=[];labels=[]
    for label in (0,1):
        for position in positions:
            for _ in range(repeats):
                a=np.zeros((8,8))
                if label==0:a[position,:]=1
                else:a[:,position]=1
                images.append(a+rng.normal(scale=noise,size=a.shape));labels.append(label)
    return np.array(images),np.array(labels)

def sigmoid(scores):
    # This branch-free identity avoids exp overflow for large logits.
    return np.exp(-np.logaddexp(0,-scores))

def fit(images, labels, steps=400, rate=.5):
    a=np.asarray(images,dtype=float);y=np.asarray(labels)
    if a.ndim!=3 or a.shape[1:]!=(8,8) or len(a)<1 or y.shape!=(len(a),):
        raise ValueError('need N grayscale 8x8 images and N labels')
    if not np.isfinite(a).all() or not np.isin(y,[0,1]).all():
        raise ValueError('need finite images and binary labels')
    if type(steps) is not int or steps<1 or not np.isfinite(rate) or rate<=0:
        raise ValueError('invalid training settings')
    x=a.reshape(len(a),-1);w=np.zeros(64);bias=0.
    for _ in range(steps):
        residual=sigmoid(x@w+bias)-y
        w-=rate*(x.T@residual)/len(x);bias-=rate*residual.mean()
    return w,bias

def probabilities(images,model):
    a=np.asarray(images,dtype=float)
    if a.ndim!=3 or a.shape[1:]!=(8,8) or not np.isfinite(a).all():
        raise ValueError('need finite N by 8 by 8 images')
    w,bias=model;return sigmoid(a.reshape(len(a),64)@w+bias)

def orientation_rule(images):
    a=np.asarray(images,dtype=float)
    if a.ndim!=3 or a.shape[1:]!=(8,8) or not np.isfinite(a).all():
        raise ValueError('need finite N by 8 by 8 images')
    horizontal=np.abs(np.diff(a,axis=2)).sum(axis=(1,2))
    vertical=np.abs(np.diff(a,axis=1)).sum(axis=(1,2))
    return (horizontal>vertical).astype(int)

def measure(labels,probability):
    y,p=np.asarray(labels),np.asarray(probability,dtype=float)
    if y.ndim!=1 or not len(y) or p.shape!=y.shape or not np.isin(y,[0,1]).all() or not np.isfinite(p).all() or np.any((p<0)|(p>1)):
        raise ValueError('need binary labels and matching probabilities in [0,1]')
    predicted=(p>=.5).astype(int)
    matrix=np.zeros((2,2),dtype=int)
    np.add.at(matrix,(y.astype(int),predicted),1)
    return dict(accuracy=float((predicted==y).mean()),confusion=matrix.tolist())

if __name__=='__main__':
    train,y_train=stripes([1,2],seed=1)
    validation,y_validation=stripes([1,2],seed=2)
    shifted,y_shifted=stripes([5,6],seed=3)
    model=fit(train,y_train)
    for name,x,y in [('train',train,y_train),('same-position validation',validation,y_validation),('shifted test',shifted,y_shifted)]:
        result=measure(y,probabilities(x,model))
        print(name,'accuracy:',result['accuracy'],'confusion:',result['confusion'])
        print('constant-label baseline:',float((y==0).mean()),'orientation rule:',float((orientation_rule(x)==y).mean()))
    clean,labels=stripes(range(8),repeats=1,noise=0)
    print('all-position class-mean images equal:',np.allclose(clean[labels==0].mean(axis=0),clean[labels==1].mean(axis=0)))
train accuracy: 1.0 confusion: [[24, 0], [0, 24]]
constant-label baseline: 0.5 orientation rule: 1.0
same-position validation accuracy: 1.0 confusion: [[24, 0], [0, 24]]
constant-label baseline: 0.5 orientation rule: 1.0
shifted test accuracy: 0.0 confusion: [[0, 24], [24, 0]]
constant-label baseline: 0.5 orientation rule: 1.0
all-position class-mean images equal: True

The shifted confusion matrix shows a systematic reversal, not a few random mistakes. The learned pixel weights reward the columns and penalize the rows seen in training. A shifted horizontal stripe intersects the rewarded columns without occupying those penalized rows, and vice versa. The directional rule measures changes locally and succeeds on these sampled shifts.

For T gradient steps, N images and d pixels per flattened image, training costs O(TNd), with O(Nd+d) storage in this implementation. Prediction costs O(Nd). The checks include an independently calculated first gradient step, confusion-matrix orientation, stable extreme logits, all stripe positions without noise and invalid input contracts.

Limits and comparisons

A high validation score supports generalization only to what the validation design actually probes. For real images, split at the independent unit that matters: an object, person, capture session or source collection. Several crops of the same photograph should not quietly become independent train/test examples. Fit preprocessing statistics on training data and apply augmentation only when it preserves the task’s label. A ninety-degree rotation swaps our horizontal/vertical classes, so it is not label-preserving here.

The toy failure also has a representation limit. Average the eight possible clean horizontal-stripe images; every pixel is 1/8. Average the eight vertical-stripe images and obtain the same image. A strict linear separator would need the average positive score above its threshold and the average negative score below it, which is impossible when the two average inputs coincide. More examples alone cannot make these two sets strictly linearly separable in raw pixels. Absolute directional differences are nonlinear features and need not preserve that equality.

This does not prove that every linear classifier always achieves 50% or that a handcrafted rule wins on natural images. It identifies a specific obstruction and a task-specific alternative. Real evaluation should additionally examine class imbalance, per-class errors, confidence calibration, capture conditions and label ambiguity. Inspect examples of failure before deciding whether to change data, features, architecture or the task definition.

Exercises with answers

1. The model gets 48 of 48 familiar-position validation images correct. What has been demonstrated?

Answer. Correct predictions for those independently noised observations at familiar positions. Neither unseen positions nor new scene families have been tested by that score.

2. For labels[0,0,1,1] and probabilities [0.1,0.9,0.4,0.8], compute accuracy and confusion.

Answer. Predictions are [0,1,0,1]. Accuracy is 1/2 and the row-true/column-predicted matrix is[[1,1],[1,1]].

3. Would rotating every stripe by 90 degrees while keeping its label be a valid augmentation?

Answer. No. The transformation changes horizontal into vertical and conversely. Either transform the label consistently or choose a label-preserving transformation.

4. Why is top-five accuracy uninformative for a two-class problem?

Answer. Returning both available labels already includes the answer. Top-k must be interpreted relative to the label space and protocol; it cannot substitute for top-one discrimination here.

Sources and next steps

The CIFAR description provides a concrete image/label/split contract; the ILSVRC report explains classification evaluation and incomplete per-image annotation. We read the specified sections, not every benchmark experiment, and report no result on either dataset. CIFAR dataset description ILSVRC evaluation report

Review logistic regression and model evaluation as needed. Continue with LeNet to see a learned spatial feature hierarchy, keeping its original architecture separate from later teaching variants.

Make a prediction, then check

The familiar-position validation score is 100%. Which conclusion is supported?

Choose one answer

Learning objectives

  • Define image, label and split contracts before choosing a model.
  • Use a distribution-shift counterexample to distinguish representation and evaluation failures.

Prerequisites & connections

Explore related knowledge →

References

  1. CIFAR-10 and CIFAR-100 datasets — official description
    Alex Krizhevsky; Vinod Nair; Geoffrey Hinton
  2. ImageNet Large Scale Visual Recognition Challenge — arXiv v 3, classification sections
    Olga Russakovsky; Jia Deng; Hao Su; Jonathan Krause; Sanjeev Satheesh; Sean Ma; Zhiheng Huang; Andrej Karpathy; Aditya Khosla; Michael Bernstein; Alexander C. Berg; Li Fei-Fei · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit image classification experiments and CNN architecture models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 6 tests: independent first logistic-gradient step, known confusion matrix and stable logits, same-position 100% versus shifted 0% synthetic outcome,50% constant baseline, nonlinear orientation rule and equal class-mean obstruction. No natural-image benchmark claimed.
  • Single AI author compared both locales across six sections, assumptions, definitions, equations, executed code and output, four exercise/answer pairs and scoped citations.43 checks across six draft articles; not independent human review or full historical training reproduction.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • Original synthetic figure generated from the audited classifier: true labels0/1/0/1, predictions0/1/1/0 and vertical probabilities0.003/0.997/0.872/0.127 after rounding. Visually inspected PNG; displayed clean examples distinguished from noisy split statistics. Generator scripts/figures/classification-shift.py SHA256 640e5b932f98c8faac52eb320320d0714a2e12178a911c1d15253826237bf337.
  • After visual reading review, shortened/localized inline citation labels. Verified ordered link targets and every protected code/math/tag span unchanged; full source identities remain in metadata. Frozen drafts preserved and final article SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.