Repository navigation
[Dataset + Taks + Model] PMData stress detection; CLIPStress raw-text input and zero-shot - #1675
Conversation
Test CoverageTotal: 87.73% (54265 / 61855 lines)
|
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: need change
Thank you for this contribution. It adds a PMData dataset, a daily stress detection task and the CLSP model, with synthetic-data tests, docs, two example scripts and reproduction numbers. The dataset and task look sound, and coverage is good: 96% for pmdata.py, 94.5% for the task, 85.7% for clsp.py and 87.6% for the whole repository. All of these meet the bar.
To get this merged:
- CLSP seems to duplicate a model PyHealth already has.
pyhealth.models.CLIPStress(pyhealth/models/clip_stress.py, withclip_stress_utils.py) implements the same paper, Yang et al. CHIL 2025. As far as I can tell, it has the same pretrain, linear-probe and fine-tune stages, the one-to-one and soft contrastive targets, projection heads, and cached frozen-BERT text embeddings. The description says no existing model does contrastive pretraining between sensor/tabular data and text, which doesn't match this. Please either:- remove CLSP and use CLIPStress with the new PMData dataset and task, or
- explain in the description and the CLSP docs why a second model is needed, and compare it with CLIPStress. The differences I can see are time-step attention versus channel attention, the built-in text encoder,
set_stagefor use withTrainer, andzero_shot. If these are real gaps, extending CLIPStress may be a better fit than a new class.
- If you keep CLSP, update the description's claim that no existing model does this.
Optional suggestions:
examples/pmdata_stress_detection_clsp.pyimportsDaySplitandwrite_synthetic_pmdatafrom the other example script. A short note in the description would make that choice clear.- The PMData dataset and task parts look ready on their own. If the model question takes time to settle, you could land them first.
Reviewed commit 1d6531f
Add PMDataDataset for the PMData sports-logging dataset (Fitbit, PMSYS, Google Forms, participant overview and food-image paths as 11 tables) and PMDataStressDetection, the binary daily stress task of Yang et al., "Contrastive Pretraining for Stress Detection with Multimodal Wearable Sensor Data and Surveys" (CHIL 2025). Includes synthetic-data tests, API docs, and an MLP example with task ablations (feature groups, label threshold, day vs participant split). Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
Add CLSP, the model of Yang et al., "Contrastive Pretraining for Stress Detection with Multimodal Wearable Sensor Data and Surveys" (CHIL 2025): a Transformer + tabular residual MLP encoder pretrained with a CLIP loss against frozen BERT embeddings of each day's text description, then linear probing or fine-tuning. Stages switch with set_stage() so every stage runs through Trainer; zero_shot() scores samples against class texts. PMDataStressDetection gains include_text / text_statistics, which add the paper's text description of each day (channel statistics and feature lines, never the label). Includes model tests with a fake text encoder, task text tests, API docs, and a full-pipeline example with ablations (soft vs one-to-one targets, text without statistics, zero-shot, 10% labels, day vs participant split). Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
- examples/pmdata_stress_detection_clsp.py: one-at-a-time sweep of the contrastive temperature (0.03, 0.2) and hidden/projection size (32, 128), with real-data results and findings in the docstring. - Annotate **kwargs and PMDataDataset.default_task's return type. Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
- Use built-in generics and X | None (ruff UP006/UP007/UP035/UP045). - Annotate the task's class-level schemas with ClassVar (RUF012). - Catch only the errors reading a photo's EXIF time can raise (BLE001). - from torch import nn (PLR0402); same style applied to tests and examples. Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
…nd zero-shot PyHealth already has CLIPStress (sunlabuiuc#1516) for the same paper, so CLSP is removed and the PMData pipeline runs on CLIPStress, extended with: - text_encoder: CLIPStress can take a task's raw text field directly, embedded by a frozen encoder cached per text (FrozenTextEncoder in clip_stress_utils) and kept out of the state dict. Cached text_embedding tensors work exactly as before. - zero_shot(): label-free prediction by similarity to class descriptions, scored as in pretraining. Tests in tests/core/test_clip_stress_text.py; the existing CLIPStress tests pass unchanged. The full pipeline example is now examples/pmdata_stress_detection_clip_stress.py. Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
1d6531f to
088476a
Compare
Co-authored-by: Wanting Mao <wmao8@illinois.edu> Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
|
/review |
| Every number is the mean ± std of test ROC-AUC over ``--seeds`` seeds. | ||
|
|
||
| Results on the real PMData (1,688 labeled days, 5 seeds, test ROC-AUC; | ||
| "vs" is the mean paired difference to the reference row of the same seed): |
There was a problem hiding this comment.
[low] Docstring reports paired deltas and seed counts the script does not print
The header says "vs" is the mean paired difference to the reference row, and the Findings cite values such as "+0.001, 3 of 5 seeds" and "+0.019, 3 of 5". main() (line 442 onward) only prints per-seed rows and a mean/std/count summary, so these deltas and seed counts cannot be reproduced from the script. Either compute the paired differences per seed in main() and print them, or drop the Δ and seed-count claims from the docstring.
| } | ||
|
|
||
|
|
||
| class LabeledSubsetSplit(Split): |
There was a problem hiding this comment.
[low] New example scripts and split helpers have no smoke test
The repo runs its existing CLIP examples on synthetic data in tests/core/test_clip_stress_examples.py. The new examples, including LabeledSubsetSplit (line 143) and the per-seed run logic, are not exercised by any test, although the description says they run without --root. Add a short smoke test in the same style that runs run_seed or main on the synthetic PMData writer with one seed and a few epochs.
| return _concat(frames, columns) | ||
|
|
||
|
|
||
| def _image_capture_time(path: Path) -> str | None: |
There was a problem hiding this comment.
[low] EXIF capture-time branch is untested
_image_capture_time only has a test for a file without EXIF ("not a real jpeg"), which returns None. The branch that reads DateTimeOriginal (tag 0x9003) or DateTime and formats it with TIMESTAMP_FORMAT is never run. Add a test that writes a small JPEG with a known EXIF date using PIL, and check that food_images gets the expected timestamp.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: approve
Thank you for this contribution. It adds the PMData dataset and a daily stress detection task. It also extends CLIPStress with raw-text input (text_encoder) and zero_shot(). It includes two example pipelines with ablations and thorough synthetic-data tests.
The change looks ready to merge. I found no blocking problems.
- Existing behaviour: The
CLIPStresschanges are additive.text_encoderis a new trailing keyword. The cached-vector path is unchanged. The frozen encoder is held outside the module tree, so it isn't trained or saved in the state dict. - Sharing: Your description names each link between components and gives a reason for it. These are the
CLIPStressuse ofFrozenTextEncoder, the CLIP example's reuse ofDaySplitandwrite_synthetic_pmdatafrom the MLP example, and theRawProcessoruse. - Dataset source: The class docstring and the docs page both cite the PMData source and paper.
- Coverage: The whole repository is at 87.7%, above the 60% bar. Every changed file is above 80%:
pmdata.py96.1%,pmdata_stress_detection.py94.5%,clip_stress.py91.6%,clip_stress_utils.py88.1%. - Documentation: The docs match the code.
Optional suggestions:
- The CLIP example docstring reports paired deltas and "x of 5 seeds" counts that the script doesn't print. Printing them, or noting how they were computed, would make the results easier to reproduce.
- Both example scripts have no automated smoke test. A small test that runs them on the synthetic data would guard against regressions.
- The EXIF capture-time branch in
_image_capture_timeisn't covered. A tiny JPEG with EXIF data would exercise it.
Reviewed commit 2688a06
Contributors: Brian Zhao (bnzhao2, bnzhao2@illinois.edu), Wanting Mao (wmao8, wmao8@illinois.edu), Aditya Radhakrishnan (aditya63, aditya63@illinois.edu)
Contribution Type: Full pipeline — Dataset + Task + Model improvements: new PMData dataset and stress task, and improvements to the existing
CLIPStressmodel (raw-text input viatext_encoder,zero_shot()), with the end-to-end pipeline on PMDataPaper: Zeyu Yang, Han Yu, Akane Sano. "Contrastive Pretraining for Stress Detection with Multimodal Wearable Sensor Data and Surveys." CHIL 2025 (PMLR 287). https://proceedings.mlr.press/v287/yang25a.html — authors' code: https://github.com/comp-well-org/clip-stress-detection
Dataset: PMData (Thambawita et al., MMSys 2020), open, CC BY-NC 4.0: https://datasets.simula.no/pmdata/
Description:
Reproduces the paper in PyHealth on PMData: the PMData sports-logging dataset (16 participants, ~5 months of Fitbit, PMSYS and Google Forms data), the paper's daily stress detection task, and the full contrastive-pretraining pipeline. PyHealth already has the paper's model,
CLIPStress(#1516, merged Nov 26), so this PR does not add a second model: it runs the pipeline onCLIPStressand extends it where PMData needed it. (An earlier version of this PR added a separateCLSPmodel; it has been removed.)PMDataDatasetconverts the raw exports once into 11 tidypmdata-<table>.csvtables, loaded throughBaseDataset:participants,fitbit_hourly(hourly steps/calories/distance sums and mean heart rate, reduced from >100 MB per-person heart-rate files),fitbit_daily,sleep,sleep_score,exercise,wellness,srpe,injury,reporting, andfood_images(photo paths with EXIF capture time; pixels are not loaded). The participant spreadsheet is read with the standard library, so no new dependency is needed. Missing per-participant files are skipped.PMDataStressDetectionmakes one sample per participant-day with a wellness report:wearable(24 × 4 hourly Fitbit values),survey(daily features from configurable groups: demographics, activity, sleep, training, nutrition, injury, same-day wellness answers), and a binarystresslabel (score > 3, as in the paper). Options:feature_groups,stress_threshold,wearable_channels,min_hours, andinclude_text/text_statistics, which add the paper's text description of each day as arawstring (9 statistics per hourly channel plus onename: valueline per feature; stress, mood and label are never included). Inputs are z-scored and imputed byTensorProcessor, fitted on the training split. No existing task covers PMData.CLIPStressextensions (additive; existing behaviour and all existing CLIPStress tests are unchanged):text_encoder:text_keymay now be a task'srawtext field instead of a precomputedtext_embeddingtensor. A newFrozenTextEncoder(clip_stress_utils.py) embeds each distinct text once with gradients off (mask-aware mean pooling, asencode_stress_prompts(pooling="masked_mean")) and caches it; it is held outside the module tree, so it is not trained or saved in the state dict, and classification stages never call it. Why: PMData's descriptions come from the task, soCLIPStressnow works straight fromset_taskoutput without a separate embedding-cache step.zero_shot(): label-free prediction by comparing each sample's projected embedding with projected class descriptions (default"label: relaxed"/"label: stressed"), scored as in pretraining (cosine forpaper_cosine, dot product forreference_soft); precomputedclass_embeddingswork for models trained on cached vectors. Why: the standard CLIP-style check of whether the pretrained text space carries the label, used in our ablations.tests/core/test_clip_stress_text.py(9 tests, synthetic data, patched Hugging Face loaders).On the real data the task yields 1,688 labeled days (297 stressed).
Full pipeline with CLIPStress (
examples/pmdata_stress_detection_clip_stress.py)PMDataDataset→PMDataStressDetection(include_text=True)→CLIPStress(text_encoder="bert-base-uncased", objective="paper_cosine")→ contrastive pretraining → fine-tuning / linear probe → test ROC-AUC. Same network with and without pretraining, plus model ablations and a one-at-a-time hyperparameter sweep (none of them in the paper); 60/20/20 split, pretraining 50 epochs then 30 epochs of fine-tuning / linear probing (best validation AUC), CLIPStress defaults otherwise, 5 seeds, test ROC-AUC (mean ± std). "Δ" is the mean paired difference to the reference row of the same seed (supervised for the first rows, pretrained + fine-tuning for the ablations).zero_shot(), no labels)Findings:
Task ablation with an existing model (
examples/pmdata_stress_detection_mlp.py)Existing
pyhealth.models.MLP, 60/20/20 split, best-validation-AUC checkpoint, 5 seeds, test ROC-AUC (mean ± std). None of these ablations are in the paper.surveyfeatures; hourlywearablealways used)PatientSplit)Findings:
Files to Review:
pyhealth/datasets/pmdata.py— dataset and raw-file preparationpyhealth/datasets/configs/pmdata.yaml— table configpyhealth/tasks/pmdata_stress_detection.py— stress detection taskpyhealth/models/clip_stress.py—text_encoder(raw text) andzero_shot()added toCLIPStresspyhealth/models/clip_stress_utils.py— newFrozenTextEncodertests/core/test_pmdata.py— 34 dataset/task tests on synthetic data (each runs in milliseconds; the shared fixture spends ~5 s once starting and stoppingBaseDataset's Dask cluster); raw files in a temp folder, in-memoryPatientstests/core/test_clip_stress_text.py— 9 tests for the CLIPStress extensions (fake text encoder, 4 synthetic samples): raw-text pretraining and gradients, encoder frozen and not saved, zero-shot, Trainer step,FrozenTextEncoderpooling and cacheexamples/pmdata_stress_detection_clip_stress.py— full pipeline and model ablations; runs on synthetic data without--root. It reusesDaySplit(the paper's random-day split) and the synthetic PMData writer from the MLP example rather than duplicating them.examples/pmdata_stress_detection_mlp.py— task ablation with an existing modeldocs/api/datasets/pyhealth.datasets.PMDataDataset.rst,docs/api/tasks/pyhealth.tasks.PMDataStressDetection.rst,docs/api/models/pyhealth.models.CLIPStress.rst(new "Raw text and zero-shot prediction" section),docs/api/datasets.rst,docs/api/tasks.rst— docs and index entriespyhealth/datasets/__init__.py,pyhealth/tasks/__init__.py— exports