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.
Select project: Put your names next to the project
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.
- Ask participants to indicate the suspected defect location using verbal description (voice is recorded with tobii-pytracker and later is transcibed into description).
- Record:
- gaze coordinates,
- gaze timestamps,
- inspection time,
- participant decision,
- voice
- Conduct a pilot experiment.
- 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.
2. Comparing Human and AI Attention in Image Classification
Difficulty: Intermediate
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 (or SHAP - select appropriate).
- 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,
- participant voice
- 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.
3. Ablation Study of Counterfactuals by Design
Difficulty: Intermediate
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 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 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 term from cost fuciton
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.
4. Robustness of DANCE to Errors in the Feature-Relationship Graph
Difficulty: Intermediate
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, such a graph may be incomplete or inaccurate. Some actual relationships may be missing, spurious relationships may be present, and estimated edge weights may differ from the true dependencies between features.
The goal of this project is to evaluate the robustness of DANCE to controlled errors in the feature-relationship graph. The experiments should use the ACFX implementation of DANCE and several tabular classification datasets containing continuous, categorical, or mixed attributes.
A complete reference Google Colab notebook will be provided. It demonstrates how to:
- install and configure ACFX,
- prepare a tabular classification dataset,
- train a classifier,
- learn a feature-relationship graph using DirectLiNGAM,
- generate counterfactuals with DANCE,
- calculate the required counterfactual-quality metrics,
- handle unsuccessful generation attempts,
- save the evaluation results.
The reference notebook also contains the implementation of the evaluation metrics. Students should reuse and, when necessary, extend this implementation rather than reimplementing the complete evaluation framework from scratch.
The main contribution of the project should be the systematic corruption of feature-relationship graphs and the experimental analysis of how different graph errors affect the quality of counterfactual explanations.
The study should determine whether counterfactual quality decreases gradually as the graph becomes less accurate, or whether specific types and levels of graph corruption cause abrupt failures.
Starting materials
The following materials will be provided:
- a Google Colab notebook demonstrating a complete ACFX workflow,
- an example tabular classification dataset,
- code for training a basic classifier,
- code for learning a graph with DirectLiNGAM,
- code for generating counterfactuals using DANCE,
- implementations of the required evaluation metrics,
- an example showing how to store the results in a structured record.
The student is expected to understand, adapt, and extend the provided code. The project is not limited to rerunning the reference notebook.
Main tasks
- Run and understand the provided ACFX reference notebook.
- Verify that the reference experiment can be reproduced.
- Refactor the notebook where necessary to support repeated experiments.
- Select approximately 5–10 tabular classification datasets.
- Include datasets with different:
- numbers of features,
- sample sizes,
- class balances,
- graph densities,
- proportions of categorical attributes.
- Train or load one classifier for each dataset.
- Learn or define a baseline feature-relationship graph for each dataset.
- Generate counterfactuals using the original, unmodified graph.
- Implement reusable graph-corruption operators.
- Generate multiple corrupted versions of each baseline graph.
- Run DANCE using the original and corrupted graphs.
- Evaluate counterfactual quality using the metrics provided in the reference notebook.
- Ensure that the same classifier, factual instances, desired classes, and experimental settings are used when comparing graph conditions.
- Repeat every stochastic graph-corruption condition using at least 5 random seeds.
- Save all corrupted adjacency matrices, random seeds, configuration parameters, and result records.
- Analyze which graph errors are most harmful to DANCE.
Dataset selection
The selected datasets should provide a diverse evaluation environment. The collection should preferably contain:
- binary and multiclass classification problems,
- datasets with continuous attributes,
- datasets with categorical attributes,
- datasets with mixed attribute types,
- low-dimensional and higher-dimensional datasets,
- datasets with balanced and imbalanced classes.
Datasets may be obtained from sources such as:
- OpenML,
- the UCI Machine Learning Repository,
- scikit-learn,
- established counterfactual-explanation benchmarks.
The student should document:
- the dataset source,
- the prediction task,
- the number of instances,
- the number and types of features,
- the class distribution,
- preprocessing operations,
- train-test splitting,
- feature scaling,
- the method used to obtain the baseline graph.
The exact selection of datasets should be agreed upon with the supervisor before running the full experiment.
Baseline experiment
For each dataset, the student should first establish a clean-graph baseline.
The baseline should include:
- a fixed train-test split,
- a trained classifier,
- an unmodified feature-relationship graph,
- a fixed collection of factual instances,
- a defined desired class for every factual instance,
- counterfactuals generated with DANCE,
- all required evaluation metrics,
- counterfactual-generation time,
- successful and unsuccessful generation attempts.
The clean-graph baseline must be completed before introducing graph corruption.
Whenever possible, factual instances should initially be classified correctly by the classifier. The same factual instances must subsequently be used in every graph-corruption condition.
Required graph-corruption operators
The graph representation and orientation must remain consistent with the convention used by ACFX and the graph-learning method. For example, when using a DirectLiNGAM adjacency matrix, the student must verify which matrix dimension represents a parent and which represents a child before modifying the graph.
Edge removal
Randomly remove a selected proportion of existing edges.
Suggested corruption levels:
- 0%,
- 5%,
- 10%,
- 20%,
- 40%,
- 60%.
In addition to random removal, implement at least one targeted variant:
- remove the strongest edges first, or
- remove edges associated with the most influential features.
The number of removed edges and their original weights must be recorded.
Edge addition
Add edges that do not exist in the baseline graph. Self-loops must not be introduced.
Suggested corruption levels, defined relative to the original number of edges:
- 5%,
- 10%,
- 20%,
- 40%,
- 60%.
Implement at least two variants:
- random edge addition,
- addition of edges conflicting with the original causal or topological order.
The weight of a newly added edge should be sampled using a documented strategy. For example, its absolute value may be sampled from the distribution of nonzero weights in the original graph.
Edge-weight noise
Add noise to every nonzero edge weight:
w_corrupted = w + epsilon
where:
epsilon ~ Normal(0, sigma × s_w)
and s_w is a scale determined from the nonzero weights in the baseline graph.
Suggested noise levels:
sigma = 0.05,sigma = 0.10,sigma = 0.25,sigma = 0.50,sigma = 1.00.
The definition of s_w must be documented. It may, for example, be the standard deviation or mean absolute value of the nonzero graph weights.
The student should also report how often the added noise changes the sign of an edge.
Edge-sign reversal
Reverse the sign of a selected proportion of existing nonzero edges.
Suggested corruption levels:
- 5%,
- 10%,
- 20%,
- 40%.
Random and targeted sign reversal may be compared. A targeted strategy could reverse the signs of the strongest edges first.
Combined corruption
Apply several corruption types simultaneously, for example:
- edge removal,
- edge addition,
- edge-weight noise.
The combined condition should represent a realistic estimated graph containing several types of error.
At least three combined corruption levels should be prepared:
- low corruption,
- medium corruption,
- high corruption.
The exact parameters of these levels must be documented and applied consistently across repeated runs.
Graph validity and acyclicity
Some corruption operators may introduce cycles or invalidate the original feature ordering.
The implementation must explicitly check:
- whether the corrupted graph contains self-loops,
- whether the graph remains acyclic,
- whether the original topological order is still valid,
- whether all matrix dimensions remain consistent,
- whether the corrupted graph contains non-finite weights.
If DANCE requires a directed acyclic graph, the student should select and document one of the following strategies:
- reject graph modifications that introduce cycles,
- remove an edge responsible for each introduced cycle,
- restrict edge addition to edges consistent with a topological order,
- run a separate experiment comparing acyclic and cycle-producing corruption.
The chosen strategy must remain consistent within a given experiment.
Required experiment controls
- The classifier must remain fixed across graph-corruption conditions.
- The train-test split must remain fixed.
- The factual instances must remain fixed.
- The desired class for each factual instance must remain fixed.
- The same feature bounds must be used.
- The same categorical-feature definitions must be used.
- The same counterfactual-generation hyperparameters must be used.
- Graph perturbations must not modify the dataset or classifier.
- Results must include both successful and unsuccessful generation attempts.
- Random corruption must be reproducible using stored random seeds.
- The clean graph must be included as the 0% corruption condition.
- The same evaluation implementation must be used for all methods and conditions.
If a graph corruption makes DANCE unable to generate a counterfactual, this must be recorded as an experimental result rather than removed from the analysis.
Required metrics
The reference notebook contains implementations of the required metrics and demonstrates how to calculate them for counterfactuals generated by ACFX: Notebook
The project should report at least:
- number of generated counterfactuals,
- number of valid counterfactuals,
- fidelity or validity rate,
- mean desired-class probability,
- classification loss,
- proximity loss,
- sparsity loss,
- graph-consistency or causality loss,
- diversity,
- Local Outlier Factor score,
- counterfactual-generation time,
- generation failure rate.
The provided implementation includes:
- classification loss based on the margin between the strongest alternative class and the desired class,
- range-normalized proximity for continuous attributes,
- change-based proximity for categorical attributes,
- sparsity measured as the proportion of modified features,
- graph-consistency penalty based on the supplied weighted relationship graph,
- determinant-based diversity,
- novelty-mode Local Outlier Factor.
Students should preserve the provided metric definitions to ensure that results are comparable across datasets and graph-corruption conditions.
A metric may be modified or extended only when:
- the change is clearly justified,
- the new definition is documented,
- the original metric is also retained for comparison.
Use of the provided metrics module
The reference notebook creates and imports a reusable module named:
counterfactual_metrics.py
The module provides the following functions:
compute_yloss(…)compute_proximity_loss(…)compute_sparsity_loss(…)compute_causal_penalty(…)compute_diversity(…)fit_lof(…)evaluate_counterfactuals(…)
Students are not required to reimplement these functions from scratch.
However, they should:
- understand the meaning of every reported metric,
- verify that the input arrays have the expected shapes,
- correctly define continuous and categorical attributes,
- ensure that the desired-class probability column is selected correctly,
- preserve handling of empty counterfactual sets,
- preserve reporting of unsuccessful generation attempts,
- add tests if the module is extended,
- document every modification to the provided implementation.
The main evaluation function returns a dictionary containing:
no_cfsno_valid_cfsfidelityprobabilitylossproximity_losssparsity_losscausality_lossdiversitylof_factorexecution_timestatuserror
This dictionary should be extended with experimental metadata, including:
- dataset name,
- factual-instance identifier,
- original class,
- desired class,
- corruption operator,
- corruption intensity,
- graph-corruption seed,
- counterfactual-generation seed,
- number of original graph edges,
- number of corrupted graph edges,
- graph density,
- acyclicity status,
- counterfactual-generation hyperparameters.
Interpretation of the metrics
no_cfsis the number of generated counterfactuals.no_valid_cfsis the number of counterfactuals classified 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_lossmeasures the normalized distance between the factual instance and its counterfactuals.sparsity_lossis the proportion of features modified in the counterfactual.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.execution_timerecords the time required to generate the counterfactuals.statusindicates whether evaluation was successful, no counterfactual was produced, or an error occurred.errorcontains information about a generation or evaluation failure.
The term causality_loss should be interpreted carefully. If the graph was learned from observational data, the metric measures consistency with the supplied graph. It does not by itself prove that a counterfactual is causally valid.
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, proximity, sparsity, and plausibility differently?
- Are strong graph relationships more important than weak relationships?
- Are dense graphs more vulnerable to corruption than sparse graphs?
- Does sensitivity depend on the number of features?
- Does sensitivity differ between continuous and categorical attributes?
- Are some datasets more sensitive because their predictions depend on a small number of relationships?
- Does DANCE remain useful when the feature-relationship graph is only approximately correct?
- Which corruption operators cause counterfactual-generation failures?
- Can graph uncertainty be estimated from the variability of generated counterfactuals?
- Can counterfactual variability indicate that a graph should not be trusted?
Suggested experimental procedure
For each dataset:
- Prepare a fixed train-test split.
- Train the classifier.
- Learn or define the baseline graph.
- Select a fixed collection of factual instances.
- Generate counterfactuals using the baseline graph.
- Calculate and store the baseline metrics.
- Generate corrupted graphs using each required corruption operator.
- Run DANCE using every corrupted graph.
- Repeat stochastic corruption using at least 5 random seeds.
- Calculate all metrics using the provided metrics module.
- Store successful and unsuccessful runs.
- Aggregate results by dataset, corruption operator, and corruption intensity.
- Compare all conditions with the clean-graph baseline.
As a practical minimum, the student should evaluate approximately 50 factual instances per dataset. If runtime permits, 100 or more instances per dataset are recommended.
Suggested analysis
For each metric, report:
- the absolute metric value,
- the difference relative to the clean-graph baseline,
- the relative percentage degradation,
- the mean across graph-corruption seeds,
- the standard deviation across graph-corruption seeds,
- confidence intervals where appropriate,
- the number and rate of unsuccessful runs.
Use degradation curves in which:
- the x-axis represents graph-corruption intensity,
- the y-axis represents counterfactual quality,
- separate lines represent corruption operators,
- uncertainty bands represent variability across seeds or factual instances.
Consider reporting the area under the degradation curve as a summary of robustness. Because metrics have different directions, the interpretation should be standardized:
- higher fidelity and target-class probability are better,
- lower classification, proximity, sparsity, and graph-consistency losses are generally better,
- higher LOF scores indicate more typical samples when using
score_samples, - diversity should be interpreted jointly with validity and plausibility.
The analysis should distinguish between:
- gradual quality degradation,
- sudden failure thresholds,
- dataset-specific sensitivity,
- corruption-specific sensitivity,
- variability caused by stochastic counterfactual generation,
- variability caused by graph corruption.
Recommended result visualizations
- Metric degradation curves.
- Counterfactual-generation failure-rate curves.
- Heatmaps comparing datasets and corruption operators.
- Box plots showing variability across corruption seeds.
- Graph visualizations before and after corruption.
- Scatter plots comparing graph distance with counterfactual-quality degradation.
- Pareto plots comparing validity, proximity, sparsity, and graph consistency.
- Representative factual-counterfactual pairs for low, medium, and high graph corruption.
Expected deliverables
- An extended version of the provided Google Colab notebook.
- A reusable graph-corruption module.
- Implementations of all required graph-corruption operators.
- Tests for graph-corruption functions.
- Any documented extensions to
counterfactual_metrics.py. - A reproducible DANCE experiment pipeline.
- Configuration files or dictionaries defining all experiments.
- Original and corrupted adjacency matrices.
- Stored random seeds and graph-corruption metadata.
- A CSV or Parquet file containing per-instance results.
- A CSV or Parquet file containing aggregated results.
- Robustness curves for every graph-corruption operator.
- A comparison of dataset-level sensitivity.
- Representative visualizations of clean and corrupted graphs.
- A report identifying which graph errors are most harmful to DANCE.
- Instructions for reproducing the experiments in Google Colab or a local Python environment.
Minimum completion criteria
To complete the project successfully, the student must:
- reproduce the provided baseline notebook,
- evaluate at least 5 datasets,
- implement edge removal, edge addition, edge-weight noise, and edge-sign reversal,
- include at least one combined corruption condition,
- use at least 5 graph-corruption seeds per stochastic condition,
- include a clean-graph baseline,
- evaluate the same factual instances across graph conditions,
- report all required metrics,
- record unsuccessful generation attempts,
- provide reproducible result files,
- analyze the relationship between corruption intensity and counterfactual quality.
Optional extensions
- Compare DirectLiNGAM and NOTEARS graphs.
- Compare learned graphs with expert-defined graphs.
- Introduce uncertainty estimates for graph edges.
- Weight graph penalties according to edge confidence.
- Develop corruption operators that preserve a selected topological order.
- Compare random and adversarial graph corruption.
- Identify the smallest graph modification that substantially changes a counterfactual.
- Analyze whether ensemble graphs improve DANCE robustness.
- Compare DANCE with a counterfactual method that does not use a feature-relationship graph.
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.