SleepFM-Clinical Documentation

repository·main·Indexed 20 days ago

https://github.com/zou-group/sleepfm-clinical

A multimodal sleep foundation model for extracting clinically meaningful features from Polysomnography (PSG) recordings. It utilizes a transformer-based contrastive learning approach for sleep staging and predicting future disease risks, such as dementia and cardiovascular issues. The toolkit includes utilities for converting .EDF files to .hdf5, generating 5-second and 5-minute level embeddings, and fine-tuning models for sleep event classification and Cox Proportional Hazards (CoxPH) disease prediction.

Tokens
2.4K
Snippets
6
Records
11
Agent score
22%

What's inside SleepFM-Clinical

  1. Fine-tune for Sleep Staging

    main

    To adapt the pretrained model for sleep stage classification:

    1. Prepare Labels: Ensure you have CSV label files in the format Start,Stop,StageName,StageNumber. These files must be named to correspond with your .EDF and .hdf5 files (e.g., mesa-sleep-0001.csv).
    2. Configure: Check configs/config_finetune_sleep_events.yaml for staging parameters.
    3. Fine-tune: Run sleepfm/pipeline/finetune_sleep_staging.py.
    4. Evaluate: Run sleepfm/pipeline/evaluate_sleep_staging.py to test on the test set.
  2. Pretrain the SleepFM model

    main

    The pretraining process uses a transformer-based contrastive learning approach.

    1. Configuration: Edit configs/config_set_transformer_contrastive.yaml to set your data paths and hyperparameters.
    2. Execution: Run sleepfm/pipeline/pretrain.py.

    Note: The pipeline uses configs/dataset_split.json for data splitting and configs/channel_groups.json for modality channel definitions.

    # Run the pretraining pipeline
    python sleepfm/pipeline/pretrain.py
  3. Fine-tune for Disease Prediction (CoxPH)

    main

    To adapt the pretrained model for predicting disease risk using a Cox Proportional Hazards (CoxPH) loss function:

    1. Configure: Use sleepfm/configs/config_finetune_diagnosis_coxph.yaml.
    2. Data: You must provide your own dataset and set up the appropriate dataloaders.
    3. Execution: Run sleepfm/pipeline/finetune_diagnosis_coxph.py.
  4. Install SleepFM-Clinical

    main

    To set up the SleepFM environment, clone the repository and use Conda to create the environment from the provided env.yml file.

    Recommended Environment:

    • Python: 3.10
    • OS: Linux (tested on CentOS 7.9.2009)
    • GPU: NVIDIA A40, A100, or RTX 2080 Ti (reduce batch size for smaller GPUs)
    • CUDA: 12.4
    • Hardware: 8 CPU cores and at least 32 GB RAM recommended.
    git clone https://github.com/zou-group/sleepfm-clinical.git
    cd sleepfm-clinical
    conda env create -f env.yml
    conda activate sleepfm_env
  5. Generate embeddings for downstream tasks

    main

    After pretraining, generate latent representations (embeddings) for your training, validation, and test sets. These embeddings are used for downstream classification tasks like sleep staging.

    Script: sleepfm/pipeline/generate_embeddings.py

  6. Predict diseases using the Diagnosis model

    main

    The disease prediction model (based on a COXPH framework) outputs log-probabilities for various medical conditions.

    Output Format: The model typically outputs a vector of size 1065, representing log-probabilities for 1065 different conditions.

    Mapping Outputs to Diseases: To understand what each index in the output vector represents, map the indices to their corresponding phecodes using the sleepfm/configs/label_mapping.csv file.

    Data Requirements: The DiagnosisFinetuneFullCOXPHWithDemoDataset requires:

    • HDF5 files containing modality embeddings.
    • Demographic data (e.g., age, gender) in a CSV.
    • Event indicators (is_event.csv) and time-to-event data (time_to_event.csv).
    # Mapping model outputs to disease labels
    import pandas as pd
    
    labels_df = pd.read_csv("../sleepfm/configs/label_mapping.csv")
    
    # Assuming 'all_outputs' are the model's logprobs and 'all_is_event' are the event indicators
    labels_df["output"] = all_outputs[0]
    labels_df["is_event"] = all_is_event[0]
    labels_df["event_time"] = all_event_times[0]
  7. Preprocess EDF files to HDF5

    main

    Before using SleepFM, you must convert your PSG (Polysomnography) recordings from EDF format to HDF5. You can do this using the EDFToHDF5Converter class.

    Important: PSG recordings often have varying channel sets. You must ensure your channels are correctly mapped to modalities (e.g., EEG, EOG, EMG, ECG) by updating sleepfm/configs/channel_groups.json. If your data contains channels not covered by the default mapping, consult a domain expert to categorize them correctly in the config file.

    ```python
    from preprocessing.preprocessing import EDFToHDF5Converter
    import os
    
    base_save_path = "demo_data"
    root_dir = "/edf_root"
    target_dir = "/note"
    
    edf_path = "demo_data/demo_psg.edf"
    hdf5_path = os.path.join(base_save_path, "demo_psg.hdf5")
    
    converter = EDFToHDF5Converter(
        root_dir=root_dir,
        target_dir=target_dir,
        resample_rate=128
    )
    
    # Convert a single file
    converter.convert(edf_path, hdf5_path)

    For batch processing multiple files, use the shell script: sleepfm/preprocessing/preprocessing.sh.

  8. Perform Sleep Staging with finetuned models

    main

    Sleep staging classifies sleep stages (e.g., Wake, Stage 1, Stage 2, Stage 3, REM) from PSG data. While pretrained models are available, it is highly recommended to finetune the model head on your specific dataset to account for distribution shifts.

    Finetuning: Use the script sleepfm/pipeline/finetune_sleep_staging.py to adapt the model to your data.

    Data Loading: Use SleepEventClassificationDataset which requires HDF5 files and corresponding CSV label files. The dataset supports a context parameter to define the sequence length for temporal modeling.

    from models.dataset import SleepEventClassificationDataset
    from torch.utils.data import DataLoader
    
    # Initialize dataset
    test_dataset = SleepEventClassificationDataset(
        sleep_staging_config, 
        channel_groups, 
        split="test", 
        hdf5_paths=hdf5_paths, 
        label_files=label_files
    )
    
    # Use the specific collate function for sleep staging
    test_loader = DataLoader(
        test_dataset, 
        batch_size=8, 
        shuffle=False, 
        num_workers=1, 
        collate_fn=sleep_event_finetune_full_collate_fn
    )
  9. Generate embeddings from SleepFM pretrained model

    main

    You can generate two types of embeddings from the SleepFM pretrained model:

    1. Granular 5-second-level embeddings: High-resolution temporal embeddings.
    2. Aggregated 5-minute-level embeddings: Lower-resolution embeddings suitable for long-term analysis.

    To perform this manually, load the model using its config.json and best.pt checkpoint, then pass the data through a SetTransformerDataset and a DataLoader using the collate_fn.

    # For full automation, use the pipeline script:
    # sleepfm/pipeline/generate_embeddings.py
    
    # Manual snippet for model initialization:
    import torch
    import sys
    from utils import load_config, load_data
    
    model_path = "../sleepfm/checkpoints/model_base"
    config_path = os.path.join(model_path, "config.json")
    config = load_config(config_path)
    
    # Dynamically instantiate the model class defined in config
    model_class = getattr(sys.modules[__name__], config['model'])
    model = model_class(
        config['in_channels'], 
        config['patch_size'], 
        config['embed_dim'], 
        config['num_heads'], 
        config['num_layers'], 
        pooling_head=config['pooling_head'], 
        dropout=0.0
    )
    
    checkpoint = torch.load(os.path.join(model_path, "best.pt"))
    model.load_state_dict(checkpoint["state_dict"])
    model.eval()
  10. Reference: SleepFM Model Checkpoints

    main

    The following pretrained models are available in the repository:

    • Pretrained Base Model: sleepfm/checkpoints/model_base
    • Finetuned Disease Prediction Model: sleepfm/checkpoints/model_diagnosis
    • Finetuned Sleep Staging Model: sleepfm/checkpoints/model_sleep_staging