This is an old revision of the document!
Programming Assignment
Select one of the assignments below.
Assignments marked with
can be extended as a continution eg. as master thsis, or other projects.
Projects marked with
can be (with some additional work and depending on the results) published as scientific papers.
1. Comparing Human and AI Attention in Visual Anomaly Detection
Difficulty: Intermediate
Project type: Experimental study, computer vision, eye tracking
Technologies: Python, Tobii-PyTracker, PyTorch, Anomalib, PatchCore, OpenCV, NumPy, SciPy
Project description
The goal of this project is to prepare a pilot study comparing the visual attention of human operators with the anomaly regions identified by an artificial intelligence model.
The study will use the CoinDefect6K dataset, which contains images of coins acquired in an industrial visual-inspection setting. A selected visual anomaly-detection method, preferably PatchCore from the Anomalib library, should be used to generate pixel-level anomaly maps for selected images. The same images will then be presented to human participants using Tobii-PyTracker, and their eye-gaze data will be collected.
The project should investigate whether human participants and the anomaly-detection model focus on similar image regions when evaluating whether a coin contains a defect.
Main tasks
- Configure and run a selected visual anomaly-detection method on the CoinDefect6K dataset.
- PatchCore is recommended as the initial baseline, but another method available in Anomalib may be used if justified.
- Select approximately 20–30 representative images:
- normal images,
- images with clearly visible defects,
- images with small or ambiguous defects,
- examples representing different defect types.
- Generate and save normalized anomaly maps for the selected images.
- Prepare a basic visual-inspection experiment using Tobii-PyTracker.
- Present each image to participants and ask them to decide whether it contains a defect.
- Optionally ask participants to indicate the suspected defect location using the mouse.
- Record:
- gaze coordinates,
- gaze timestamps,
- inspection time,
- participant decision,
- decision confidence,
- manually indicated defect location, if collected.
- Conduct a pilot experiment with approximately 5–10 participants. Students familiar with visual inspection may be treated as novice operators.
- Remove invalid gaze samples and transform the gaze coordinates into the coordinate system of the displayed image.
- Generate individual and aggregated human-attention heatmaps.
- Normalize the human heatmaps and AI anomaly maps to the same resolution and numerical range.
- Compare the human and AI maps quantitatively.
Suggested comparison metrics
- Pearson correlation between the flattened heatmaps.
- Spearman rank correlation.
- Cosine similarity.
- Intersection over Union after thresholding the maps.
- Overlap between the top 10% and top 20% most salient pixels.
- Distance between the centers of mass of the heatmaps.
- Percentage of human gaze falling inside the highest-anomaly region.
- NSS or AUC-Judd, if human fixations are represented as discrete fixation locations.
Human–AI similarity should also be compared with human–human similarity. This will provide a reference for interpreting whether the observed human–AI agreement is high or low.
Research questions
- Do human participants and the anomaly-detection model focus on similar image regions?
- Is human–AI similarity higher for obvious defects than for small or ambiguous defects?
- Does human–AI similarity depend on defect type?
- Is stronger human–AI agreement associated with correct human decisions?
- Are there images for which the human and the model reach the same decision while focusing on different regions?
- Are there images for which the model detects a defect before participants inspect its location?
Expected deliverables
- A reproducible Tobii-PyTracker experiment.
- A script or notebook generating AI anomaly maps.
- A script generating individual and aggregated gaze heatmaps.
- A dataset containing anonymized gaze measurements and participant responses.
- A quantitative comparison of human and AI attention.
- Example visualizations presenting:
- strong human–AI agreement,
- weak human–AI agreement,
- regions inspected mainly by humans,
- regions highlighted mainly by the AI model.
- A short technical report describing the experiment, results, limitations, and recommendations for a larger study.
Important considerations
- The displayed image must not be resized differently for AI-map generation and gaze analysis.
- Screen coordinates must be transformed carefully into image coordinates.
- The order of images should be randomized.
- A short calibration and familiarization stage should be included.
- Human participants should not be shown the AI anomaly maps before making their decisions.
- As gaze and participant decisions are collected, the study must follow the applicable institutional requirements for research involving human participants.
2. Comparing Human and AI Attention in Image Classification
Difficulty: Advanced
Project type: Human-centered AI, image classification, explainable AI, eye tracking
Technologies: Python, Tobii-PyTracker, PyTorch, TorchVision, Captum, ResNet-50, Grad-CAM
Project description
The goal of this project is to compare human visual attention with image regions used by a pretrained image classifier. Unlike the anomaly-detection project, the model must assign an image to one of several semantic classes rather than identify a local defect.
The recommended setup is a pretrained ResNet-50 classifier with ImageNet-1K weights available through TorchVision. The model is already trained and can be used without additional model training. The project should therefore focus on designing and conducting the human study rather than developing a new classifier.
A carefully selected subset of approximately 30–50 images should be used. The subset should contain both correctly and incorrectly classified examples, images with one dominant object, images with multiple objects, and visually ambiguous examples.
Main tasks
- Load a pretrained ResNet-50 model using TorchVision.
- Use the default ResNet50_Weights.IMAGENET1K_V2 weights and the preprocessing transformations associated with these weights.
- Select images representing approximately 8–12 understandable ImageNet classes.
- Avoid obscure ImageNet labels that human participants are unlikely to understand.
- Obtain the model’s:
- top-1 prediction,
- top-5 predictions,
- class probabilities.
- Generate class-specific model-attention maps using Grad-CAM.
- Optionally compare Grad-CAM with one additional attribution method, such as Integrated Gradients or Occlusion.
- Implement an eye-tracking experiment using Tobii-PyTracker.
- Ask participants to classify each image or select a class from a restricted list.
- Record:
- gaze data,
- participant classification,
- response time,
- confidence,
- whether the participant changed their initial decision.
- Generate human-attention heatmaps.
- Compare human gaze with the attribution map generated for:
- the model’s predicted class,
- the correct class, when different,
- the class selected by the participant.
- Analyze correctly and incorrectly classified images separately.
Suggested study conditions
A within-subject experiment may include two conditions:
- Unaided condition: the participant sees only the image.
- AI-assisted condition: the participant sees the image, the model prediction, and optionally the model-attention map.
If both conditions are used, the order should be counterbalanced and the same image should not be shown twice to the same participant unless an appropriate washout or image-pair design is used.
Research questions
- Do humans and the classifier rely on similar image regions?
- Is human–AI attention similarity higher when both produce the correct classification?
- What happens when humans and the classifier predict different classes?
- Does the model focus on the foreground object, its context, or irrelevant background elements?
- Does displaying a model-attention map influence subsequent human visual attention?
- Can an attribution map help participants recognize an incorrect model prediction?
- Are highly confident model predictions associated with stronger human–AI attention alignment?
Suggested analysis
- Compare human and model heatmaps using correlation, cosine similarity, top-k overlap, and center-of-mass distance.
- Compare human gaze with object bounding boxes or segmentation masks, if available.
- Compare attention similarity across:
- model-correct and model-incorrect images,
- human-correct and human-incorrect responses,
- agreement and disagreement cases,
- simple and cluttered images,
- high- and low-confidence model predictions.
- Use mixed-effects models or repeated-measures tests if a sufficient number of participants is collected.
Expected deliverables
- A reproducible Tobii-PyTracker classification study.
- A prepared image subset with class labels and model predictions.
- Grad-CAM or equivalent model-attribution maps.
- Individual and aggregated human-attention maps.
- A quantitative human–AI attention comparison.
- An analysis of agreement and disagreement cases.
- A technical report documenting the experimental procedure and results.
Important considerations
- Grad-CAM is a post-hoc approximation and should not be described as a direct measurement of where the model “looked.”
- The attribution must be generated for a clearly specified class.
- The displayed image should correspond exactly to the image crop received by the classifier.
- ImageNet labels may be overly specific. A mapping to a smaller set of human-readable categories may be required.
- The selected stimuli should be tested before the final study to ensure that the required classes are understandable to participants.
3. Ablation Study of Counterfactuals by Design
Difficulty: Advanced
Project type: Time-series counterfactual explanations, experimental evaluation
Technologies: Python, PyTorch or TensorFlow depending on the implementation, NumPy, Pandas, SciPy
Project description
The goal of this project is to investigate the role of individual components of the objective function used in Counterfactuals by Design.
The student should first reproduce the original version of the method described in the paper “Counterfactuals by Design: Residual Decomposition and Back-to-Normality Editing for Time Series.” The first version of the paper and the available materials can be found at:
https://zenodo.org/records/22794856
The implementation of the second version of the method will be provided on request.
The main research task is to conduct controlled ablation experiments in which selected components of the objective function are removed or assigned different weights. The objective is to determine how each component affects validity, proximity, sparsity, plausibility, signal reconstruction, and the interpretability of generated counterfactuals.
Main tasks
- Run the available implementation of the first Counterfactuals by Design method.
- Reproduce at least one experiment reported in the original work.
- Run the second version of the implementation provided by the supervisor.
- Identify all independently weighted components of the training and counterfactual-generation objectives.
- Refactor the implementation so that every loss component can be:
- enabled or disabled,
- assigned a configurable weight,
- logged separately during training.
- Prepare a full-model baseline using the original loss configuration.
- Conduct one-component-at-a-time ablations.
- Investigate selected combinations of removed components when scientifically justified.
- Repeat experiments using multiple random seeds.
- Preserve the same data splits, classifier, factual examples, target classes, and evaluation procedure for all configurations.
Minimum ablation design
The exact names of the losses should follow the supplied implementation. The experiment should include:
- the complete objective function,
- removal of each reconstruction-related component,
- removal of each classification or validity component,
- removal of each decomposition or separation component,
- removal of regularization terms,
- removal of constraints controlling the counterfactual residual,
- removal of terms responsible for preserving the normal or morphology component,
- selected weight sweeps for the most influential components.
For each loss component, test at least:
- original weight,
- weight equal to zero,
- reduced weight, for example 0.1 × the original value,
- increased weight, for example 10 × the original value.
A complete Cartesian product is not required. Begin with one-factor-at-a-time ablations and select only the most informative interactions for additional experiments.
Evaluation criteria
- Counterfactual validity.
- Target-class probability.
- Proximity to the factual signal.
- Sparsity of the modification.
- Counterfactual generation success rate.
- Reconstruction error.
- Classification performance of the original and modified signal.
- Plausibility of the generated signal.
- Magnitude and localization of the modified residual.
- Preservation of non-target signal characteristics.
- Diversity, if multiple counterfactuals are generated.
- Stability across random seeds.
- Execution time.
The analysis should also include visual examples. For each important configuration, present the factual signal, reconstructed normal component, residual component, modified residual, and final counterfactual.
Research questions
- Which objective components are necessary for producing valid counterfactuals?
- Which components preserve the quality of signal reconstruction?
- Which components prevent unrealistic or adversarial perturbations?
- Which components are responsible for concentrating modifications in interpretable signal regions?
- Are any loss components redundant?
- Are there conflicts between validity, proximity, and plausibility?
- Does the importance of a component differ between the first and second versions of the method?
Expected deliverables
- A working reproduction of the available Counterfactuals by Design implementation.
- A configuration-based implementation of the ablation experiments.
- Experiment scripts supporting multiple random seeds.
- A CSV file containing one record per experiment.
- Plots showing metric changes after removing each component.
- Representative counterfactual visualizations.
- A ranked summary of the practical importance of the loss components.
- A report discussing which components are essential, beneficial, redundant, or potentially harmful.
Important considerations
- An ablation must change only the examined component.
- Hyperparameters unrelated to the ablated component must remain fixed.
- Failure to generate a counterfactual is a valid result and must be recorded.
- The analysis should not rely only on validity because removing constraints may improve validity while producing unrealistic counterfactuals.
- Conclusions should be based on repeated experiments rather than individual examples.
4. Robustness of DANCE to Errors in the Feature-Relationship Graph
Difficulty: Advanced
Project type: Counterfactual explanations, robustness testing, structured perturbation experiments
Technologies: Python, ACFX, DANCE, NumPy, Pandas, DirectLiNGAM or NOTEARS, scikit-learn, SciPy
Project description
DANCE uses a feature-relationship graph to guide counterfactual generation. In practice, the supplied or learned graph may contain errors. Some relationships may be missing, spurious relationships may be present, and estimated edge weights may be inaccurate.
The goal of this project is to evaluate how robust DANCE is to controlled corruption of the feature-relationship graph. The experiments should use the ACFX implementation of DANCE and several tabular classification datasets containing continuous and categorical attributes.
The study should evaluate whether graph errors gradually reduce counterfactual quality or whether specific types of corruption cause abrupt failures.
Main tasks
- Configure and run DANCE using ACFX.
- Select approximately 5–10 tabular classification datasets.
- Use datasets with different:
- numbers of features,
- sample sizes,
- class balances,
- graph densities,
- proportions of categorical attributes.
- Train or load one classifier per dataset.
- Learn or define a baseline feature-relationship graph.
- Generate counterfactuals using the unmodified graph.
- Implement controlled graph-corruption operators.
- Run DANCE with the corrupted graphs.
- Evaluate counterfactual quality using the same factual samples, target classes, model, and random seeds.
- Repeat each stochastic condition using at least 5 random graph-corruption seeds.
- Save the corrupted adjacency matrices and experimental metadata so that every result can be reproduced.
Required graph-corruption operators
Edge removal
Randomly remove a selected percentage of existing edges.
Suggested levels:
- 0%,
- 5%,
- 10%,
- 20%,
- 40%,
- 60%.
Include an additional targeted variant in which the strongest edges are removed first.
Edge addition
Add nonexistent edges while preventing self-loops.
Suggested levels should be defined relative to the original number of edges:
- 5%,
- 10%,
- 20%,
- 40%,
- 60%.
Test at least two variants:
- random edge addition,
- addition of edges conflicting with the original causal or topological order.
Edge-weight noise
For every nonzero edge weight, apply additive noise:
w_corrupted = w + epsilon
where:
epsilon ~ Normal(0, sigma × s_w)
and s_w is a scale derived from the nonzero weights in the original graph.
Suggested noise levels:
- sigma = 0.05,
- sigma = 0.10,
- sigma = 0.25,
- sigma = 0.50,
- sigma = 1.00.
Edge-sign reversal
Reverse the sign of a selected proportion of edge weights:
- 5%,
- 10%,
- 20%,
- 40%.
Combined corruption
Apply edge removal, addition, and weight noise simultaneously. The combined condition should represent a realistic estimated graph containing several types of error.
Required experiment controls
- The classifier must remain fixed across graph-corruption conditions.
- The factual instances and desired classes must remain fixed.
- The same feature bounds and categorical-feature definitions must be used.
- Graph perturbations must not modify the dataset itself.
- Results must include both successful and unsuccessful generation attempts.
- If DANCE requires an acyclic graph, the implementation must either preserve acyclicity or explicitly report when corruption violates this requirement.
- Random corruption must be reproducible from a stored random seed.
Required metrics
The project should implement and report at least:
- number of generated counterfactuals,
- number of valid counterfactuals,
- fidelity or validity rate,
- mean target-class probability,
- classification loss,
- proximity loss,
- sparsity loss,
- causality or graph-consistency loss,
- diversity,
- Local Outlier Factor score,
- counterfactual generation time,
- generation failure rate.
The accompanying reference notebook already uses classification loss, range-normalized proximity, sparsity, graph-based causal penalty, determinant-based diversity, and novelty-mode Local Outlier Factor. The implementation should preserve these definitions unless a change is clearly documented.
Required Python module
Prepare a standalone Python file named:
counterfactual_metrics.py
The file should provide reusable implementations of at least:
compute_yloss(…)compute_proximity_loss(…)compute_sparsity_loss(…)compute_causal_penalty(…)compute_diversity(…)fit_lof(…)evaluate_counterfactuals(…)
The implementations should be based on the provided reference notebook but must not depend on notebook-global variables.
The main evaluation function should return a dictionary containing fields compatible with the following structure:
no_cfsno_valid_cfsfidelityprobabilitylossproximity_losssparsity_losscausality_lossdiversitylof_factorexecution_timestatuserror
The module must:
- support binary and multiclass classifiers,
- correctly identify the target-class probability column from
model.classes_, - support continuous and categorical attributes,
- handle an empty counterfactual set without crashing,
- return
NaNfor metrics that cannot be computed, - validate array dimensions,
- avoid computing means over empty arrays,
- include docstrings and type hints,
- include a small collection of unit tests.
Metrics output example
An evaluation record should follow the logic below:
no_valid_cfsis the number of counterfactuals predicted as the desired class.fidelityis the proportion of generated counterfactuals classified as the desired class.probabilityis the mean probability assigned to the desired class.lossmeasures the margin between the strongest alternative class and the desired class.proximity_lossis the normalized distance from the factual instance.sparsity_lossis the proportion of modified features.causality_lossmeasures inconsistency with the supplied feature-relationship graph.diversitymeasures differences among counterfactuals generated for the same factual instance.lof_factormeasures how typical the counterfactuals are relative to the training data.
Research questions
- How quickly does counterfactual quality deteriorate as graph corruption increases?
- Is DANCE more sensitive to missing edges, additional edges, incorrect signs, or inaccurate weights?
- Does graph corruption affect validity and plausibility differently?
- Are dense graphs more vulnerable to corruption than sparse graphs?
- Are some datasets more sensitive because their predictions depend on a small number of relationships?
- Does DANCE remain competitive when the graph is only approximately correct?
- Can graph uncertainty be estimated from the variability of generated counterfactuals?
Suggested analysis
For each metric, report:
- absolute metric value,
- difference relative to the clean-graph baseline,
- relative percentage degradation,
- mean and standard deviation across graph-corruption seeds.
Use degradation curves in which the x-axis represents corruption intensity and the y-axis represents counterfactual quality. Consider reporting the area under the degradation curve as a single robustness summary.
Expected deliverables
- A reusable graph-corruption module.
- A standalone
counterfactual_metrics.pyfile. - Unit tests for the metric implementations.
- A reproducible DANCE experiment pipeline.
- Clean and corrupted graph files.
- A CSV file containing per-sample and aggregated results.
- Robustness curves for every corruption operator.
- A comparison of dataset-level sensitivity.
- A report identifying the graph errors that are most harmful to DANCE.
5. Comparison of Counterfactual Generators for ECG Classification
Difficulty: Advanced
Project type: Time-series explainability, ECG classification, counterfactual explanations
Technologies: Python, PyTorch or TensorFlow, PTB-XL, NumPy, SciPy, wfdb
Project description
The goal of this project is to compare at least three counterfactual-generation methods for ECG classification.
A common ECG classifier and the same factual test signals must be used for all methods. The evaluation should determine whether the generated signals are valid counterfactuals, whether they remain close to the original ECG, and whether their modifications are plausible and interpretable rather than merely adversarial.
The recommended dataset is PTB-XL. The initial comparison may focus on a binary task, such as normal versus abnormal ECG, or on selected diagnostic superclasses. The exact classification task should be fixed before the counterfactual methods are compared.
Required types of counterfactual generator
The comparison should contain at least three substantially different approaches:
- Direct optimization method: optimize the ECG samples or a constrained perturbation to change the classifier decision.
- Generative or latent-space method: search for a counterfactual in the latent space of an autoencoder, variational autoencoder, or another generative model.
- Structure-aware method: use Counterfactuals by Design, a residual-editing method, or another approach explicitly designed to preserve signal structure.
An optional fourth baseline may use a nearest unlike neighbor from the test or reference set.
Existing ECG-oriented counterfactual code, such as VCCE, may be investigated, but all selected methods must ultimately be evaluated using a consistent classifier, task, and metric implementation.
Main tasks
- Prepare a consistent PTB-XL preprocessing pipeline.
- Use the recommended patient-level or predefined PTB-XL split to prevent patient leakage.
- Train or reuse one ECG classifier.
- Select factual examples that the classifier initially predicts correctly.
- Define the desired counterfactual class.
- Implement or adapt at least three counterfactual generators.
- Generate one or more counterfactuals for every factual example.
- Record failed generation attempts.
- Evaluate all methods using the same metrics and constraints.
- Compare both quantitative results and representative ECG visualizations.
- Investigate whether the modifications correspond to clear signal changes or small adversarial perturbations.
Minimum evaluation metrics
- Counterfactual validity.
- Desired-class probability.
- Counterfactual generation success rate.
- L1 and L2 proximity.
- Maximum pointwise perturbation.
- Sparsity in the time domain.
- Number and duration of modified temporal segments.
- Dynamic Time Warping distance.
- Correlation between factual and counterfactual signals.
- Change in signal energy.
- Frequency-domain distance or power spectral density difference.
- Total variation of the perturbation.
- Counterfactual diversity.
- Stability across random seeds.
- Generation time.
If feasible, include general signal-quality indicators or an anomaly detector trained on real ECG signals. Domain-specific physiological constraints may be used as an additional analysis, but the main comparison should not depend solely on manually encoded ECG knowledge.
Recommended experimental levels
Level 1: Binary classification
Begin with a normal-versus-abnormal task. This simplifies target-class definition and facilitates visual comparison of counterfactuals.
Level 2: Diagnostic superclass classification
If the binary experiment is successful, extend the evaluation to selected PTB-XL diagnostic superclasses, for example:
- NORM,
- MI,
- STTC,
- CD,
- HYP.
Level 3: Cross-model validation
Evaluate generated counterfactuals using an independently trained classifier. This helps detect counterfactuals that exploit only the original classifier’s decision boundary.
Research questions
- Which method produces the highest percentage of valid ECG counterfactuals?
- Which method produces the smallest changes?
- Are the smallest changes also the most plausible?
- Do direct optimization methods produce adversarial-looking perturbations?
- Do latent-space methods preserve overall morphology better?
- Does residual-based generation produce clearer transitions toward a normal or target-class signal?
- Do counterfactuals remain valid for an independently trained classifier?
- Which methods produce localized and interpretable modifications?
- How stable are the generated counterfactuals across repeated runs?
Required visual analysis
For representative examples, display:
- the factual ECG,
- the generated counterfactual,
- the pointwise difference,
- the absolute perturbation,
- the classifier probability before and after generation,
- the modified temporal regions,
- multiple leads when a 12-lead classifier is used.
The report should include examples of:
- a successful and plausible counterfactual,
- a valid but potentially adversarial counterfactual,
- a counterfactual with excessive modification,
- a generation failure,
- disagreement between the original and independent classifier.
Expected deliverables
- A common ECG preprocessing and classification pipeline.
- Implementations or adapters for at least three counterfactual generators.
- A shared counterfactual-evaluation module.
- A CSV file containing per-sample results.
- Aggregate comparison tables and Pareto plots.
- Representative ECG visualizations.
- An analysis of validity under an independent classifier.
- A report discussing the advantages, limitations, and failure modes of each method.
Important considerations
- Dataset splits must be defined at the patient level.
- All methods must receive the same input signals and target classes.
- Signal normalization must be inverted before interpreting counterfactual changes.
- Validity for the original classifier is not sufficient evidence of a meaningful counterfactual.
- Very small modifications may indicate adversarial behavior rather than meaningful diagnostic change.
- Counterfactual quality should be considered as a trade-off among validity, proximity, plausibility, interpretability, and robustness.
- The project is methodological and should not make clinical claims.
General Requirements for All Projects
- The implementation must be reproducible from a clean environment.
- Dependency versions and random seeds must be recorded.
- Large intermediate objects should be cached when appropriate.
- Failed experiments must be reported rather than silently removed.
- Evaluation results should be saved incrementally to avoid losing long-running experiments.
- Every experiment should produce machine-readable results, preferably CSV or Parquet.
- Source code should contain documentation and clear execution instructions.
- The final report should distinguish observations supported by experiments from hypotheses requiring further validation.