Teaching pack · UAT 456
A 15-week teaching plan, 15 worksheets, a scoring rubric and a map from the course description to the lessons, for instructors to evaluate and adapt before teaching.
Coverage of the course description
The lessons fully teach 10 of 10 description topics. Each topic lists the modules and lesson sections that teach it, and incomplete topics say what is missing.
| Description topic | Modules | Where it is taught | Status |
|---|---|---|---|
| AI, machine learning and computer vision applied to UAS data and missions | M1M5M15 | Module 1: The pipeline of an intelligent image-analysis system · Module 5: Deep-learning models for images · Evaluating automated image-analysis systems · Module 15: The inspection application and the acceptance test · The navigation application: landing on a pad and vision-based control · The surveying application and conformity decisions · Intelligent systems, alerting and handling failure | Covered |
| Data preparation and annotation | M1M6 | Module 1: Preparing image data · Small objects in large images, and tiling · Label-preserving augmentation · Annotating images: shapes, formats and agreement · Module 6: Defining the problem and building labels · Preparing data without leaking · Splitting data to match the real question | Covered |
| Classification and prediction | M2M7M8 | Module 2: Classifying images from features · Module 7: Metrics for imbalanced data · Logistic regression on the fleet data · Decision trees · Random forests and gradient boosting · Choosing a model that matches the deployment question · Module 8: Regression metrics · Correlated features, ridge and lasso · Time-series data from the bottling line | Covered |
| Object detection and recognition | M3M13 | Module 3: From classification to detection · Merging results from overlapping tiles · Module 13: Choosing a technique from the output the task needs · Classifying patches with colour and texture features · Detecting repeated objects by template matching | Covered |
| Object tracking | M3M14 | Module 3: Tracking by detection · Counting with a count line · Measuring tracking quality · Module 14: Optical flow and point tracking with KLT · A single-object tracker and handling a loss | Covered |
| Image segmentation | M4M13 | Module 4: Image segmentation · Segmenting with k-means colour clustering · Separating touching objects with morphology and watershed · Segmenting with deep learning · Anomaly detection · Module 13: Segmenting cracks and evaluating thin lines | Covered |
| Model evaluation | M3M5M7M10 | Module 3: Evaluating a detector: precision, recall and average precision · Module 5: Confidence calibration · Evaluating automated image-analysis systems · Module 7: Metrics for imbalanced data · Module 10: Tuning hyper-parameters · Calibrating probabilities and choosing the threshold from cost · Reporting the test result with uncertainty and the cost of the task · Monitoring data drift after deployment | Covered |
| Processing of camera and sensor imagery | M1M11M12 | Module 1: Image processing · Module 11: Images and video in OpenCV · Queues, latency and the frames you must drop · Checking frame quality before use · Image filters, colour and regions of interest · Frames from thermal and multispectral sensors · Module 12: The Canny edge detector · The Hough transform for straight lines · Features, descriptors and matching · Mosaicking and accumulated drift | Covered |
| Applications to inspection, surveying, monitoring, navigation and autonomous mission support | M12M14M15 | Module 12: Detecting change between two flights · Module 14: Scale and the uncertainty of a measurement · Measuring crack width near the resolution limit · Depth and the step between panels from two camera stations · Module 15: The inspection application and the acceptance test · The navigation application: landing on a pad and vision-based control · The surveying application and conformity decisions · Intelligent systems, alerting and handling failure | Covered |
| Use of software tools for introductory intelligent-system development | M1M5M11 | Module 1: Annotating images: shapes, formats and agreement · Module 5: Transfer learning · Ready-made tools: running a trained model from a file · Module 11: Images and video in OpenCV | Covered |
Weekly teaching plan
| Week | Topic | Pre-class | Lecture | Lab | Evidence |
|---|---|---|---|---|---|
| 1 M1 | Small objects, tiling and image processing | Read 'Small objects in large images, and tiling' and 'Image processing'; run Examples 1 and 2 | Object size in pixels, tile count and overlap, gray-world balance and standardisation with training-set values | Worksheet 1 part B: split data by date or paddock, write the datasheet, compute and cut tiles | Datasheet and tile calculations |
| 2 M2 | Histograms of oriented gradients | Read 'Histograms of oriented gradients (HOG)'; run Example 1 | Gradients, unsigned orientation, cells, blocks, normalisation and window size against object size | Worksheet 2 part B: compute a cell histogram by hand and by code, then extract colour and HOG features for every patch | Hand versus code histogram comparison |
| 3 M3 | Tracking by detection | Read 'Tracking by detection'; run Example 2 | Predict, associate, update and manage the track life cycle; the Hungarian method; appearance features | Worksheet 3 part B: run the detector on every video frame, then match with the Hungarian method | Video with track IDs and a log of ID breaks |
| 4 M4 | Morphology, watershed and deep segmentation | Read 'Separating touching objects with morphology and watershed' and 'Segmenting with deep learning'; run Example 2 | Erosion, dilation, opening, closing, distance transform, watershed and its limits; U-Net and foundation models for labelling | Worksheet 4 part B: separate touching objects with morphology and watershed, and try making masks with a foundation model | Counts before and after separation, failure cases and labelling times |
| 5 M5 | Confidence calibration and system evaluation | Read 'Confidence calibration', 'Evaluating automated image-analysis systems' and 'Processing-time budget'; run Examples 2 to 4; take the module 5 quiz | ECE, temperature scaling, four levels of evaluation, subgroup results, characteristics of trustworthy AI and time budgets | Mini-project part B: measure ECE and apply temperature scaling, evaluate the end output by subgroup, and build a time budget on the real device | System evaluation results and quiz result |
| 6 M6 | Preparing data without leaking | Read 'Preparing data without leaking'; run Example 2 | Anything learned from data is learned from the training part only; Pipeline and leaky feature selection | Worksheet 1 part B: run Example 2 with 50, 500 and 5,000 random features and write a short note on why the accuracy of the wrong method changes | Accuracy table of the two methods and a short note |
| 7 M7 | Logistic regression, SVM and non-linear relationships | Read 'Logistic regression on the fleet data' and 'When the relationship is not linear'; run Example 2 | Odds ratios, straight versus curved boundaries, RBF SVM (C and gamma), standardising and domain-knowledge features | Worksheet 2 part B: change the acceptable cap-torque band (0.3 and 0.8 N·m), compare PR-AUC of each model and try removing the err feature | PR-AUC table of the models and notes on the err feature |
| 8 M8 | Limits of regression models and time-series features | Read 'The limits of a regression model: extrapolation' and the first half of 'Time-series data from the bottling line'; run Example 3 | Trees cannot predict beyond what they have seen, RMSE by cycle band, model documentation, lags, rolling windows that use only the past, and known-in-advance variables | Worksheet 3 part B: move the training edge to cycles 200 and 350, record RMSE by band and write a short model note stating the range not to use | RMSE-by-band table and the model note |
| 9 M9 | DBSCAN and PCA | Read 'Density-based clustering with DBSCAN' and 'Dimensionality reduction with PCA'; run Examples 3 and 4 | Core points and noise, the k-distance plot, eps and min_samples, PCA, loadings, cumulative variance | Worksheet 4 part B: refine eps between 0.8 and 1.5, choose a value with reasons, and run PCA on 8 columns of your own data and read the loadings | Table with the chosen eps and the meaning of PC1 and PC2 |
| 10 M10 | Reporting with uncertainty, and drift monitoring | Read 'Reporting the test result with uncertainty and the cost of the task' and 'Monitoring data drift after deployment'; run Examples 3 and 4 | Bootstrap over whole airframes, simulating the alert policy and its cost, KS on the inputs, the alert rate, late labels and the retraining condition | Worksheet 5 part B: change the mid-job motor-failure cost to 15,000 and 100,000 baht and the vibration shift to 1.0 and 5.0, then write a report statement honest about the uncertainty interval | Table of cost and drift effects with a report statement |
| 11 M11 | Queues, latency and drop policy | Read 'Queues, latency and the frames you must drop'; run Example 2 | Processing load, Little's law, drop-new versus drop-old, and why inspection should not drop frames | Worksheet 1 part B: time the group's processing stage and choose a queue size with the simulator | Latency table by queue size and the reason for the choice |
| 12 M12 | The Hough transform and feature matching | Read 'The Hough transform' and 'Features, descriptors and matching'; run Examples 2 and 3 | Lines with rho and theta, HoughLinesP, ORB versus SIFT, RANSAC and the repeating-pattern case | Worksheet 2 part B: find angles and spacing with Hough, and register two images with ORB and SIFT | Table of pairs, inliers and the error at check points |
| 13 M13 | Template detection and crack segmentation | Read 'Detecting repeated objects by template matching' and 'Segmenting cracks'; run Examples 3 and 4 | TM_CCOEFF_NORMED, IoU, precision, recall, multi-scale search, black-hat and the tolerant metric | Worksheet 3 part B: detect repeated objects with a template and segment cracks with black-hat against hand-labelled truth | Precision and recall table and strict and tolerant segmentation metrics |
| 14 M14 | Single-object tracker and scale | Read 'A single-object tracker' and 'Scale and the uncertainty of a measurement'; run Examples 2 and 3 | TRACK and COAST states, re-search, GSD from geometry and from a target, and the GUM uncertainty budget | Worksheet 4 part B: write a tracker with states, occlude the object, and compute the uncertainty budget of one length | Log of the frames lost and regained, and the uncertainty budget with U |
| 15 M15 | Navigation, surveying and vision-based control | Read 'The navigation application' and 'The surveying application and conformity decisions'; run Examples 2 to 4 | ArUco with solvePnP, the LANDING_TARGET message, gain against delay, the guarded rule, and the effect of GSD on uncertainty | Worksheet 5 part B: test the navigation or surveying part of the group's application following the examples | Table of marker detection heights, or the uncertainty budget with the decision rule |
Worksheets and instructor guide
One worksheet per module. Students open it on the web, print it or download the .docx. The instructor guide under each worksheet gives the class timing, expected results, discussion questions and notes for students with different backgrounds.
1Worksheet 1 Preparing a drone image dataset for training
Analysis activity · About 1.5 h of class time · CLO1
Objective: Define the data scope and labelling policy, split by group, write a datasheet, tile, balance colour and augment data while keeping boxes correct
Equipment
- Sample drone images provided by the department with usage rights
- CVAT for labelling
- Computer with Python, numpy, opencv, scikit-learn, scipy and the example code at /downloads/uat-456/
- Datasheet template
Safety
- Desk work at a computer; no flying
- Blur or crop identifiable people before sharing, and keep data only on department storage
- Use only images you have the right to use, and record their source
Steps
- Write a one-page data scope and labelling policy
- Label 30 images in CVAT, two people separately, and compare agreement
- Split the data by date or paddock and write a datasheet following the headings of Gebru et al.
- Compute object size in pixels and the tile count with Example 1, then cut the tiles
- Try gray-world balance on morning and midday images with Example 2 and explain when it fails
- Write flip and rotate functions that transform boxes, and test them with the method in Example 3
Deliverables
- Data scope and labelling policy
- Annotator agreement result
- Datasheet
- Tile calculations and box-transform test results
Checklist
- The data scope and labelling policy contain measurable rules (such as at least half the body visible) and state how people are blurred
- Table 1 has at least 8 entries with IoU, plus the kappa of the whole set
- Table 2 shows the formulas n_px = L/GSD and nx = ⌈(W − t)/(t − o)⌉ + 1 with units
- Table 3 tests both the flip and the 90-degree rotation, and the formula box matches the real image in every row
- The datasheet has sections for purpose, composition, collection, recommended uses and limitations
Instructor guide
Class timing
- Briefing; write the data scope and labelling policy10 min
- Label 30 images in CVAT, two people separately25 min
- Compare agreement, split the data and write the datasheet20 min
- Compute object size and tile count, then cut tiles10 min
- Gray-world trial and box-transform tests20 min
- Wrap-up and hand-in checklist5 min
Expected results
- With the lesson's Example 4: box A (100, 200, 180, 232) against B (104, 198, 186, 234) gives IoU 0.790; class labels of 12 animals agree 0.75, chance agreement 0.47, kappa 0.53. Your values will differ; an IoU of about 0.7 to 0.9 between two people is normal, and if kappa is below about 0.6, revise the policy before labelling more.
- With the camera of Example 1 (5,472 × 3,648 px, GSD 2.5 cm, cow 2.0 × 0.8 m): the cow is 80 × 32 px; shrinking the whole image to 640 px leaves 9.4 × 3.7 px; 640-pixel tiles with 128 overlap give 11 × 7 = 77 tiles and 1.58 times the pixels. If the department camera differs, check the formulas and that the overlap is not shorter than the object.
- Box (100, 200, 180, 232) in a 640 × 640 tile: horizontal flip gives (460, 200, 540, 232) and a 90-degree clockwise rotation gives (408, 100, 440, 180), turning 80 × 32 into 32 × 80. Every row must match the box recovered from the really transformed mask; a mismatch means an axis was swapped.
- Kappa is always below raw agreement because it removes chance agreement, for example 0.75 against 0.53 when 'cow' is so common that chance alone gives 0.47. A strong answer names the conflicting classes (calf against cow, and 'unsure') and proposes a measurable rule, such as a calf being shorter than half an adult in the image.
- At a GSD of 1.5 cm the cow is 2.0/0.015 = 133.3 px, longer than the 128-pixel overlap, so it is not enough: a cow cut by a tile edge may never be whole in any tile. Set the overlap to at least 134 px (rounded to a convenient value such as 160), which increases the number of tiles.
- Morning images of dry pasture, where the scene really is yellow-brown: gray-world assumes the average is grey and pulls colours wrong, for example gains R 0.859, G 0.953, B 1.271 turn a white cow (228, 214, 168) into a bluish (196, 204, 214). Better: lock the white balance for the whole flight or photograph a grey card at take-off, then use colour augmentation.
- Images taken seconds apart are nearly identical; if they land in different sets the test score is inflated, so split by flight date or paddock. The mean and standard deviation must come from the training set only and be reused unchanged on validation, test and real images; otherwise test information leaks into training.
Discussion questions
- If every image comes from the wet season, how will the system fail in the dry season, and how should the datasheet state this limitation?
- Why is a box that shifts slightly after rotation more dangerous than a program that crashes?
- Before sending images to outside annotators, what must be done with images showing farm workers or neighbours under the Personal Data Protection Act?
Adapting to student background
- Upper secondary (M.6)
- Have them derive the tile-count and the flip and rotate formulas by hand before coding and compute kappa from a 3 × 3 table themselves; pair them with a classmate confident in CVAT.
- Vocational certificate
- Start with labelling in CVAT and drawing a box on grid paper, then physically rotate the paper to see where the corners go; give a step-by-step fill-in sheet for n_px and the tile count.
- Diploma
- Extension: write automated tests for every box transform (vertical flip, 180 and 270-degree rotation) and convert boxes to YOLO rows and back exactly.
2Worksheet 2 Features and a classifier for cattle and look-alikes
Analysis activity · About 1.5 h of class time · CLO1, CLO2
Objective: Extract colour and HOG features, train a classifier, read the confusion matrix and find the missing feature
Equipment
- Dataset from Worksheet 1
- Computer with Python, numpy, opencv, scikit-learn, scipy and the example code at /downloads/uat-456/
- Paper and calculator for hand calculation
Safety
- Desk work at a computer; no flying
- Use only images you have the right to use, and record their source
Steps
- Cut 32 × 32 or 64 × 64-pixel patches, at least 4 classes with 50 each
- Compute one cell's histogram by hand and with Example 1, and compare
- Extract colour and HOG features and train an SVM with Example 2, splitting the test set by paddock or date
- Read the confusion matrix, find the most confused pair, then propose and test one extra feature
- Report per-class precision, recall, F1 and macro average before and after adding the feature
Deliverables
- Patch set table
- Hand versus code histogram table
- Confusion matrices before and after the added feature
- Conclusion on which feature separates the confused pair
Checklist
- Table 1 has at least 4 classes with 50 patches each and shows the test set comes from paddocks or dates not used for training
- Table 2 covers all 9 bins and the hand and code values match, or the difference is explained
- Confusion matrices (rows = true class) are reported before and after the added feature
- Table 3 gives per-class precision, recall and F1 and the macro average, not accuracy alone
Instructor guide
Class timing
- Briefing and cutting patches15 min
- Histogram by hand and by code15 min
- Extract features and train the SVM25 min
- Read the matrix and test an extra feature20 min
- Per-class summary and hand-in checklist15 min
Expected results
- At least 4 classes, such as cow, termite mound, bush and bare soil, with at least 50 patches each at 32 or 64 px. Check that each paddock or date sits in one set only; if patches from one source image appear in both sets, fix it before training.
- With the cell of Example 1 (background 60, lower-right corner 200): bin 0 to 20 degrees 980, bin 40 to 60 degrees 198 (√(140² + 140²)), bin 80 to 100 degrees 980, others 0 (recomputed). Hand and code must match in every bin; with a cell from a real image, differences should not exceed rounding.
- With Example 2 (synthetic): colour only, accuracy 0.933, cow precision 1.00, recall 0.733, F1 0.846; mound precision 0.789, recall 1.00, F1 0.882; macro F1 0.932. After adding HOG, accuracy 0.989, cow recall 0.956, F1 0.977, mound F1 0.978, macro F1 0.989 (recomputed from the matrices). Real images will score lower; check that rows and columns were read correctly.
- In Example 2 the confused pair is red-brown cattle against termite mounds (12 of 45 cows predicted as mounds) because they share a colour. HOG separates them because a long cow has strong edges in two directions while a round mound has edges in every direction. A strong answer uses the pair from the group's own matrix and explains how the chosen feature differs between the two classes.
- (48/8 − 1)² × 36 = 25 × 36 = 900 values. If objects are much smaller than a cell, their key edges are averaged with the background inside one cell and HOG cannot describe the shape, so the window and cell must match the object size in pixels.
- Accuracy pools every class, so easy classes hide the failing one: colour alone scores 0.933 but cow recall is only 33/45 = 0.733, so the system under-counts every morning. A strong answer quotes the group's per-class recall and F1.
- Synthetic images are far easier than real ones; results on a test set split by paddock or date are usually lower and reflect field use better. Report the paddock-split test result with per-class recall, not the synthetic 0.989.
Discussion questions
- When should a small system on an edge device still use designed features instead of a CNN?
- If features are not standardised, what does V, which reaches 255, do to the SVM?
- How can a real system use simple features such as area and colour to reject impossible boxes?
Adapting to student background
- Upper secondary (M.6)
- Have them compute the corner pixel's gradient magnitude and direction by hand (√(140² + 140²) and 45 degrees) and derive the HOG length formula before running code.
- Vocational certificate
- Have them draw the 8 × 8 cell on grid paper, shade the bright part and draw edge arrows before voting into bins, and read the confusion matrix from a sheet with the true-class rows shaded.
- Diploma
- Extension: add a shape feature (length-to-width ratio from moments), compare it with HOG for separating cows from mounds, and time feature extraction per patch.
3Worksheet 3 Detecting, tracking and counting in drone video
Lab · About 1.5 h of class time · CLO2, CLO3
Objective: Detect with tiling, merge duplicate boxes, track with the Hungarian method and count with a count line without double counting
Equipment
- A YOLO-family detector you have the right to use
- Sample video, or a drone with a camera to record in the training area
- Computer with Python, numpy, opencv, scikit-learn, scipy and the example code at /downloads/uat-456/
- Sheet for counting by eye
Safety
- If recording your own video, fly within CAAT conditions in visual line of sight, keep people clear, and check batteries and propellers before flight
- Record people or vehicles without identifying individuals or number plates
- Blur or crop identifiable people before sharing, and keep data only on department storage
Steps
- Run the detector on Worksheet 1 images, both shrunken whole and tiled, and compare box counts
- Merge tile boxes with Example 1, try several IoU and IoS thresholds, and compare with counting by eye
- Run the detector on every video frame and match with the Hungarian method from Example 2
- Count with a count line as in Example 3 and compare with ID counting and counting by eye
- Log ID breaks and propose one fix
Deliverables
- Still-image count table for each method
- Video with track IDs
- Video count table for three methods
- ID-break log and proposed fix
Checklist
- Table 1 uses the count by eye as the reference and states the IoU or IoS threshold in every row
- Tile boxes were shifted by the tile's top-left corner before merging
- Table 2 covers all three methods against the count by eye
- The submitted video shows no faces or number plates and is stored on department storage
Instructor guide
Class timing
- Briefing, safety, drone check or video preparation10 min
- Detect on stills both ways and count by eye20 min
- Merge boxes with IoU and IoS thresholds15 min
- Record or load video, detect every frame and match with the Hungarian method25 min
- Count with the count line and log ID breaks15 min
- Wrap-up and hand-in checklist5 min
Expected results
- With Example 1: half box (596, 100, 640, 130) against full box (590, 98, 672, 131) gives IoU 0.488 and IoS 1.000; NMS at IoU 0.5 counts 4 cows and IoS 0.6 counts 3, which is right (recomputed). On real images, shrinking the whole image usually under-counts because objects shrink to a few pixels, tiles with NMS IoU over-count at tile edges, and IoS should be closest to the count by eye.
- With Example 3: 6 IDs, 5 crossings (the loitering animal is counted twice) and 4 when each track counts once, which is right (recomputed). On the group's video, the ID count should exceed the count by eye, and one crossing per track should be closest to it.
- The log should give the frame, the cause (occlusion, walking close together, leaving the image, several missed detections) and the effect on the count. Reasonable fixes include Hungarian instead of greedy matching, waiting more frames before deleting a track, adding appearance features to the matching cost, or a two-line count band.
- Shrinking the whole image under-counts because objects become too small to detect. IoU merging over-counts because a half box and a full box have an IoU below the threshold (0.488 < 0.5). IoS fixes it because it is 1.000 when the small box lies inside the large one, but too low an IoS threshold merges two cows standing close into one, so choose it on the validation set.
- Greedy takes T1 with D1 (0.9) first, leaving T2 only D2 at 0.1, below 0.3, so T2 is unmatched and a new ID starts. Hungarian pairs T1 with D2 (0.8) and T2 with D1 (0.7), total 1.5, and every track is matched (recomputed). In the group's video, differences appear mostly when objects walk close together.
- The old ID disappears before crossing and is not counted; the new ID crosses once and is counted once, so the animal is counted exactly once. It still misses an ID that breaks exactly at the line: the new ID starts below the line and is never counted. A two-line band, or counting tracks that were once above the band and end below it, fixes this.
- HOTA = √(0.81 × 0.64) = 0.72. MOTA is dominated by detection and barely reflects ID switches, which are the main cause of over-counting at the gate, so report IDF1 or HOTA with the error of the final count.
Discussion questions
- Consecutive stills overlap; how can the team avoid counting the same cow in two images?
- If AP is high at IoU 0.5 but low at 0.75, can the detector be used for head counting, and for measuring size?
- What must be watched for personal data when recording people or vehicles in the training area?
Adapting to student background
- Upper secondary (M.6)
- Have them compute IoU and IoS for Example 1 by hand and solve the 2 × 2 assignment by trying every pairing before using linear_sum_assignment; for flying, pair them with an experienced classmate.
- Vocational certificate
- Give them the drone check and video recording with the pre-flight checklist, and have them count crossings by plotting each ID's y path on graph paper before coding.
- Diploma
- Extension: add a two-line count band and test the case of an ID breaking at the line, and compute the detector's AP at IoU 0.5 and 0.75 on real images with the code of Example 4.
4Worksheet 4 Surface maps, counting touching animals and anomaly alerts
Analysis activity · About 1.5 h of class time · CLO2
Objective: Segment surfaces and evaluate with IoU and Dice, separate touching objects, and detect anomalies with thresholds set from false alerts
Equipment
- Orthomosaic of a pasture or university field
- Masks of touching objects from real or synthetic images
- Tracks from Worksheet 3 or the simulated data in Example 3
- Computer with Python, numpy, opencv, scikit-learn, scipy and the example code at /downloads/uat-456/
Safety
- Desk work at a computer; no flying
- Blur or crop identifiable people before sharing, and keep data only on department storage
- Alerts are prompts for a person to check, not animal diagnoses
Steps
- Label part of the image by hand as a reference, then segment with k-means as in Example 1, before and after filtering
- Compute each surface's area in rai and report per-class IoU and Dice
- Separate touching objects with morphology and watershed as in Example 2, and record cases that cannot be separated
- Have a foundation model make masks from point clicks and time it against drawing by hand
- Detect anomalies with the Mahalanobis distance and Isolation Forest, then compute false alerts per day for the chosen threshold
Deliverables
- Surface map with area and IoU and Dice table
- Separation results and failure cases
- Labelling time comparison
- Alert list with the threshold rationale
Checklist
- Table 1 converts pixels to rai with A = n_px × GSD² and 1 rai = 1,600 m²
- IoU and Dice are reported for every class and the metric used is named
- Table 2 records at least one case that could not be separated, with the reason
- Table 3 states the chosen threshold and the false alerts per day, and says alerts are prompts for a person to check
Instructor guide
Class timing
- Briefing and hand-labelled reference15 min
- k-means before and after filtering; area, IoU and Dice25 min
- Separate objects with morphology and watershed15 min
- Foundation-model masks and labelling time10 min
- Anomaly detection and thresholds from false alerts20 min
- Wrap-up and hand-in checklist5 min
Expected results
- With Example 1 (240 × 200 px, GSD 1 m, 30 rai in total): the raw image gives grass 26.55, bare soil 3.45 and water 0.00 rai (the pond vanishes); after a 5 × 5 Gaussian blur, grass 25.68, soil 3.38, water 0.95 rai with IoU 0.999, 0.997, 0.994 (Dice = 2IoU/(1 + IoU), so IoU 0.960 gives Dice 0.980). Real images score lower; check that areas add up to the image and no class vanished.
- With Example 2: connected components find 2 blobs, watershed finds 3 animals of 1.21, 1.19 and 1.21 m², close to a 2.0 × 0.8 m ellipse (π × 1.0 × 0.4 = 1.26 m², recomputed). A blob of about 2.4 m² counted as one is probably two that were not separated; the expected failure is objects lying side by side along their whole length.
- With the simulated data of Example 3 (recomputed with numpy): limit D = √χ²(2, 0.99) = 3.03; cow 118 D 1.02, normal; cow 256 z +1.44 and −1.87 but D 4.24, alert; cow 311 D 18.31, cow 342 D 11.14, cow 407 D 4.44, all alerts; Isolation Forest agrees in the lesson output. Take logarithms of your own data first, because distances are positive and right-skewed.
- Noise spreads the large class (grass, 86%), so k-means spends two clusters on grass and absorbs the 3% pond into dark grass; filtering tightens each surface's group. In the example, raw grass IoU 0.960 looks good while water is 0.000, so an overall average hides a vanished small class.
- 900 × 0.01 = 9 a day. To stay near one a day, use 99.9% (900 × 0.001 = 0.9 a day, D limit about 3.72), alert only when abnormal two rounds in a row, or send only the top 3. A strong answer notes that a stricter limit misses more borderline cases and must be agreed with the users.
- Each value is normal on its own (|z| < 2.58), but normal data are correlated: cattle far from the herd usually walk a lot. Cow 256 is far but walks little; the Mahalanobis distance accounts for the correlation and gives D 4.24, above 3.03.
- Times depend on the group's images and tools. A strong answer reports the time per object for both methods and the share of masks needing correction. The foundation model does not know the job's labelling policy, such as whether to include the shadow, so every mask must be checked and corrected.
Discussion questions
- A class vanishes while the overall average barely moves; what harm does that do to a farm that moves the herd based on grass area?
- If the two weeks of 'normal' training data contain sick cattle, how does the anomaly detector learn the wrong thing?
- Who should decide when the system flags an animal, and what should be recorded?
Adapting to student background
- Upper secondary (M.6)
- Have them compute areas from pixels and convert IoU to Dice by hand, and read the 3.03 limit from a χ² table before using scipy, linking to school statistics.
- Vocational certificate
- Give them the reference labelling and the hand-drawing timing; use a printed mask to locate each animal's core before running watershed, and a fill-in sheet for the rai calculation.
- Diploma
- Extension: compare alerts under a two-rounds-in-a-row rule with the 99% limit, and vary the watershed core threshold (0.4 to 0.8 of the maximum), reporting the range that counts correctly.
5Worksheet 5 Mini-project: evaluating a whole image-analysis pipeline
Lab · About 1.5 h of class time · CLO3
Objective: Fine-tune a deep model, measure confidence calibration, evaluate the end output by subgroup, build a time budget and write a model card
Equipment
- The group's dataset from Worksheets 1 to 4
- Computer or service with a GPU for fine-tuning
- Edge device for timing, if available
- Computer with Python, numpy, opencv, scikit-learn, scipy and the example code at /downloads/uat-456/
Safety
- Desk work; if an edge device uses lithium batteries, charge it in a fire-safe bag or box
- Blur or crop identifiable people before sharing, and keep data only on department storage
- State limitations honestly in the model card and leave final decisions to people
Steps
- Compute the chosen backbone's receptive field and stride with Example 1 and compare with object size
- Fine-tune the detector head-only and whole-model, and compare on the validation set
- Measure ECE and apply temperature scaling as in Example 2
- Evaluate the end output against your own counts or measurements, split into at least two subgroups, as in Example 3
- Time the pipeline on the real device without warm-up runs and build a budget as in Example 4
- Write a one- to two-page model card and present it with recommended operating conditions
Deliverables
- Fine-tuning comparison table
- Reliability diagram and ECE before and after scaling
- Subgroup end-output evaluation and time budget
- Model card and presentation slides
Checklist
- Table 1 shows the receptive field, the stride and the object size in cells of the layer used
- Table 2 covers before and after temperature scaling, with T and ECE
- Table 3 splits at least two subgroups and times the real device without warm-up runs
- The model card states the valid conditions, the untested conditions, and that people make the final decision
- The data come from Worksheets 1 to 4 and are still split by paddock or date
Instructor guide
Class timing
- Briefing and receptive-field calculation10 min
- Fine-tune the detector two ways30 min
- ECE and temperature scaling10 min
- Subgroup end-output evaluation15 min
- Timing on the device and the time budget10 min
- Model card and presentation15 min
Expected results
- With the backbone of Example 1 (six 3 × 3 layers, 640 tiles, cow 80 × 32 px): receptive field 3, 7, 11, 19, 35, 67 px; final stride 32 leaves the cow 2.5 × 1 cells; backbone 394,928 parameters, head only 514, whole model 395,442 (recomputed). Validation results depend on the group's data; check both methods use the same validation set and the test set is untouched.
- With the simulated data of Example 2 (2,000 boxes, recomputed): bin (0.8, 1.0] holds 1,162 boxes at confidence 0.961 but only 0.872 correct; ECE before 0.102, T = 2.09, ECE after 0.021. Your T may differ; accept it when ECE falls after scaling and accuracy stays the same.
- With Example 3 (12 flights; criteria MAPE at most 3% and no flight off by more than 5%): all flights MAE 5.8 head, bias −3.6%, MAPE 3.7%, fail; morning MAE 1.8, bias −0.9%, MAPE 1.2%, worst 1.8%, pass; midday MAE 9.8, bias −6.2%, MAPE 6.2%, worst 9.7%, fail. Time budget of Example 4: 180 images × 77 tiles, laptop at 45 ms/tile takes 11.3 min, GPU module at 12 ms/tile 3.7 min (both within 20 min); gate video at 15 fps has 66.7 ms, uses 51 ms, margin 15.7 ms (all recomputed).
- In the example backbone the last RF of 67 px is shorter than the 80-pixel cow, so no single position sees the whole cow; add layers or a head that combines positions, and watch the stride so objects are not smaller than one cell, for example a 9.4-pixel cow from a shrunken image is smaller than a conv5 cell (16 px).
- Temperature divides every logit by one value, so the order of predictions and the accuracy do not change; in the example ECE falls from 0.102 to 0.021. With unscaled values the model is overconfident (0.961 but 0.872 correct), so people receive too few boxes and the automatically accepted ones are wrong more often than expected.
- Overall MAPE 3.7% looks like a near pass, but split by time the morning passes (1.2%) while midday fails and under-counts every flight (bias −6.2%), probably because cattle shelter under trees. The right conclusion is to hand over for morning flights only and write that condition, plus untested ones such as the late dry season, into the model card.
- Judge from measured times against 20 minutes or 66.7 ms per frame. The slow case is what makes the job late; the mean on the development machine hides slow frames, and the real device is usually slower. The 15.7 ms margin in the example is enough but small, so any model change needs re-timing.
Discussion questions
- When the farm changes camera or the grass changes colour with the season, how will the team see the system degrading before accuracy drops?
- If a downloaded model gives different results in two runtimes, what should the team check?
- Does stating limitations honestly in the model card help or hurt the chance that the farm accepts the system?
Adapting to student background
- Upper secondary (M.6)
- Have them compute the receptive field layer by layer with r_l = r_(l−1) + (k − 1)j_(l−1) and the 5-bin ECE from the table by hand before using code.
- Vocational certificate
- Give them the timing on the edge device and safe battery charging, and have them read ECE from a reliability diagram drawn on graph paper before seeing the formula.
- Diploma
- Extension: export the model to ONNX, run the same test image in two runtimes and check they agree, then test the wrong-channel-order case of Example 5.
6Worksheet 6 Build a maintenance data set and split it without leaking
Analysis activity · About 1.5 h of class time · CLO5, CLO4
Objective: Build labels from a failure log, choose H and baselines, then split the data to match the deployment question while checking for leakage at every step
Equipment
- Computer with Python, numpy, pandas, scikit-learn and matplotlib
- The example code at /downloads/uat-456/
- The department's real flight or PLC logs (if available), with person-identifying columns removed
Safety
- Desk work, no flying; keep any real data that identifies a person within the group
Steps
- Run Example 1 with the group's seed and report the number of flights, failures and the prevalence table by H
- Choose one H with reasons from the technicians' lead time and explain how the end-of-log rows are handled
- Compute two baselines (always healthy, and a single-threshold rule) and report accuracy, recall and precision
- Run Example 2 with 50, 500 and 5,000 random features and write a short note on why the wrong method looks too good
- Run Example 3 with cut days 150, 200 and 300 and choose a split for a fleet that buys new drones every year
- Check all ten features one by one for whether the value is known at prediction time, with reasons
Deliverables
- Prevalence-by-H table and baseline table
- Short note on leaky feature selection
- Table comparing splits and the chosen split
- Feature-by-feature check table
Checklist
- Table 1 uses the labelled count after dropping end-of-log rows, not labelling them healthy
- Both baselines report accuracy, recall and precision
- Table 2 states the deployment question each split answers, with SD and test prevalence
- Table 3 covers all 10 features (the nine and pct_life) with reasons
- The chosen H is justified by the group's assumed parts-ordering and repair-queue times
Instructor guide
Class timing
- Briefing; run Example 1 and build labels15 min
- Choose H and compute baselines15 min
- Example 2, leaky feature selection15 min
- Example 3, comparing splits25 min
- Feature-by-feature check15 min
- Wrap-up and hand-in checklist5 min
Expected results
- With the lesson's seed 482 (recomputed with pandas): 6,806 flights, 61 failures; prevalence at H 7, 14, 21, 30, 60 days = 0.039, 0.071, 0.106, 0.151, 0.308. At H = 21, 6,404 labelled, 679 positive; always healthy accuracy 0.894, recall 0; rule vib_r5 > 16 accuracy 0.845, caught 408/679 (recall 0.60), 722 false alarms, precision 0.36. The group's seed gives other numbers with the same pattern.
- Lesson output (needs scikit-learn) at cut day 250: random by flight 0.850 (SD 0.023), by time 0.761, by airframe GroupKFold 0.596 (SD 0.138), StratifiedGroupKFold 0.603 (SD 0.030); time-split test prevalence 0.113. At cut days 150, 200, 300 the test prevalence recomputes to 0.103, 0.112, 0.112 (399, 323, 102 positive flights). The group's PR-AUC should rank the same way: random highest, airframe lowest.
- vib, temp, amps, hours, ambient, payload: known after that flight (hours is the current motor's hours). vib_r5, temp_r5, amps_r5: known, because they average only the past 5 flights. pct_life: not known, because motor_hours comes from the future failure record.
- About 89% of flights are healthy, so always predicting healthy scores 0.894 while catching no failing motor. The rule catches 60% but raises 722 false alarms, which drops its accuracy to 0.845. Always report recall, precision and prevalence with accuracy.
- The more random features, the more of them correlate with the 120 labels by chance, so selecting before the split inflates accuracy more (the lesson gives 0.742 at 500 features), while the Pipeline stays near 0.5 every time. The group's values may differ, but the direction must be the same.
- Split by airframe (StratifiedGroupKFold), because the question is about drones never seen. It is lowest (0.603) because the model does not know a new airframe's baseline, while a random split lets it memorise each airframe, a gap of about 0.25. Report the mean with its SD, because the uncertainty comes from the number of airframes.
- PR-AUC jumps from 0.603 to 0.981, one feature holds 0.62 of the importance, and pct_life is missing in 2,036 of 6,404 rows (recomputed), all negatives, so the missing pattern gives the answer away. Remove failure-log columns right after building labels, keep only fault, and keep separate label and feature tables.
Discussion questions
- Who should set H, the data analyst or the head technician, and why?
- If a model scores far better than expected, what should the team check before celebrating?
- Which columns of the department's real flight logs identify people, and when should they be removed?
Adapting to student background
- Upper secondary (M.6)
- Have them compute prevalence and the always-healthy accuracy by hand, and use probability to explain why some of 500 random features must correlate with the labels by chance.
- Vocational certificate
- Start with a 20-row paper flight table: label by hand which flights fail within 21 days and strike out the undecidable end rows before running code; fill Table 3 by asking when a technician would know each value.
- Diploma
- Extension: if the department has real flight logs, export a per-flight summary of at least 100 flights from several airframes and repeat the baselines and the split comparison on real data.
7Worksheet 7 Choose and evaluate classifiers to match the task
Analysis activity · About 1.5 h of class time · CLO4, CLO5
Objective: Read classifier results with metrics suited to imbalanced data, choose a model family, and report a one-shot test result against the technicians' rule
Equipment
- Computer with Python, numpy, pandas, scikit-learn and matplotlib
- The example code at /downloads/uat-456/
- The department's real flight or PLC logs (if available), with person-identifying columns removed
Safety
- Desk work, no flying; keep any real data that identifies a person within the group
Steps
- Run Example 1 with thresholds 0.3, 0.5 and 0.7 and tabulate precision and recall against the technicians' rule
- Project the model's precision at an assumed 3% prevalence and write how many false alarms a technician sees per correct alarm
- Run Example 2 with acceptable cap-torque bands of 0.3 and 0.8 N·m and try removing the err feature
- Pick a new set of 12 caps, compute the root Gini and the best split by hand, and compare with DecisionTreeClassifier
- Tabulate boosting learning rates 0.3, 0.1 and 0.03 against 50 to 500 trees and mark where overfitting starts
- Run Example 5 with test cut days 200 and 300 and write a one-page report on the chosen model family and why
Deliverables
- Precision and recall table by threshold
- Hand Gini calculation
- Learning-rate versus number-of-trees table
- One-page model-choice report
Checklist
- Table 1 covers thresholds 0.3, 0.5, 0.7 and the technicians' rule, with TP and FP
- Table 2 shows G = 1 − Σp² and the hand result matches DecisionTreeClassifier
- Table 3 marks where the hold-out score starts to fall or stops rising (overfitting starts)
- The one-page report states the model family, main metric, expected prevalence, alert budget and baseline
Instructor guide
Class timing
- Briefing, thresholds and prevalence projection20 min
- Cap data and acceptance bands15 min
- Hand Gini10 min
- Boosting table20 min
- Walk-forward and model-choice report20 min
- Wrap-up and hand-in checklist5 min
Expected results
- Lesson output at threshold 0.5 (training period, five airframe folds): logistic TP 150, FP 122, precision 0.55, recall 0.32; weighted TP 373, FP 758, precision 0.33, recall 0.80; technicians' rule (whole table, module 6) recall 0.60, precision 0.36. Threshold 0.3 should raise recall and lower precision, 0.7 the reverse; the group's seed may differ but must follow this order.
- With the lesson's set (4 of 12 defective): root G = 1 − (2/3)² − (1/3)² = 0.444; best cut torque at most 2.250; left 9 caps with 1 defective, G = 0.198; right 3 caps all defective, G = 0; weighted 0.148 (recomputed). A new set gives other cut points; check the chosen cut has the lowest weighted Gini and matches the tree.
- Lesson output (depth-3 trees up to 300): η 0.3 rises fast but stumbles (0.599 at 10 trees, 0.558 at 100, 0.647 at 300); η 0.1 rises steadily to 0.704 at 300; η 0.03 is still climbing at 0.659 and needs more trees. At 500 trees η 0.3 usually starts to fall first. Choose the number of trees from the hold-out, not the training score.
- Using recall 150/465 = 0.323 and false-alarm rate 122/4,043 = 0.030 at threshold 0.5: precision = 0.323 × 0.03 / (0.323 × 0.03 + 0.030 × 0.97) = 0.248, so about 3.0 false alarms per correct alarm (the same formula at 2% gives 0.179, matching the lesson table; recomputed).
- No. ROC-AUC 0.918 against 0.914 and PR-AUC 0.617 against 0.623 are nearly equal, so the models rank flights almost identically. Only the operating point on the same curve moves (recall 0.32 to 0.80 for precision 0.55 to 0.33), and that point must be chosen from the cost of the work.
- Caps fail on both sides (loose and cracked) and the limit shifts with line speed, so a straight boundary separates only one side (PR-AUC 0.177, near the 0.088 prevalence). |torque − setpoint| states the question directly, so it scores 0.801, above complex models. Without err, logistic regression falls back, while trees and a scaled SVM still find the pattern.
- In the lesson the good families differ by at most 0.05 while the SD across windows is 0.10 to 0.13, so the difference is noise. Conclude they cannot be separated, choose by a rule set in advance or prefer the simpler model, and report one test, for example boosting PR-AUC 0.760 at a 10% alert budget (190 alerts), precision 0.71, recall 0.63, against the rule's 325 alerts at precision 0.42: 135 fewer alerts at the same recall.
Discussion questions
- Why is the random forest's out-of-bag score (0.831) above the airframe split (0.597) and even above the real test?
- If technicians can handle only a set number of alerts a day, how should an alert budget set the threshold instead of 0.5?
- What other technician knowledge could become a feature that answers the question directly?
Adapting to student background
- Upper secondary (M.6)
- Have them derive precision as a function of prevalence from Bayes' theorem and compute the Gini of every possible cut for the 12 caps by hand.
- Vocational certificate
- Have them lay 12 cap cards in torque order, place a ruler as a cut and count defective caps on each side before computing Gini, and use a fill-in TP and FP version of Table 1.
- Diploma
- Extension: run Example 5 with test cut days 200 and 300 and report whether the selected model changes, citing each window's SD.
8Worksheet 8 Regression, regularisation and time-series forecasting
Analysis activity · About 1.5 h of class time · CLO4, CLO5
Objective: Apply ridge and lasso to correlated features, report the valid range of the model, and evaluate a time series with walk-forward against persistence
Equipment
- Computer with Python, numpy, pandas, scikit-learn and matplotlib
- The example code at /downloads/uat-456/
- The department's real flight or PLC logs (if available), with person-identifying columns removed
Safety
- Desk work, no flying; keep any real data that identifies a person within the group
Steps
- Run Example 1 with 3, 5, 10 and 20 training packs and compare the SD of the cycles coefficient for OLS and ridge
- Add one more feature correlated with cycles and see how the OLS SD changes and how much ridge helps
- Run Example 2 with a finer alpha grid and choose a value with reasons from the flatness of the CV curve
- Run Example 3 with the training edge at cycles 200 and 350 and record RMSE by band
- Write a short model note stating the training range and the cycle range not to use
- Run Example 4 adding lag48 and removing day, and compare walk-forward and shuffled-fold MAE
Deliverables
- Graph of coefficient SD by number of packs
- RMSE-by-band table
- Short model note
- Table of walk-forward and shuffled-fold MAE and the skill against persistence
Checklist
- Table 1 splits by pack and never puts one pack's measurements on both sides
- Features are standardised before ridge and lasso, and alpha is chosen by pack-wise CV
- Table 2 covers all three bands for both edges, 200 and 350
- Table 3 includes persistence as the baseline and uses shift before rolling
- The model note states the training cycle range and the range not to use
Instructor guide
Class timing
- Briefing and Example 1 by number of packs20 min
- Extra correlated feature and finer alpha grid15 min
- Training edges 200 and 35020 min
- Short model note10 min
- Walk-forward time series20 min
- Wrap-up and hand-in checklist5 min
Expected results
- At 5 packs (recomputed with a closed-form numpy fit, matching the lesson): OLS cycles coefficient −0.103, SD 0.105, RMSE 0.077; ridge α = 1 SD 0.060, RMSE 0.073; α = 10 SD 0.022, RMSE 0.077; α = 100 SD 0.009, RMSE 0.117. At 3 packs the SD should be higher, and at 10 and 20 it should keep falling, with ridge below OLS at every size.
- Lesson output at edge 300 (needs scikit-learn): ridge 0.093, 0.204, 0.530 Ah; random forest 0.106, 0.330, 0.783; boosting 0.105, 0.334, 0.792. At edge 200 every band should be worse; at edge 350 the trees have seen the start of the knee, so 360-400 should improve clearly, but they still cannot go beyond what they have seen.
- Persistence MAE 0.091 A and same-hour-yesterday 0.346 A (recomputed). Lesson output: ridge walk-forward 0.075, shuffled 0.065, skill 18%; boosting 0.073 and 0.054, skill 20%. With lag48 added and day removed, boosting's gap between shuffled and walk-forward MAE should narrow, because the trees can no longer memorise each day's level from day.
- More data pins down how credit is split between features carrying the same information (ir 0.93 and throughput 0.97 with cycles), so the split swings less. Predictions can be good while coefficients swing (OLS RMSE 0.077 at SD 0.105), so a single coefficient must not be read as the effect of cycles on capacity.
- In the lesson, CV RMSE for α 0.01 to 10 is 0.0609 to 0.0612, flat and indistinguishable, and worsens at 100 (0.0779). Every value in the flat range is equivalent, so lean towards the strongest one for stability. A strong answer cites the group's curve and reports RMSE on unused packs (lesson 0.0699 Ah).
- A random forest predicts with leaf averages of the training data, so it cannot go beyond what it has seen and its trend goes flat. At edge 350 the nearby band improves but further bands are still too high (lesson: pack 3 at 400 cycles, true 7.91 Ah, forest 8.31). The note must state the trained range (for example 10 to 300 cycles) and require more data and retraining when packs exceed it.
- Skill = 1 − MAE_model/MAE_persistence, for example 1 − 0.073/0.091 = 0.20. Shuffled folds put neighbouring hours and days on the training side, so the model interpolates between seen points and trees memorise each day's level from day (ridge 13% and boosting 26% too good), while real use must forecast hours not yet seen.
Discussion questions
- If a client asks what capacity a battery will have at 400 cycles, how should the team answer when the model was trained to 300?
- Do ridge's MAPE of 2.4% and RMSE of 0.262 Ah tell the same story?
- Why might a skill of only 20% over persistence still be worthwhile for alerting on abnormal motor current?
Adapting to student background
- Upper secondary (M.6)
- Have them compute MAE, RMSE and skill on a small example by hand, write ridge's closed form (XᵀX + αI)⁻¹Xᵀy and explain why a large α pushes coefficients towards zero.
- Vocational certificate
- Use the department's training-drone battery records if available: plot capacity against cycles by hand to see the knee before modelling, and use a fill-in RMSE table.
- Diploma
- Extension: with real motor-current or battery-voltage logs from the department, build persistence as the baseline and report one model's walk-forward skill.
9Worksheet 9 Cluster and reduce the production-line data
Analysis activity · About 1.5 h of class time · CLO4
Objective: Choose the number of clusters and the clustering technique to suit the data, set up DBSCAN, read PCA from its loadings, and read a t-SNE plot with care
Equipment
- Computer with Python, numpy, pandas, scikit-learn and matplotlib
- The example code at /downloads/uat-456/
- The department's real flight or PLC logs (if available), with person-identifying columns removed
Safety
- Desk work, no flying; keep any real data that identifies a person within the group
Steps
- Run Example 1 with the group's seed, tabulate k from 2 to 6 and write which k you choose and why
- Remove the standardisation before k-means and report how the result changes
- Run Example 2 with 1 to 8 components, look at the BIC and explain why the largest value should not be chosen
- Run Example 3 with eps refined between 0.8 and 1.5, choose a value and say who should inspect the flights labelled noise
- Run Example 4 on 8 columns of your own data, check the cumulative variance and write what PC1 and PC2 mean from the loadings
- Run Example 5 at perplexity 2, 15 and 200 and write which conclusions stay the same in every setting
Deliverables
- Table of k with reasons and the BIC table
- Table with the chosen eps and a proposal for the noise points
- Meaning of PC1 and PC2
- One-page summary of when to use k-means, GMM and DBSCAN
Checklist
- Data are standardised before k-means, DBSCAN and PCA, with the unstandardised result reported for comparison
- Table 1 covers k from 2 to 6 and BIC for 1 to 8 components, with the reason for the choice
- Table 2 has at least 5 eps values between 0.8 and 1.5 and marks the chosen one
- Table 3 explains PC1 and PC2 from the loadings in terms of the line's physics
- The one-page summary says when to use k-means, GMM and DBSCAN on the group's data
Instructor guide
Class timing
- Briefing and k-means15 min
- No standardisation, and GMM BIC15 min
- DBSCAN15 min
- PCA on the group's data15 min
- t-SNE at several perplexities15 min
- One-page summary and checklist15 min
Expected results
- Lesson output with seed 482 (needs scikit-learn): silhouette for k 2 to 6 = 0.538, 0.479, 0.490, 0.373, 0.317; ARI 0.217, 0.852, 0.901, 0.659, 0.520; BIC for 1 to 6 = 22,146, 14,038, 10,517, 10,815, 11,110, 11,407, lowest at 3; full GMM ARI 1.000 with weights 0.50, 0.33, 0.17, matching 900, 600, 300 of 1,800 minutes (recomputed). Other seeds differ, but BIC should bottom out near 3.
- Lesson output (548 flights): 4th-neighbour distance 98% quantile 1.47, maximum 6.74. With min_samples 5: eps 0.7 gives 5 clusters and 68 noise; eps 1.0 gives 4 clusters and 18 noise (all 10 anomalies); eps 1.5 gives 3 clusters and exactly 10 noise but absorbs the night survey. A sensible choice is about 1.0 to 1.2, which keeps the night survey as its own cluster; accept other values if the reasoning cites the group's table.
- Lesson data (recomputed with numpy): on raw units PC1 explains 0.9995 with a speed loading of 0.999; standardised, 0.563, 0.233, 0.120, cumulative 0.916 at three axes. PC1 has similar positive weights on speed, conv_amps, vib and bearing_temp (0.43 to 0.46), the line-load axis; PC2 contrasts torque and air_bar with fill_sd; PC3 is water_temp (0.93). t-SNE trustworthiness 0.983 to 0.987 at every setting (lesson).
- Silhouette peaks at k = 2 (0.538) because it favours coarse, clean structure, but ARI at k = 2 is only 0.217 since two modes merge. The technician knows there are small bottles, large bottles and changeover, so k = 3 (ARI 0.852). A strong answer combines the internal criterion with domain knowledge.
- Without standardisation, speed in the hundreds dominates every distance: PC1 explains 99.95% with a speed loading of 0.999, an effect of units, not structure, and k-means splits on speed alone.
- Not always: noise may be a new, rare flight type, such as the 8 night-survey flights that become noise at eps 0.5 or min_samples 10. Send them to people who know the flying, such as the chief pilot or technician, before calling them abnormal.
- What holds is which points lie near which (trustworthiness about 0.98). Do not read cluster size (changeover is truly 2.49 times wider but looks 0.59 to 0.73 times as wide), between-cluster distance (true 0.71, plots 0.88 to 2.49), or cluster on the plot coordinates.
Discussion questions
- If BIC and silhouette disagree, what should the team trust?
- Does low variance in PCA mean unimportant, when the signal of a rare fault may sit on that axis?
- Why must the eps and min_samples used be recorded in the report?
Adapting to student background
- Upper secondary (M.6)
- Have them run one-dimensional k-means on 6 points by hand for two rounds, and compute a single point's silhouette and the cumulative variance ratio from eigenvalues by hand.
- Vocational certificate
- Use 8 columns from a real line or the lab PLC, ask a technician how many modes the line has before clustering, and circle groups by hand on a printed 2-D scatter before seeing the result.
- Diploma
- Extension: try scikit-learn's HDBSCAN on the flights of Example 3 and compare whether it handles clusters of different density better.
10Worksheet 10 Hand over a maintenance model with results you can trust
Analysis activity · About 1.5 h of class time · CLO6, CLO5
Objective: Check that tuning really helped, choose a threshold from cost, report results with uncertainty, set monitoring conditions and write a model card
Equipment
- Computer with Python, numpy, pandas, scikit-learn and matplotlib
- The example code at /downloads/uat-456/
- The department's real flight or PLC logs (if available), with person-identifying columns removed
Safety
- Desk work, no flying; keep any real data that identifies a person within the group
- Do not use a maintenance model to assess people, and do not load model files from unknown sources
Steps
- Run Example 1 with a random-search budget of 60 and nested cross-validation over random-forest hyper-parameters; report the selection bias
- Run Example 2 with defective-cap costs of 20, 60 and 150 baht, compute p* by hand and compare the cost per 1,000 caps
- Run Example 3 with mid-job failure costs of 15,000 and 100,000 baht and write a one-sentence report statement honest about the uncertainty interval
- Run Example 4 with vibration shifts of 1.0 and 5.0 (and negative values) and see whether the retraining rule still catches them
- Run Example 5 on the bottling-line data of module 9, compute grouped permutation importance and write a one-paragraph explanation for a technician
- Write a one-page model card stating the use, the prohibitions, the test result with its uncertainty interval, the retraining condition and the personal data removed
Deliverables
- Selection-bias table and p*-by-cost table
- Report statement of the test result with its uncertainty interval
- Permutation-importance explanation for a technician
- One-page model card
Checklist
- Table 1 reports the nested-CV outer score as the expectation for new airframes, not the search score
- Table 2 shows p* = c_FP/(c_FP + c_FN) by hand for all three costs and states the costs are assumed
- The uncertainty interval resamples whole airframes (40) and the report statement does not claim beyond it
- The model card states the use, the prohibitions (not for judging pilots or people), the retraining condition and the personal data removed
- The feature table has no person-identifying column and airframe IDs are not tied to names
Instructor guide
Class timing
- Briefing and nested CV20 min
- Thresholds from cost15 min
- Policy cost and uncertainty interval15 min
- Drift trials10 min
- Permutation importance15 min
- Model card and checklist15 min
Expected results
- Lesson output: default CV 0.561; grid 0.631; random 27 draws 0.592 to 0.632; nested CV search score 0.578, outer 0.524, default 0.531; bias 0.578 − 0.524 = 0.054; tuned minus default −0.007 (SD 0.109). At a budget of 60 the best score usually rises slightly while the outer score does not clearly improve; a random forest should show the same picture.
- p* = 3/(3 + 20) = 0.1304, 3/(3 + 60) = 0.0476, 3/(3 + 150) = 0.0196 (recomputed; evaluation set 1,200 caps, 106 defective). At 60 baht the lesson gives raw forest 1,718, sigmoid 1,555, isotonic 1,645 baht per 1,000 caps (accept all 5,300, reject all 2,735). At 20 baht accepting all costs 1,767, the threshold rises and fewer caps are rejected; at 150 baht accepting all costs 13,250, the threshold falls and more good caps are rejected.
- Lesson output for the test window, 22 failures (assumed costs: inspection 1,500, planned replacement 6,000, mid-job failure 40,000 baht): run to failure 880.0; every 30 days 120 inspections, 9 caught, 13 missed, 754.0; technician rule 96, 16, 6, 480.0; model τ 0.2 94, 20, 2, 341.0 thousand baht (recomputed from the counts). Drift: KS of vib_r5 stays at or below 0.113 in the clean world and 0.232 to 0.305 after the shift; alert rate 0.107 to 0.142 (+33%). At a 15,000-baht failure cost τ usually rises and the gap to the rule narrows; at 100,000 τ falls and the gap widens.
- Mostly because the maximum of noisy numbers rises: more trials push the best score up without a better model. Nested CV in the lesson shows a bias of 0.054 and no gain over the default on unseen airframes (−0.007, SD 0.109), so the outer score is what must be reported.
- p* = 3/153 = 0.0196. A probability of 0.03 is above p*, so reject it: rejecting costs 3 × 0.97 = 2.91 baht in expectation against 150 × 0.03 = 4.50 baht for releasing it.
- A good statement: in this test window (22 failures, assumed costs) the model cost about 29% less than the technicians' rule (139 thousand baht, 95% interval from resampling airframes −269 to −37 thousand), so it is unlikely to be luck alone, but it is not an annual saving. Airframes are resampled because flights of one airframe are not independent; resampling flights gives an interval that is too narrow (PR-AUC width 0.105 against 0.190).
- vib and vib_r5 are correlated at 0.95; shuffle one and the model still uses the other, so the separate values are low (0.017 + 0.099 = 0.116), while shuffling both gives 0.211. Tell the technician that removing all vibration information drops the warning ability nearly as much as flight hours, and that importance says what the model uses, not what causes the failure.
- An upward shift makes every airframe look more worn, so alerts rise and more are wrong. A downward shift makes airframes look healthier, so alerts fall and more failing motors are missed, which is more dangerous. KS measures the size of a distribution change in either direction, so it still fires if the shift is large enough (a 1.0 shift may not reach 0.2), and the alert rate shows a fall. Report the group's actual run.
Discussion questions
- If the vibration readings shift because of a new batch of propellers, should the model be retrained at once or the maintenance records checked first?
- Why must model files from unknown sources never be loaded?
- If management asks to use the model to rank pilots, how should the team respond under the model card and the Personal Data Protection Act?
Adapting to student background
- Upper secondary (M.6)
- Have them derive p* from the expected costs c_FP(1 − p) < c_FN p and compute the policy costs from the counts by hand before reading the simulation code.
- Vocational certificate
- Have them play the technician receiving alerts, use a fill-in cost sheet (inspections × 1,500 + caught × 6,000 + missed × 40,000), and write the permutation-importance explanation in a technician's words.
- Diploma
- Extension: run Example 5 on the module 9 bottling-line data or the department's real PLC records, compute grouped permutation importance of correlated sensors, and add input checks before prediction.
11Worksheet 11 A pipeline that receives, checks and records frames
Lab · About 3 h of class time · CLO8, CLO7
Objective: Measure real frame times, choose a queue size and drop policy, check frame quality, and choose a filter by measuring the feature that must be kept
Equipment
- Training drone with camera, or sample video from the lecturer
- Computer with Python and OpenCV
- The module 11 example code
Safety
- If flying to record, fly within CAAT conditions in visual line of sight, keep people clear, check batteries and propellers before flight, and do not record faces unnecessarily
- If using the lecturer's sample video or images, it is desk work with no flying
Steps
- Record at least 30 s of slow flight and read it with VideoCapture, logging the arrival time of each frame
- Report missing frames, the real frame rate and the longest gap as in Example 1
- Time the group's processing stage, feed it to the queue simulator and choose a queue size with reasons
- Add the quality gate, tune thresholds on real frames and show three dropped frames with causes
- Try three filters on a frame with added noise and measure how much of the line or edge is left
- Separate a dominant colour with HSV and compare with a hand-drawn area
Deliverables
- Frame-time table and missing frames
- Queue simulation results and the reason for the choice
- Report of frames accepted and dropped with examples
- Filter comparison table and HSV result
Checklist
- Table 1 uses times from a clock that never goes backwards (time.monotonic), not VideoCapture get()
- Table 2 uses the group's measured processing times and the queue choice cites p95 latency
- Table 3 shows at least three dropped frames with causes, and thresholds set from the job's real frames
- Filters are judged on the line or edge to keep, not RMSE alone, and HSV is compared with a hand-drawn area
- The submitted video shows no faces unnecessarily
Instructor guide
Class timing
- Briefing, safety, drone check and recording flight (or sample video)40 min
- Read the video and log frame times30 min
- Time the processing stage and simulate the queue30 min
- Quality gate on real frames35 min
- Filters and HSV30 min
- Wrap-up and hand-in checklist15 min
Expected results
- With the simulated data of Example 1 (30 fps, 4.0 m/s, GSD 20 mm, recomputed): 282 of 300 received, 18 missing, real rate 28.3 fps, longest gap 531 ms (16 periods), during which the drone moved 2.13 m = 106 px against a normal 6.7 px per frame. Real video will differ; accept values computed from your own logged times, with the gap in both ms and px.
- With the times of Example 2 (25 ms for 70%, 62 ms for 30%, mean 36.4 ms, load 1.09, recomputed): queue 1 drop-new 85.5%, 53/98 ms; queue 1 drop-old 86.0%, 47/85 ms; queue 4 drop-new 91.2%, 133/215 ms; queue 4 drop-old 91.0%, 121/178 ms; unbounded 100%, 2,609/5,097 ms. Little's law: 27.3 × 0.121 = 3.3 frames.
- With the synthetic frames of Example 3: defocus 0.01 of the reference, motion blur 0.12, dark 0.12 with mean 52.2, over-exposed 1.10 but 73.3% clipped, all four dropped. Filters of Example 4 on salt and pepper: 3 × 3 median RMSE 0.8 with the crack kept at 50.0; 5 × 5 median erases the crack (0.0). HSV in Example 5 gives 7.2, 15.4, 1.2% against true 7.0, 14.8, 1.1%, exact after opening. Judge the group's real frames by the same pattern.
- When frames go missing the real spacing is longer than assumed, for example a 531 ms gap moves the drone 106 px instead of 6.7 px, so taking every 32nd frame gives overlap as low as 0.71 while choosing by time gives 0.77 to 0.80 (key-frame spacing for 80% is 0.2 × 21.6/4.0 = 1.08 s or 32.4 frames, recomputed).
- Load = mean processing time × fps. Above 1, an unbounded queue processes everything but looks at images seconds old (2,609 ms in the example). Navigation should use a short drop-old queue for the latest image; inspection should drop nothing, recording every frame to disk and processing after the flight.
- The variance of the Laplacian depends on surface roughness: sharp smooth plaster scores 28.2 while a blurred rough surface still scores 291.2, so a fixed threshold of 100 rejects the good image and accepts the blurred one; compare with the median of recent accepted frames of the same scene. The over-exposed frame scores 1.10 because scaling brightness magnifies pixel differences, but 73.3% of pixels are clipped at 255 and the information is gone.
- For salt and pepper use a median smaller than twice the width of the feature (3 × 3 for a 2-pixel crack). The 5 × 5 median's RMSE of 5.6 looks good but erases the crack, which is only 10 of the 25 pixels in the window. For Gaussian noise the bilateral filter has the lowest RMSE, 4.4, but keeps only 31.4 of 50 units of crack contrast, so measure the feature the job needs.
Discussion questions
- If CAP_PROP_POS_MSEC reads 0 on every frame, what does it mean and where else can frame times come from?
- What happens to a 16-bit thermal frame cast to 8 bits with astype, and why must thresholds be set on temperature rather than grey level?
- Which canal tasks may drop frames, and which must never drop any?
Adapting to student background
- Upper secondary (M.6)
- Have them compute the load, Little's law and the key-frame spacing by hand before running the simulator, and explain why a queue cannot help when the load exceeds 1.
- Vocational certificate
- Give them the pre-flight check, the recording flight and camera set-up, then have them look at dropped frames beside their sharpness numbers; provide a script template where only thresholds are filled in.
- Diploma
- Extension: build a real two-thread pipeline (capture and processing) with the chosen queue, measure the real p95 latency and compare it with the simulator.
12Worksheet 12 Registering and comparing two flights
Lab · About 3 h of class time · CLO7, CLO8
Objective: Set Canny thresholds, find lines with Hough, register images with ORB and SIFT, test the repeating-pattern case and build a change detector
Equipment
- Camera or training drone and a textured surface (concrete, wall)
- Tape measure and a small object to place as a change
- Computer with Python, OpenCV and the module 12 example code
Safety
- If flying to record, fly within CAAT conditions in visual line of sight, keep people clear, check batteries and propellers before flight, and do not record faces unnecessarily
- If using the lecturer's sample video or images, it is desk work with no flying
Steps
- Photograph the surface twice at least an hour apart with a slightly different angle and light
- Set Canny thresholds from a crack-free area and report continuity and stray edges
- Find the angle and spacing of regular lines with Hough and compare with the tape measure
- Register the two images with ORB and SIFT; report pairs, inliers, time and the error at five check points
- Try a repeating-pattern scene and record how the matching fails
- Place one new object, run the change detector and report the regions found and the false ones
Deliverables
- Edge images and continuity table
- Table of angle and spacing against the tape
- ORB versus SIFT inlier and error table
- Change-detection result with false regions
Checklist
- Canny thresholds are set from a crack-free area and the percentile used is stated
- Table 2 converts pixels to metres with the GSD and compares with the tape in the image
- Table 3 reports inliers and the error at five check points, not only that a homography was found
- The change result reports both real regions found and false regions
- Images show no faces, and the time and light of each shoot are recorded
Instructor guide
Class timing
- Briefing, safety, drone check and first shoot30 min
- Canny thresholds30 min
- Hough and tape comparison25 min
- Second shoot and ORB and SIFT registration45 min
- Repeating-pattern trial15 min
- Change detection and wrap-up35 min
Expected results
- With the synthetic image of Example 1 (high threshold from the 99.8th percentile of a crack-free area, 74; low 37): one threshold covers 73.3% with 9 gaps, longest 13 px, 140 stray pixels; hysteresis covers 100% with no gaps but 1,250 stray, 403 after dropping pieces under 40 px; thresholds too low give 19,997 (26% of the image). Real images should show the same pattern.
- With Example 2 (GSD 0.040 m): tilt 3.00 degrees, width 12.02 m (true 12.00), centre offset 17.9 px = 0.72 m, joint spacing 125.0 px = 5.00 m (recomputed). Against the group's tape, accept differences explained by GSD uncertainty (an imprecise shooting distance) and thick lines producing several overlapping lines.
- With Example 3: normal texture ORB 801 pairs, 781 inliers, corner error 0.18 px; SIFT 833 pairs, 833 inliers, 0.03 px; repeating pattern ORB 177 pairs, 33 inliers, 9.27 px; SIFT 0 pairs, no homography. Example 5: plain difference finds 2 of 2 real changes with 288 false; brightness-normalised 80; shift-tolerant with cleaning 0 (threshold 4σ = 26.2). On real images SIFT is usually slightly more accurate than ORB but slower.
- Hysteresis trades line continuity against stray edges: coverage goes from 73.3% to 100% but stray pixels from 140 to 1,250. Dropping pieces shorter than 40 px cuts them to 403 because concrete texture gives short edge pieces while a crack is long and continuous.
- 118 × 0.040 = 4.72 m, −5.6% from 5.00 m (recomputed). The real spacing may differ from the design, the flight may have been lower than assumed so the real GSD is below 0.040, or a thick line gave overlapping lines not yet averaged; check against a tape or a target of known size in the image.
- Identical panels give descriptors so close that the ratio approaches 1: SIFT rejects every pair, ORB keeps 177 but only 33 inliers (18.6%) and a 9.27 px error. The ratio test works correctly; the scene simply has nothing that tells panels apart. Use a GNSS position to restrict which panel to match, or targets that differ from panel to panel.
- Different light (12%) raises the difference everywhere and a 1.5 px misregistration turns every edge into a double line. Layer one matches the median and robust spread, cutting false regions from 288 to 80; layer two compares with the local maximum and minimum, so small shifts do not count; layer three thresholds at 4σ of the unchanged area, then opens, closes and drops small regions, leaving 0.
Discussion questions
- How much error does a chain along the 12 km canal accumulate without targets, and how often should targets be placed (Example 4: 25,000 pairs give 362.0 mm, anchoring every 200 pairs keeps it within 5.6 mm)?
- When is ORB enough, and when is the extra time for SIFT worth paying?
- How will the change detector's thresholds, tuned on this image set, be proved again by an acceptance test before real use?
Adapting to student background
- Upper secondary (M.6)
- Have them find (ρ, θ) for a vertical and a horizontal line by hand and split accumulated error into the systematic Nb and the random σ√N before running the simulation.
- Vocational certificate
- Give them the two shoots by tripod or drone, placing the tape and the changed object and measuring real distances; use a prepared script where only thresholds change.
- Diploma
- Extension: build a two-strip mosaic with feathering and gain compensation as in Example 4 on real images, and measure the brightness step across the seam against plain pasting.
13Worksheet 13 A baseline for classification, detection and segmentation
Analysis activity · About 3 h of class time · CLO7, CLO9
Objective: Build a classical baseline and evaluate it with precision, recall, IoU and the tolerant metric, with the group's decision table
Equipment
- At least 20 real images of a concrete surface or wall
- Computer with Python, OpenCV and scikit-learn
- The module 13 example code
Safety
- Mainly desk work; no flying
- Keep images showing faces or number plates out of the dataset
Steps
- Cut at least 200 patches of 128 × 128 pixels, label two classes and split by source image
- Extract features, train logistic regression and report accuracy against always answering 'normal', with the confusion table
- Choose the threshold on the validation set, report the test result and explain the difference
- Detect a repeated object with a template; report precision and recall at IoU 0.5 and test light and scale
- Label crack masks by hand on five images, run black-hat and report strict Dice and the 2-pixel tolerant metric
- Write a 5-method by 5-criterion decision table and find the weight at which the result flips
Deliverables
- Confusion table and the chosen threshold
- Template-matching precision and recall table
- Table of the two segmentation metrics
- Decision table with sensitivity analysis
Checklist
- Sets are split by source image, so patches of one image never sit in different sets
- The threshold is chosen on a validation set with real proportions and the test result is reported once
- Table 2 matches one to one at IoU of at least 0.5 and tests both light and scale
- Table 3 reports both strict Dice and the 2-pixel tolerant metric
- The decision table filters by the required output first and states the scores are the team's judgement
Instructor guide
Class timing
- Briefing, cutting and labelling patches45 min
- Features, training and the confusion table30 min
- Choosing the threshold on validation25 min
- Template matching30 min
- Crack masks and black-hat35 min
- Decision table and wrap-up15 min
Expected results
- With Example 2 (test 6,000 patches, 120 cracks = 2%; a 5.0 × 3.0 m panel = 135 × 81 = 10,935 patches, recomputed): always 'sound' accuracy 96.0%, classifier 97.1%; threshold 0.50 recall 96.7%, precision 55.8%, 171 per panel; 0.80 gives 90.8%, 92.4%, 17 per panel; 0.95 gives 84.2%, 99.0%, 2 per panel; the 0.75 chosen on validation gives recall 91.7%, precision 85.9%, 33 per panel (above the target of 20). Real images will differ; check that per-panel counts are false-alarm rate × patches per panel.
- With Example 3 (12 weep holes): normal light at 0.60 gives 14 boxes, TP 12, FP 2 (precision 0.86); at 0.85 TP 12, FP 0; dim light CCOEFF 0.85 still 12/12; SQDIFF 0.20 gives 454 boxes, FP 442 (precision 0.03); images 1.3 times larger with one scale give recall 0.00 (mean peak 0.82 on the true holes); scales 0.8 to 1.5 restore 12/12.
- With Example 4: Otsu IoU 0.05, Dice 0.09 (392 pieces); black-hat Dice 0.85, tolerant precision 0.88; with long thin pieces kept IoU 0.84, Dice 0.91, tolerant precision and recall 1.00; a perfect answer shifted 1 px Dice 0.91, shifted 2 px 0.83. Decision table of Example 1 (recomputed): task A template 4.40, deep detector 2.30, flipping when the robustness weight reaches 0.55 (exact crossing 0.53); task B without labels black-hat 4.10 against 2.30, with 2,000 images deep segmentation 3.43 against 3.15.
- In the example accuracy differs by only 1.1 points (97.1% against 96.0%) while crack recall is 96.7% against 0%. Inspectors work per panel: a false-alarm rate of 1.56% sounds small but times 10,935 patches is 171 per panel, which nobody can check (0.15% × 10,935 ≈ 16 per panel).
- The lesson's 0.75 chosen on validation gives 33 false alarms per panel on test, above the target of 20, because validation held only 2,880 sound patches, so few false-alarm events were counted and the figure fluctuates. Use a large enough validation set, or two stages: a light filter followed by a more accurate decision.
- CCOEFF_NORMED subtracts the mean and divides by the standard deviation of both patches, so a linear light change I' = gI + c cancels, but a fixed-size template no longer fits a larger object and the peak on true holes drops from 0.95 to 0.82, below the threshold. Set the scale range from the real range of flight heights and the threshold from measured scores of real objects.
- No. Method 3's Dice of 0.91 equals a perfect answer shifted 1 px, so the remaining error is at the one-pixel level, beyond the image's resolution; a 2 to 3-pixel line shifted by one pixel overlaps by less than half. Read the tolerant metric and the resulting width (module 14) as well.
- In the example task A flips when the robustness weight rises from 0.20 to about 0.53. A strong answer reports the group's own flip point and notes the scores are the team's judgement; if the flip point is close to the weights used, the result is fragile and needs evidence, such as measuring how much the real appearance varies.
Discussion questions
- Why build a classical baseline before deciding to train a deep model?
- Can a box detector measure crack width? What kind of output does width measurement need?
- If the job allows at most 2 false alarms per panel, how does a two-stage system help?
Adapting to student background
- Upper secondary (M.6)
- Have them compute the IoU of a box shifted by 4 px and the decision-table scores by hand, and find the flip point by solving a linear equation.
- Vocational certificate
- Have them photograph a real wall or floor and label patches on screen, cut their own hole or stud template from a real image, and test light by reshooting in the morning and afternoon.
- Diploma
- Extension: build a two-stage system (a light filter followed by a stricter classifier) and report false alarms per panel against a single stage at the same recall.
14Worksheet 14 Tracking and measuring with uncertainty
Lab · About 3 h of class time · CLO8
Objective: Track an object and measure its speed, build a tracker that copes with occlusion, compute a length uncertainty budget, measure thin lines and estimate a step
Equipment
- A slow object of known speed (foam block on a conveyor or radio-controlled boat) and a video camera
- A reference bar of known length, a test sheet of lines 0.3 to 3 mm wide and two plates 3 mm apart in level
- Computer with Python, OpenCV and the module 14 example code
Safety
- Mainly tripod or ground work; any flying follows CAAT conditions in visual line of sight
- If shooting near water, watch for slippery ground and do not enter the water
Steps
- Track foam or texture with LK and compare the speed with the true one, removing the background motion
- Try frame gaps of 1, 4 and 16 with and without a pyramid, counting the points that pass the backward check
- Write a tracker with TRACK and COAST states and hide the object for 5 to 20 frames
- Find the GSD two ways and compute the uncertainty budget of one length with U at k = 2
- Measure the line widths on the test sheet with FWHM and pixel counting and find the narrowest width that can be trusted
- Photograph the two plates from two stations, estimate the step and compare with a contact instrument
Deliverables
- Table of measured against true speed
- Log of the tracker states during occlusion
- Uncertainty budget of a length with U
- Table of measured against true widths and the step result
Checklist
- Table 1 covers gaps of 1, 4 and 16 frames with and without a pyramid, with background motion removed
- The frames entering COAST and returning to TRACK are logged for every 5 to 20-frame occlusion
- The budget lists each source, combines them by root sum of squares and reports U at k = 2 with units
- Table 3 states the narrowest trustworthy width and reports narrower lines as 'narrower than the measurement limit'
- The step result is compared with a contact instrument and states the baseline used
Instructor guide
Class timing
- Briefing, safety and camera set-up15 min
- LK tracking and frame gaps40 min
- TRACK and COAST tracker30 min
- GSD two ways and the uncertainty budget35 min
- Line-width measurement30 min
- Step measurement and wrap-up30 min
Expected results
- With the synthetic frames of Example 1 (GSD 0.020 m, 30 fps, water 2.1 px/frame, bank −0.3): gap 1 keeps 189 to 190 of 256 points; gap 16 without a pyramid keeps 12, with 3 levels 186; relative motion 2.42 px/frame gives 1.45 m/s (true (2.1 + 0.3) × 0.020 × 30 = 1.44 m/s, recomputed), standard error 0.026 m/s. For the group's object, compare with the conveyor speed or a hand-timed speed.
- With Example 2: the log is fully hidden in frames 58 to 69; the tracker enters COAST at frame 53 and returns to TRACK at 76, final error 0.5 px, worst 8.9 px, while the stateless tracker ends 115.8 px off. Budget of Example 3 (recomputed): geometric GSD 0.2895 ± 0.0145 mm/px; bar 0.2897 (0.12%); L = 3,410 × 0.2897 = 987.8 mm, 992.7 mm after correcting half the tilt bound; bar 0.12% (14%), tracing 0.04% (2%), tilt 0.28% (84%); u 0.31% = 3.1 mm, U = 6.1 mm; Monte Carlo 992.7 ± 3.1 mm, 95% interval 987.2 to 998.2.
- With Example 4 (GSD 0.289 mm, blur 0.8 px, recomputed): a hairline measures 1.14 px = 0.33 mm; 0.3 mm measures FWHM 0.63 and count 0.59; 0.6 mm gives 0.76 and 0.72; 1.0 mm gives 1.03 ± 0.05 and 1.02 ± 0.14; 1.5, 2.0 and 3.0 mm follow the truth within 0.05 mm for FWHM. The 3 mm step of Example 5: baseline 0.30 m 2.99 ± 0.56 mm, 0.75 m 3.03 ± 0.22, 1.50 m 2.99 ± 0.11, 3.00 m 3.00 ± 0.06; per-point error at 1.5 m 0.82 mm.
- A hovering drone drifts slightly, so every image point includes camera motion; subtract the bank motion from the water motion (in the example 2.1 − (−0.3) = 2.4 px/frame). Speed = 1.8 × 0.025 × 25 = 1.125 m/s, which is the surface speed, not the cross-section mean.
- Results depend on how many frames were hidden; a strong answer logs every loss and recovery frame. Partly hidden frames score low and give shifted positions; using them to update the velocity makes the COAST prediction worse every frame, for example a velocity off by 1 px/frame over 20 hidden frames is 20 px off, so the search radius must be at least 20 px.
- In the example the 8-degree tilt is 84% of the variance. Tilt always shortens a length (at most 1/cos 8° − 1 = 0.98% = 9.7 mm, more than U), so correct by half the bound first and treat the remainder as a uniform distribution; folding it into the noise alone leaves the value systematically low.
- In the example lines narrower than 3 px read about twice too wide (0.3 mm gives 0.63); from 1.0 mm (3.5 px) up they approach the truth. The narrowest trustworthy width should be about 3 px, or 0.87 mm at a GSD of 0.289 mm; if the group's value differs, explain it with the blur and GSD of the camera used (the lesson camera must be within about 6.9 m for 1.0 mm to span 3 px).
- A common error, such as camera rotation wrong by 0.01 degrees, puts the absolute depth off by 4.4 mm, more than the step, but cancels in the difference, so the step is still 2.85 ± 0.12 mm. The per-point error δZ ≈ Z²σ√2/(fB) falls with the baseline (0.30 m gives 4.10 mm, 1.50 m 0.82 mm), so choose a baseline whose averaged error is at least twice smaller than the resolution needed.
Discussion questions
- If the irrigation office wants 0.3 mm crack widths, how should the team respond when the image limit is about 0.87 mm?
- How does surface speed differ from the mean cross-section speed, and what else is needed to estimate discharge?
- When should the tracker declare FAILED, and who should be told?
Adapting to student background
- Upper secondary (M.6)
- Have them compute GSD = hp/f, the root-sum-of-squares budget and δZ by hand before running the Monte Carlo check.
- Vocational certificate
- Give them the tripod set-up, placing the reference bar and the stepped plates, and measuring with a vernier or depth gauge to compare with the image; use a fill-in uncertainty budget.
- Diploma
- Extension: use a homography from four targets to remove the plate's tilt before measuring length, and compare the uncertainty budget before and after.
15Worksheet 15 An acceptance plan and test suite for the application
Lab · About 3 h of class time · CLO9
Objective: Write measurable acceptance criteria, compute the sample size, test the navigation or surveying part of the application and write the failure tests as code
Equipment
- The group's data and code from Worksheets 11 to 14
- A printed ArUco marker of known size (if the navigation application is chosen)
- Computer with Python, OpenCV and the module 15 example code
Safety
- If flying to record, fly within CAAT conditions in visual line of sight, keep people clear, check batteries and propellers before flight, and do not record faces unnecessarily
- Test marker landing in a simulator or on the ground first, never directly on a flying drone near people
Steps
- Choose one application and write its requirement and at least three measurable acceptance criteria with pass limits
- Compute the sample size as in Example 1 and prepare the test set to that size
- Navigation: photograph the marker at several heights, find the greatest detection height and choose the gain by simulation
- Surveying: estimate the uncertainty budget and write a guarded decision rule
- Intelligent system: choose an N-of-M rule from the costs of false alerts and misses and test it on video with real events
- Write at least five failure test cases as code and write a one-page acceptance report
Deliverables
- Acceptance plan and sample-size calculation
- Test results for the navigation, surveying or intelligent part
- A runnable failure test suite
- One-page acceptance report
Checklist
- At least three acceptance criteria are measurable, with pass limits and measurement methods
- The sample size is computed before testing and recall is reported with its 95% Wilson interval
- The test set is kept apart from the data used to tune thresholds
- At least five failure cases run and report pass or fail
- The acceptance report states how personal image data are protected (event clips only, blurring, retention period)
Instructor guide
Class timing
- Briefing; choose the application, write requirements and criteria30 min
- Sample size and test set preparation30 min
- Safety and testing the chosen application part60 min
- Write failure test cases as code30 min
- Write the one-page acceptance report25 min
- Presentation and hand-in checklist5 min
Expected results
- With Example 1 (recomputed): 37 of 40 found, recall 0.925, Wilson interval 0.801 to 0.974, lower bound below 0.90, fail; 9 false alarms in 12 panels, 0.75 per panel, 95% Poisson upper bound 1.31, at most 2, pass. Cracks to seed to show recall of at least 0.90: true recall 0.95 needs 127, 0.97 needs 69, 0.99 needs 35, and with no misses 29 in a row (0.90²⁹ = 0.047).
- Navigation (Example 2, f = 640 px, 0.60 m marker): sides 128, 64, 38, 26, 19, 13 px at 3, 6, 10, 15, 20, 30 m, found up to 15 m; range error 0.4, 9.4, 24.0, 65.8 cm, lateral 0.3 to 2.2 cm. Gain (Example 3): 0.2 and 0.5 no overshoot, 1.0 overshoots 3.5%, 1.5 oscillates 14.3%; total delay 0.48 s, start at no more than 0.62 per second. Surveying (Example 4): u 2.6 cm, U 5.3 cm, acceptance limit 6.047 m, 6.07 m means retest (P 12.8%). Intelligent system (Example 5): 1/1 331 per hour; 3/5 25, 100% caught, 0.20 s; 5/10 2, 98%; 8/15 0, 76% (all recomputed; marker size in pixels from f × 0.60/Z).
- At least five cases, such as the camera stopping, a dark frame, the marker lost for 0.5 s then back (must end in TRACK), lost for 3 s (must ABORT at cycle 31 = 3.1 s), seen every other cycle (must ABORT rather than switch forever), never seen (must stay in SEARCH), the tracker lost, and a slow link. Every case must state its expected outcome before running.
- 45/50 = 0.90 with a Wilson interval of 0.786 to 0.957 (recomputed); the lower bound is below 0.90, so it fails even though the measured value equals the criterion. The number to seed depends on the expected true recall (0.97 needs 69, no misses needs 29) and must be computed before testing, not taken as whatever is convenient.
- The angle depends on the marker centre, averaged over four corners, while the range depends on its size in the image; when the marker is only a few tens of pixels, one pixel changes the range a lot (at 15 m, range error 65.8 cm against lateral 2.2 cm), so take range from a rangefinder or barometer. The greatest height follows from f × 0.60/Z being at least the smallest detectable size, for example 20 px gives Z at most 640 × 0.60/20 = 19.2 m (in the example 26 px was found and 19 px was not).
- The acceptance limit is 6.10 − 0.053 = 6.047 m; 6.08 is above it, so the rule orders a retest. The probability that the true width exceeds 6.10 is 1 − Φ((6.10 − 6.08)/0.0265) = 1 − Φ(0.75) ≈ 22% (recomputed 22.4%), while the simple rule would accept it.
- N of M trades false alerts against delay and the chance of missing a briefly seen object. The 1-of-1 rule catches 100% but raises 331 false alerts an hour, so the operator stops trusting it. The choice must come from the group's costs of a false alert and a miss, tested on video with at least five real events.
- Every threshold change can be rechecked in seconds, showing at once which case breaks. A marker seen every other cycle never gets 3 consecutive sightings, so it cannot return to TRACK and must ABORT after more than 2.0 s in DEGRADED (cycle 31) instead of switching forever; if someone changes the return rule to 1 cycle, this test catches it.
Discussion questions
- Who decides in each application (inspecting engineer, autopilot, acceptance inspector, operator), and when should the system hand over to a person?
- Why does reducing the vision latency allow a higher gain and a faster landing?
- How must canal-side video showing people or number plates be handled under the Personal Data Protection Act before recording or export?
Adapting to student background
- Upper secondary (M.6)
- Have them compute the Wilson interval and the Poisson upper bound by hand and find the no-miss sample size from 0.90ⁿ ≤ 0.05 before using code.
- Vocational certificate
- Have them choose navigation or surveying, print the marker, measure heights with a tape or pole and photograph on the ground; give a test-case template where only inputs and expected outcomes are filled in.
- Diploma
- Extension: feed the group's measured latency into the simulator of Example 3 to choose the gain, then test landing in a simulator or on the ground first, never on a drone flying near people.
Scoring rubric
For worksheets and the mini-project. Each criterion scores level (1–4) ÷ 4 × weight.
| Criterion | Weight | Excellent (4) | Good (3) | Fair (2) | Needs work (1) |
|---|---|---|---|---|---|
| Data quality and preparation | 20% | Data scope, labelling policy, group-wise splits and datasheet complete and consistent, with no leakage | Nearly complete with minor gaps | Some parts missing, or random per-image splits | No scope or policy; clear leakage |
| Correctness of model development and calculations | 30% | Object size, tiles, features, box merging, tracking, segmentation and receptive field all correct, with reproducible code | Nearly all correct, method shown | Some errors or missing steps | Many errors or no method |
| Evaluation of the whole pipeline | 30% | Evaluates model and end output, splits subgroups, measures calibration and time on the real device, and draws operating conditions from the evidence | Nearly all levels evaluated; some subgroup or timing analysis missing | Only model metrics evaluated | No credible evaluation |
| Documentation, transparency and communication | 20% | Clear datasheet and model card, honest limitations, personal data protected, and a presentation users can act on | Complete but partly unclear | Some limitations or data protection missing | No documentation, or results overstated |
Assessment map: CLOs and how they are assessed Draft
The CLOs are a web-team draft; the course owner sets the final ones (curriculum book, part 4). This table is built from the worksheet and module-quiz data, so it follows any change to the CLOs.
| CLO | Worksheets | Module quizzes |
|---|---|---|
| CLO1 Explain and design an intelligent image-analysis pipeline from image-data preparation and image processing to feature extraction | W 1W 2 | M1M2 |
| CLO2 Develop image classification, object detection and tracking, image segmentation and anomaly detection with machine learning and deep-learning models | W 2W 3W 4 | M2M3M4M5 |
| CLO3 Evaluate automated image-analysis systems for accuracy, confidence calibration, processing time and fairness under real operating conditions | W 3W 5 | M3M5 |
| CLO4 Explain and choose supervised and unsupervised learning algorithms (classification, regression, clustering, dimensionality reduction) to match the data and the question | W 6W 7W 8W 9 | M6M7M8M9 |
| CLO5 Develop, split, tune and evaluate models on automation and UAS data without leakage, and report results with uncertainty | W 6W 7W 8W 10 | M6M7M8M10 |
| CLO6 Hand over and monitor models ethically: set cost-based thresholds, detect drift, explain models and protect personal data | W 10 | M10 |
| CLO7 Select and compare computer vision techniques (image and video processing, edge and feature detection, image matching, detection, classification, segmentation and tracking) to fit the problem, the data and the limits of an application | W 11W 12W 13 | M11M12M13 |
| CLO8 Develop drone image and video applications with OpenCV and Python for inspection, navigation, surveying and intelligent systems, including image-based measurement with its uncertainty | W 11W 12W 14 | M11M12M14M15 |
| CLO9 Evaluate an application against measurable acceptance criteria, improve its performance and design how it handles failures | W 13W 15 | M13M15 |