Skip to content

[Dataset + Taks + Model] PMData stress detection; CLIPStress raw-text input and zero-shot - #1675

Merged
solarsys merged 8 commits into
sunlabuiuc:masterfrom
briannlongzhao:pmdata-stress-detection
Nov 29, 2026
Merged

solarsys merged 8 commits into
sunlabuiuc:masterfrom
briannlongzhao:pmdata-stress-detection

Conversation

@briannlongzhao

@briannlongzhao briannlongzhao commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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 CLIPStress model (raw-text input via text_encoder, zero_shot()), with the end-to-end pipeline on PMData

Paper: 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 on CLIPStress and extends it where PMData needed it. (An earlier version of this PR added a separate CLSP model; it has been removed.)

  • PMDataDataset converts the raw exports once into 11 tidy pmdata-<table>.csv tables, loaded through BaseDataset: 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, and food_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.
  • PMDataStressDetection makes 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 binary stress label (score > 3, as in the paper). Options: feature_groups, stress_threshold, wearable_channels, min_hours, and include_text / text_statistics, which add the paper's text description of each day as a raw string (9 statistics per hourly channel plus one name: value line per feature; stress, mood and label are never included). Inputs are z-scored and imputed by TensorProcessor, fitted on the training split. No existing task covers PMData.
  • CLIPStress extensions (additive; existing behaviour and all existing CLIPStress tests are unchanged):
    • text_encoder: text_key may now be a task's raw text field instead of a precomputed text_embedding tensor. A new FrozenTextEncoder (clip_stress_utils.py) embeds each distinct text once with gradients off (mask-aware mean pooling, as encode_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, so CLIPStress now works straight from set_task output 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 for paper_cosine, dot product for reference_soft); precomputed class_embeddings work 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: 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).

Experiment Random days Unseen participants
Supervised, no pretraining (paper's supervised multimodal baseline) 0.746 ± 0.055 0.590 ± 0.108
Pretrained + fine-tuning (paper's method) 0.748 ± 0.047 (Δ +0.001, 3/5 seeds) 0.590 ± 0.076 (Δ 0.000)
Pretrained + linear probe 0.723 ± 0.032 (Δ −0.024) 0.571 ± 0.135
Ablation: soft contrastive targets (authors' code) 0.750 ± 0.036 (Δ +0.003)
Hyperparameters: temperature 0.03 (default 0.07) 0.745 ± 0.049 (Δ −0.003)
Hyperparameters: temperature 0.2 0.747 ± 0.039 (Δ −0.001)
Hyperparameters: hidden size 32 (default 64) 0.754 ± 0.036 (Δ +0.007)
Hyperparameters: hidden size 128 0.761 ± 0.028 (Δ +0.014, 4/5)
Ablation: text without hourly statistics 0.760 ± 0.025 (Δ +0.012)
Ablation: zero-shot (zero_shot(), no labels) 0.518 ± 0.086
Ablation: 10% labels, supervised 0.648 ± 0.048
Ablation: 10% labels, pretrained + fine-tuning 0.668 ± 0.061 (Δ +0.019, 3/5)

Findings:

  • Pretraining gives no measurable gain on PMData (0.748 vs. 0.746). The paper's PMData gain is also small (81.14 vs. 80.81); here it is well inside the seed-to-seed spread.
  • The authors' architecture is below a plain MLP on this task (0.75 vs. 0.821 below, and the paper's ~81): it attends across only 4 sensor channels (model width 24) with 0.5 dropout, which seems to underfit ~1,000 training days.
  • No generalisation to new people: every variant is near chance for unseen participants (paper: 89.36 for its participant-level split).
  • Objective and temperature do not matter here; a wider network helps slightly (+0.014). Dropping the hourly statistics from the text does not hurt.
  • Zero-shot is at chance — the descriptions never mention stress, so the text space carries no label information.
  • Label scarcity: with 10% of labels, pretraining helps a little (+0.019), the setting the method targets; PMData has few unlabeled days.

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.

Task setting (survey features; hourly wearable always used) Random days (paper's main split) Unseen participants (PatientSplit)
All features (paper's setting) 0.821 ± 0.019 0.557 ± 0.084
No same-day wellness answers 0.796 ± 0.012 0.511 ± 0.073
Passive sensing only (activity, sleep, demographics) 0.793 ± 0.010 0.496 ± 0.086
Demographics only 0.723 ± 0.022 0.323 ± 0.080
All features, stress > 2 0.702 ± 0.027 0.599 ± 0.065

Findings:

  • Reproduces the paper's setting: 0.821 vs. the paper's 80.81 (supervised) and 81.14 (contrastive pretraining) on PMData.
  • Self-report adds little: removing the answers from the stress questionnaire costs 0.025; passive Fitbit data + demographics reach 0.793.
  • Random-day splits reward recognising the participant: demographics + hourly data reach 0.723 on random days but 0.323 on unseen participants.
  • Does not generalise to new people: every setting is near chance for unseen participants, far from the paper's 89.36 for its participant-level split (only 3 test participants per split, so noisy).
  • Label definition matters: a "> 2" threshold lowers random-day AUC to 0.702.

Files to Review:

  • pyhealth/datasets/pmdata.py — dataset and raw-file preparation
  • pyhealth/datasets/configs/pmdata.yaml — table config
  • pyhealth/tasks/pmdata_stress_detection.py — stress detection task
  • pyhealth/models/clip_stress.py — text_encoder (raw text) and zero_shot() added to CLIPStress
  • pyhealth/models/clip_stress_utils.py — new FrozenTextEncoder
  • tests/core/test_pmdata.py — 34 dataset/task tests on synthetic data (each runs in milliseconds; the shared fixture spends ~5 s once starting and stopping BaseDataset's Dask cluster); raw files in a temp folder, in-memory Patients
  • tests/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, FrozenTextEncoder pooling and cache
  • examples/pmdata_stress_detection_clip_stress.py — full pipeline and model ablations; runs on synthetic data without --root. It reuses DaySplit (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 model
  • docs/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 entries
  • pyhealth/datasets/__init__.py, pyhealth/tasks/__init__.py — exports

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 28, 2026
@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.73% (54265 / 61855 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 89 / 89
pyhealth/datasets/pmdata.py 96.13% 273 / 284
pyhealth/models/clip_stress.py 91.63% 186 / 203
pyhealth/models/clip_stress_utils.py 88.10% 148 / 168
pyhealth/tasks/__init__.py 98.44% 126 / 128
pyhealth/tasks/pmdata_stress_detection.py 94.51% 172 / 182

Workflow run · 2688a06

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 1d6531f

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. CLSP seems to duplicate a model PyHealth already has. pyhealth.models.CLIPStress (pyhealth/models/clip_stress.py, with clip_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_stage for use with Trainer, and zero_shot. If these are real gaps, extending CLIPStress may be a better fit than a new class.
  2. If you keep CLSP, update the description's claim that no existing model does this.

Optional suggestions:

  • examples/pmdata_stress_detection_clsp.py imports DaySplit and write_synthetic_pmdata from 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

briannlongzhao and others added 7 commits November 28, 2026 17:55
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>
@briannlongzhao
briannlongzhao force-pushed the pmdata-stress-detection branch from 1d6531f to 088476a Compare November 28, 2026 23:56
Co-authored-by: Wanting Mao <wmao8@illinois.edu>
Co-authored-by: Aditya Radhakrishnan <aditya63@illinois.edu>
@briannlongzhao briannlongzhao changed the title [Dataset + Taks + Model] PMData stress detection with CLSP pretraining [Dataset + Taks + Model] PMData stress detection; CLIPStress raw-text input and zero-shot Nov 29, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 2688a06

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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 CLIPStress changes are additive. text_encoder is 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 CLIPStress use of FrozenTextEncoder, the CLIP example's reuse of DaySplit and write_synthetic_pmdata from the MLP example, and the RawProcessor use.
  • 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.py 96.1%, pmdata_stress_detection.py 94.5%, clip_stress.py 91.6%, clip_stress_utils.py 88.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_time isn't covered. A tiny JPEG with EXIF data would exercise it.

Reviewed commit 2688a06

@solarsys
solarsys merged commit a5bc1bf into sunlabuiuc:master Nov 29, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants