Zum Inhalt springen

English:Convolutional neural networks and image features - AI Year 9

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

Convolutional neural networks and image features - AI Year 9

QR-Code



Introduction

A Cartesian coordinate grid with horizontal and vertical axes
Coordinates help specify a location. Our image arrays use a separate row and column convention, with row zero at the top; this generic diagram is not a CNN or our pixel image.

How can a computer respond to an edge without knowing what an object means? Slide a small numerical filter across an invented image, calculate its responses and test what changes them. You will distinguish a fixed feature calculation from a trained convolutional neural network, and design sensible tests before trusting an image system. Everything needed is in the text and worked grids; no camera, personal photographs, external AI account or model download is required.


Turn pixels into local numerical responses

A greyscale image can be represented by a rectangular array of brightness values. In our original examples zero means black and one means white; intermediate fractions represent intermediate brightness. Real images can use different ranges and colour channels, so the encoding must always be declared. A pixel is a sample at an array position, not a complete object label. We index rows from the top and columns from the left, starting at zero. This differs from the upward vertical axis in the introductory coordinate illustration.

Take the three-by-three image I and the supplied two-by-two filter K below. Read each matrix row from left to right. Each image row contains zero, zero, one. Each filter row contains minus one, one. We use stride one, no padding and zero bias: place the filter only where its whole two-by-two window fits, moving one column or row at a time. There are four valid placements, arranged in a two-by-two output.

I=(001001001),K=(−11−11)

At the top-left placement, all four input values are zero. Multiply each input by the weight in the corresponding filter position and add: zero times minus one plus zero times one plus zero times minus one plus zero times one equals zero. At the top-right placement, the window is zero, one in each row. Its sum is zero times minus one plus one times one plus zero times minus one plus one times one, which equals two. The lower placements repeat these results because all image rows are identical. The raw output rows are therefore zero, two and zero, two.

Yr,c=b+∑j=01∑i=01Kj,iIr+j,c+i,Y=(0202)

This is a feature map: a table of responses to a local numerical pattern. The positive response occurs where a darker left column meets a brighter right column. The same four weights are reused at every placement, which is parameter sharing. A conventional convolutional layer can learn its weights from data, use a bias, and produce multiple feature maps from multiple input channels. Our one-channel hand-written filter has been supplied, not learned. A response of two is neither two objects nor a probability nor proof that the system understands a scene.

There is a naming detail worth keeping accurate. Our unflipped multiply-and-add operation is cross-correlation. It is the operation used by the Conv2d layer described in the primary PyTorch documentation, although CNN discussions commonly call it convolution. Mathematical convolution rotates the kernel by a half-turn first. For our asymmetric filter, that gives the negative raw responses: zero, minus two in both rows. State the convention rather than silently mixing the results. No PyTorch package is installed or run here; the independent program implements only the declared arithmetic.

StatQuest introduces image classification with convolutional networks. Use it to connect local windows, shared weights and feature maps. Its illustrated network is not our tiny fixed-filter experiment, and viewing an explanation does not establish practical deployment competence. The optional convolution and pooling diagram by Will Whitney supplies another visual route; its file page and licence are verified, but it is an external supplementary image rather than an embedded course figure.

Try before checking: calculate the lower-right output. Hint: identify the two input columns under the window before multiplying. Partial step: the two right-column values are one. The full check is zero plus one plus zero plus one, giving two. Then explain why a uniformly white image produces zero with this particular filter even though its mean brightness is high.


Add activation and pooling then test the limits

A CNN often combines convolutional layers with nonlinear activations and other operations. A ReLU activation keeps a positive input and replaces a negative one by zero. It is applied to each response separately. On our first edge map it changes nothing, because every value is already zero or positive. On the diagonal-image example below, however, it removes a negative response. A nonlinearity is a mathematical transformation, not an act of understanding.

ReLU⁡(z)=max⁡(0,z)

For this exercise only, pool the entire two-by-two activated map into one number by taking its maximum. The vertical-edge map produces two. This max pooling keeps the strongest response but discards its position and the other three values. It can make certain local position changes less visible to later stages. It does not guarantee that all translations, orientations or backgrounds leave a network unchanged.

p=maxr,cReLU⁡(Yr,c)

The following results come from the executed Fraction program. Each row lists the two raw output rows separated by a semicolon. Pooling always occurs after ReLU. The horizontal example is the transpose of the vertical input: its rows are all zero, all zero, all one. This exchanges the row and column directions; it is not a claim that the code implements a camera-angle transformation or a general rotation routine.

Original synthetic case Raw map rows Pooled response Mean brightness
Vertical edge 0, 2 ; 0, 2 2 1/3
Horizontal edge 0, 0 ; 0, 0 0 1/3
Vertical values halved 0, 1 ; 0, 1 1 1/6
Add one quarter then clip at one 0, 3/2 ; 0, 3/2 3/2 1/2
Edge moved one column left 2, 0 ; 2, 0 2 2/3
Uniformly white 0, 0 ; 0, 0 0 1
Ones on the main diagonal 0, -1 ; 1, 0 1 1/3

Two inputs with mean brightness one third produce different filter responses: the vertical and horizontal edges. A mean-brightness baseline therefore loses information that this orientation-sensitive filter preserves. Conversely, the vertical and shifted edge have the same pooled maximum despite different raw maps and different means. One number can hide distinctions in several ways. No labelled object dataset has been supplied, so none of these comparisons yields object-classification accuracy or proves one classifier is better.

Changing one weight gives another useful controlled comparison. Replace only the top-right filter weight one by two, keeping the vertical image, stride, bias and all other weights fixed. The top-right placement now gives zero plus two plus zero plus one, or three; both output rows become zero, three. Changing the stride from one to two instead leaves only the top-left valid placement, giving a one-by-one zero map. That sampling change misses the strong response found at the other placement. It cannot be passed to our deliberately limited two-by-two pooling function, which rejects a map of the wrong shape.

The complete bounded standard-library program follows. It checks exact numeric types, rectangular shapes, pixel range, kernel fit and stride before calculation. It includes an optional bias and kernel flip, but no padding, learned kernels, optimiser or object labels. The seven named cases are authored test fixtures, not photographs or a measured population sample. You can reproduce them without an AI service.

"""Exact fixed-filter arithmetic on authored greyscale grids, not CNN training."""
from fractions import Fraction as F
import json

KERNEL = [[-1, 1], [-1, 1]]


def exact(value):
    if type(value) not in (int, F):
        raise ValueError("Expected integer or Fraction values")
    return F(value)


def checked_matrix(matrix, pixels=False):
    if (not isinstance(matrix, list) or not matrix
            or len(matrix) not in range(1, 9)
            or not all(isinstance(row, list) for row in matrix)):
        raise ValueError("Expected a nonempty matrix with at most eight rows")
    width = len(matrix[0])
    if width not in range(1, 9) or any(len(row) != width for row in matrix):
        raise ValueError("Expected a rectangular matrix with at most eight columns")
    for row in matrix:
        for value in row:
            number = exact(value)
            if pixels and not F(0) <= number <= F(1):
                raise ValueError("Greyscale pixels must lie between zero and one")


def filter_map(image, kernel, stride=1, flip=False, bias=F(0)):
    checked_matrix(image, pixels=True)
    checked_matrix(kernel)
    bias = exact(bias)
    if type(stride) is not int or stride not in range(1, 5) or type(flip) is not bool:
        raise ValueError("Expected stride one to four and a Boolean flip flag")
    height, width = len(image), len(image[0])
    kh, kw = len(kernel), len(kernel[0])
    if kh > height or kw > width:
        raise ValueError("Kernel must fit inside the image")
    weights = [list(reversed(row)) for row in reversed(kernel)] if flip else kernel
    output = []
    for y in range(0, height - kh + 1, stride):
        row = []
        for x in range(0, width - kw + 1, stride):
            value = bias + sum(exact(image[y + j][x + i]) * exact(weights[j][i])
                               for j in range(kh) for i in range(kw))
            row.append(value)
        output.append(row)
    return output


def relu(matrix):
    checked_matrix(matrix)
    return [[max(F(0), exact(value)) for value in row] for row in matrix]


def pool_2x2(matrix):
    checked_matrix(matrix)
    if len(matrix) != 2 or len(matrix[0]) != 2:
        raise ValueError("This demonstration pools exactly one two-by-two map")
    return max(exact(value) for row in matrix for value in row)


def fixtures():
    vertical = [[F(0), F(0), F(1)] for _ in range(3)]
    horizontal = [list(row) for row in zip(*vertical)]
    dimmed = [[value / 2 for value in row] for row in vertical]
    changed_background = [[min(F(1), value + F(1, 4)) for value in row]
                          for row in vertical]
    shifted = [[F(0), F(1), F(1)] for _ in range(3)]
    diagonal = [[F(int(x == y)) for x in range(3)] for y in range(3)]
    return dict(vertical=vertical, horizontal=horizontal, dimmed=dimmed,
                changed_background=changed_background, shifted=shifted,
                constant=[[F(1)] * 3 for _ in range(3)], diagonal=diagonal)


def demonstrate():
    reports = dict()
    images = fixtures()
    for name, image in images.items():
        raw = filter_map(image, KERNEL)
        active = relu(raw)
        reports[name] = dict(raw=raw, relu=active, pooled=pool_2x2(active),
                             mean_brightness=sum(sum(row) for row in image) / 9)
    return dict(kernel=KERNEL, cases=reports,
                true_convolution=filter_map(images["vertical"], KERNEL, flip=True),
                stride_two=filter_map(images["vertical"], KERNEL, stride=2),
                changed_weight=filter_map(images["vertical"], [[-1, 2], [-1, 1]]),
                classifier_trained=False, kernel_learned=False,
                target_object_labels_supplied=False, padding_implemented=False)


if __name__ == "__main__":
    print(json.dumps(demonstrate(), default=str, indent=2))

Attempt before inspecting a result: use a three-by-three image with ones only on its main diagonal. At its top-right window the weighted sum is minus one; ReLU makes it zero. At its bottom-left window the sum is one and stays one. Thus a zero activated cell does not tell you whether its raw input was zero or negative. Record the raw and activated maps separately instead of describing pooling as if it preserved every detail.


Design evidence before trusting an image system

A real trained image classifier needs a task, justified labels, permissioned data, a training procedure and evaluation on relevant new cases. Convolutional layers can learn useful numerical features through optimisation. More layers add capacity and computational work, but do not by themselves guarantee better accuracy, fairer outcomes or human-like understanding. A hand-filter response and an attractive network diagram supply none of those guarantees. Compare a proposed trained system with a simpler baseline on an appropriately reserved test set, and keep the test separate from choices about architecture or thresholds.

Shortcut learning is a useful warning: a model can exploit a convenient cue that works on the available examples but fails under different conditions. For example, an object dataset could accidentally associate one class with a particular background. A good score might then reflect the background rather than the intended object property. The Geirhos and colleagues research abstract discusses this broader problem; our small arrays illustrate sensitivity, not a replication of that study or a trained shortcut detector.

Build a test matrix for a fictional museum-card sorter that distinguishes two types of invented object drawings. Keep labels and intended object content fixed when a change is meant to be irrelevant. Vary lighting, orientation or viewpoint, and background separately before combining them. Pair each risk with a planned test, an expected invariant or expected change, the measured result and a proportionate response. The toy results below are actual arithmetic evidence; the proposed photograph-level tests have not been performed.

Risk Actual grid evidence Planned test for a future trained classifier Response if it fails
Lighting changes contrast Halving values reduces the pooled response from 2 to 1 Hold object and label fixed; use permissioned controlled bright and dim versions in a reserved test set Reconsider capture conditions and training coverage; refer uncertain cases for review
Orientation or viewpoint differs Exchanging rows and columns changes the response from 2 to 0 Test intended label-preserving rotations and relevant viewpoints with separately recorded labels Restrict the supported view or obtain appropriate evidence before widening use
Background becomes an unintended cue Raising and clipping values changes the response from 2 to 3/2 Pair each object drawing with varied backgrounds independent of its label Inspect errors and dataset design rather than trusting an aggregate score

Our background fixture is deliberately precise: add one quarter to every pixel and clip values at one. Black becomes one quarter while white stays one, so contrast shrinks. It is not an actual object moved to a photographed background. Likewise, a transpose is a grid orientation example, not evidence across real three-dimensional camera angles. These distinctions keep a proposed test plan separate from completed experiments.

CodeAI introduces computer vision in context. Connect its examples to the difference between a numerical response and a justified interpretation. Keep the written method available if video playback is unavailable. No learner needs to submit a face, voice, identifying information or a personal photograph. Use invented drawings or appropriately permissioned materials and teacher-approved offline tools for any extension.

Define an error table before deployment: expected label, predicted label or abstention, condition, error type and consequence. A medical or safety-critical interpretation would require much more specialist review than this school exercise and is outside its evidence. Even in the fictional sorter, an unfamiliar or unreadable card can go to human review rather than being forced into a confident category. A maximum feature value is not a calibrated confidence score.

For your test log, retain data origin and permission, numeric encoding, labels where genuinely available, kernel or trained-model version, preprocessing, stride, expected and actual outputs, limitations and the next check. Reject invalid inputs explicitly. Our program rejects an empty or ragged grid, values outside zero to one, non-exact pixel types, a kernel that cannot fit and unsupported stride values. At a boundary, a constant image cancels under this filter, but adding bias one half produces one half at every valid placement. State the changed setting rather than treating that result as an unexplained exception.

This is an editorial Year 9 AI enrichment route anchored to the KS3 Computing idea that digital pictures can be represented and manipulated. It is not a statutory Year-specific requirement to train a CNN. If previous AI material is unfamiliar, begin with rows, columns, multiplication, addition and the supplied weights; the course explains the feature, activation and test distinctions directly. Your achievement is a reproducible calculation and a critical evaluation plan, not certified competence to deploy a real vision system.


Interactive Tasks


Quiz: Test Your Knowledge

What does the first number in each image row represent here? (The brightness of the leftmost pixel in that row) (!The number of objects understood by the system) (!A guaranteed probability of the target class) (!The accuracy of a trained classifier)



What raw map results from the supplied vertical image and filter? (Both rows are zero then two) (!Both rows are two then zero) (!Every value is one) (!Every value is minus two)



Why are filter weights called shared across placements? (The same weights are reused at each valid window) (!Every pixel must have the same brightness) (!The final labels are copied into all inputs) (!Every layer has exactly one parameter)



What convention does the default program use? (Unflipped cross-correlation) (!A half-turn kernel flip at every step) (!Automatic padding with learned pixels) (!Training every filter from object labels)



What does ReLU do to minus one? (It returns zero) (!It returns one) (!It invents a class label) (!It changes the input photograph)



What is the pooled response for the diagonal fixture? (One) (!Minus one) (!Two) (!One third)



What does stride two produce on the vertical fixture? (A single zero response at the first valid placement) (!A four by four object label map) (!The same two by two output by definition) (!A guarantee of translation invariance)



Which statement describes the executed experiment? (A supplied fixed filter is applied to invented grids) (!A deep classifier has been trained on photographs) (!A camera-angle study has been completed) (!Real museum objects have been labelled automatically)



What does adding more convolutional layers guarantee? (No automatic improvement in real-world accuracy) (!Human-like object understanding) (!Perfect performance under every background) (!Removal of the need for test data)



Which is an appropriate future background test? (Vary backgrounds independently of the intended object labels) (!Reuse training answers as input features) (!Declare a pooled value to be accuracy) (!Remove every difficult case after looking at results)





Memory Game

Pixel A numeric sample at an image position
Kernel A small array of filter weights
Feature map Local responses arranged by placement
Stride The step between window positions
ReLU The operation that replaces negative responses by zero
Max pooling Retaining the largest value from a declared window





Drag and Drop

Represent brightness values in rows and columns Encode the image
Multiply matching values and add with a bias Calculate a filter response
Replace negative responses by zero Apply activation
Retain the strongest value in a window Apply max pooling
Compare relevant new cases and a simpler method Evaluate a proposed classifier





Crossword Puzzle

PIXEL A sampled image element
KERNEL A small weight array
STRIDE The step between filter positions
RELU A rectified linear activation
POOLING Combining responses over a window
BACKGROUND An unintended scene cue a model might exploit





LearningApps

Optional extra practice. Choose an appropriate activity with your teacher. If the external collection is unavailable, use the native activities and independent tasks in this course.


Cloze Text

Complete the explanation.
Our greyscale image is a rectangular

. A small filter is also called a

. The default operation uses unflipped

. Reusing weights at several positions is parameter

. The step between positions is the

. Negative responses become zero under

. A maximum retains the strongest response during

. The same pooled result can hide different

. The program uses supplied weights rather than

weights. A feature response is not classification

. Changing lighting can reveal a

. New consequential uses require proportionate human

.



Open Tasks


Easy

  1. Label an array: Draw the three rows of the vertical fixture and mark row zero and column zero. Hint: array rows run downwards here. Show the two valid horizontal placements and distinguish this convention from the Cartesian illustration.
  2. Calculate one window: Work out the lower-right output with the supplied weights before checking the text. Hint: its two right-hand pixels are one. Keep all four multiplication terms, the zero bias and the final sum.
  3. Separate transformations: On paper put the diagonal raw map through ReLU and then pooling. Hint: keep minus one in the raw record. Explain which information disappears at each transformation.
  4. Explain the evidence: Create an original three-panel drawing labelled fixed filter, possible trained CNN and deployment review. State what was actually executed and what would need additional evidence. Do not use a real personal photograph.


Standard

  1. Compare orientations: Calculate the horizontal fixture and compare it with the vertical case, including the identical means. Hint: equal means do not imply equal arrangements. Describe the transpose accurately and avoid a claim about real camera angles.
  2. Change one weight: Replace the top-right weight by two and calculate every vertical-image response. Predict before running the bounded code in a teacher-approved environment, then record expected and actual outputs and unchanged settings.
  3. Test the sampling boundary: Explain why stride two leaves a single zero for the vertical input and why the limited pooling routine rejects it. Hint: list the valid window starts. Keep the rejection rather than inventing a pooled two-by-two result.
  4. Build a three-risk matrix: For the fictional museum sorter pair lighting, orientation and background risks with specific reserved-case tests. Separate the already executed toy outputs from the photograph or drawing tests that remain plans.


Advanced

  1. Audit a shortcut claim: Design permissioned invented object drawings in which backgrounds vary independently of labels. Explain training and reserved test roles, a simple baseline, an error table and why one high score would not prove object understanding.
  2. Investigate bias and constant inputs: Derive the output on a uniformly white image with zero bias and with bias one half. Hint: sum the filter weights first. Predict the activated and pooled results and describe the restricted claim this establishes.
  3. Transfer with safeguards: Propose a new fictional inspection task with invented greyscale symbols. Specify encoding, labels if available, permitted transformations, fallback, data permissions and error consequences. Explain what must be rechecked rather than copying a museum result.
  4. Create an accessible explanation: Produce a short original screencast or annotated page with a text transcript showing the four-window calculation and one failed assumption. Include source attribution, raw versus activated output and a proportionate human review plan; do not claim that a video proves deployment competence.



Learning Check

  1. Reconstruct the filter map: Calculate every placement for the source two-by-two filter on the vertical three-by-three input and state the convention.
  2. Track information loss: Use the diagonal image to distinguish raw response, activation and pooling.
  3. Compare baselines and perturbations: Explain the equal means of two orientations and the differing outcomes after dimming, background change and shifting.
  4. Audit settings and boundaries: Calculate the changed-weight and stride-two cases and give one invalid-input check.
  5. Challenge an overclaim with evidence: Respond to the statement that more layers guarantee accuracy and human-like understanding.
  6. Design a justified transfer: Provide three deployment risks with tests for another fictional use and distinguish actual evidence from a plan.


Worked checks and assessment guidance

  1. At top-left and bottom-left the four input samples are zero, so the response is zero. At top-right and bottom-right the two right-column samples are one, giving zero plus one plus zero plus one equals two. Thus both raw output rows are zero then two. The weights are not flipped, so the calculation is cross-correlation, commonly called convolution in CNN layers. A half-turn flip reverses this asymmetric filter and gives zero then minus two instead.
  2. The raw rows are zero then minus one and one then zero. ReLU changes the negative value to zero, yielding zero then zero and one then zero. The maximum is one. A zero activation no longer reveals whether the raw response was zero or negative, and the pooled scalar no longer records which location supplied the maximum.
  3. The vertical and horizontal fixtures both have mean brightness one third but pooled responses two and zero. Halving vertical values produces response one. Adding one quarter and clipping produces response three halves because contrast becomes three quarters. Moving the edge left preserves pooled response two while moving the nonzero raw column and changing mean brightness to two thirds. These are feature comparisons without object labels, not classification accuracy.
  4. The changed top-right weight makes each right placement three, so rows become zero then three. Stride two samples only top-left and produces a one-by-one zero map; the specific two-by-two pooling function must reject it. An empty, ragged, out-of-range or non-exact pixel array is another explicit rejection. With a constant-white image zero bias gives zero while bias one half gives one half throughout.
  5. Convolutional models use numerical transformations and, when trained, learned parameters. More capacity does not guarantee generalisation or semantic understanding. Compare appropriately reserved relevant cases and a simple baseline; inspect error consequences and failures under controlled changes. Our supplied kernel was not learned and no labelled object set exists here, so it supports neither an accuracy estimate nor a claim that a real CNN succeeded.
  6. For invented symbol inspection, hold intended labels fixed while varying brightness, intended orientation or viewpoint, and backgrounds independently. Record expected and actual outputs by condition with data origin, version and limits. The course has actually executed only small grid transformations; new labelled drawing or photograph tests remain proposed until performed. Recheck permissions, label meaning, supported conditions, baseline and human fallback before a new use.


Learning evidence

Keep the labelled three-by-three input and two-by-two filter, four multiplication sums, the convention declaration, raw and activated maps, pooled outputs and the complete seven-case test record. Add the changed-weight and stride-boundary comparisons, a rejected invalid input, an error-and-risk matrix and an original new-context explanation. Clearly distinguish supplied weights from trained parameters, feature response from accuracy and a planned deployment test from completed evidence.


OER and Wikipedia

PyTorch Conv2d documentation identifies its operator as cross-correlation and describes stride, padding, weights and bias. PyTorch MaxPool2d documentation defines window-based maximum selection. These primary operation definitions were inspected on 15 November 2026. Our exact code and seven numerical fixtures are original, restricted teaching constructions; PyTorch was not executed.

Geirhos and colleagues: Shortcut Learning in Deep Neural Networks, research abstract inspected, motivates the caution about convenient cues and changed conditions. The museum sorter, controlled test matrix and arithmetic are original teaching examples, not a replication of that study.

DfE Computing programmes of study, KS3 digital-data content, supplies the broad curricular anchor. The Year 9 CNN route is editorial enrichment, not a statutory Year-specific training requirement.

2D Cartesian Coordinates.svg, H Padleckas, public domain, embedded unchanged as a generic coordinate illustration. Array row orientation and the original numeric image are explained separately. Convolutional Network.png, Will Whitney, CC BY-SA 4.0, is an optional external diagram whose original file page and preview were checked; native embedding was unavailable and is not claimed.

https://www.youtube.com/watch?v=HGwBXDKFk9I — StatQuest with Josh Starmer: Neural Networks Part 8, Image Classification with Convolutional Neural Networks. https://www.youtube.com/watch?v=2hXG8v8p0KM — CodeAI: How Computer Vision Works. Actual metadata, embedding availability and retained preview bytes were verified and visually inspected. Videos remain external unchanged embeds, with no transcript copying, endorsement or relicensing implied. Required methods are also fully provided in the text.

All grids, expected outputs, bounded standard-library code and fictional contexts are original. The program was actually executed with exact Fraction arithmetic; it does not train a CNN, implement padding or classify real photographs. Author checks are not independent expert certification. No local generative model, paid API, camera or personal learner data is used.


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...