初始代码
This commit is contained in:
commit
a028d13162
118 files changed
+453914
No files matched your search
@@ -0,0 +1,247 @@
|
||||
<div align="center">
|
||||
|
||||
# 🚀 NormWear: A Foundation Model for Multivariate Wearable Sensing of Physiological Signals.
|
||||
|
||||
[](https://arxiv.org/abs/2412.09758)
|
||||
[](https://github.com/Mobile-Sensing-and-UbiComp-Laboratory/NormWear/releases/tag/v1.0.0-alpha)
|
||||
[](https://drive.google.com/file/d/1Mojf_iby8FnUydogwUE-b321fB1V6SGK/view?usp=sharing)
|
||||
|
||||
</div>
|
||||
|
||||
## ✨ Introduction
|
||||
This is the official implementation of the paper [Toward Foundation Model for Multivariate Wearable Sensing of Physiological Signals](https://arxiv.org/abs/2412.09758).
|
||||
|
||||
<p align="center">
|
||||
<img src="https://drive.google.com/uc?export=view&id=1kLJ9xc7c864mlPzjSo-HCiGRpzdjSMEO" width="100%">
|
||||
<br />
|
||||
</p>
|
||||
|
||||
Time-series foundation models have the ability to run inference, mainly forecasting, on any type of time series data, thanks to the informative representations comprising waveform features. Wearable sensing data, on the other hand, contain more variability in both patterns and frequency bands of interest and generally emphasize more on the ability to infer healthcare-related outcomes. The main challenge of crafting a foundation model for wearable sensing physiological signals is to learn generalizable representations that support efficient adaptation across heterogeneous sensing configurations and applications. In this work, we propose NormWear, a step toward such a foundation model, aiming to extract generalized and informative wearable sensing representations. NormWear has been pretrained on a large set of physiological signals, including PPG, ECG, EEG, GSR, and IMU, from various public resources. For a holistic assessment, we perform downstream evaluation on 11 public wearable sensing datasets, spanning 18 applications in the areas of mental health, body state inference, vital sign estimations, and disease risk evaluations. We demonstrate that NormWear achieves a better performance improvement over competitive SoTA baselines with different modeling strategies. In addition, leveraging a novel representation-alignment-match-based method, we align physiological signals embeddings with text embeddings. This alignment enables our proposed foundation model to perform zero-shot inference, allowing it to generalize to previously unseen wearable signal-based health applications.
|
||||
|
||||
## 📈 Usage
|
||||
|
||||
Download:
|
||||
|
||||
```sh
|
||||
# Clone the repository
|
||||
git clone git@github.com:Mobile-Sensing-and-UbiComp-Laboratory/NormWear.git
|
||||
```
|
||||
The python libraries dependencies are specified in `NormWear/dependencies.txt`, with an example bash script `NormWear/config_env.sh`.
|
||||
|
||||
The pretrained model checkpoint can be found in [Release](https://github.com/Mobile-Sensing-and-UbiComp-Laboratory/NormWear/releases/tag/v1.0.0-alpha).
|
||||
|
||||
### Extracting Encoder Embeddings
|
||||
|
||||
An example showing how to get signal embedding using NormWear:
|
||||
|
||||
```python
|
||||
import torch
|
||||
from NormWear.main_model import NormWearModel
|
||||
|
||||
# config
|
||||
device = torch.device('cpu')
|
||||
|
||||
### init model ##################################################################
|
||||
weight_path = "path to checkpoint here"
|
||||
model = NormWearModel(weight_path=weight_path, optimized_cwt=True).to(device)
|
||||
|
||||
# generate data
|
||||
# test example: 2 samples, 3 sensor, sequence length of 2 seconds
|
||||
# data shape notation: bn for batch size, nvar for number of sensor channels,
|
||||
# P for number of patches, E for embedding dimension (768)
|
||||
sampling_rate = 64
|
||||
x = torch.rand(2, 3, sampling_rate*2).to(device)
|
||||
|
||||
# encoding
|
||||
out = model.get_embedding(x, sampling_rate=sampling_rate, device=device) # bn, nvar, P, E
|
||||
|
||||
# log
|
||||
print("Input shape:", x.shape) # [2, 3, 128]
|
||||
print("Output shape:", out.shape) # [2, 3, P, 768]
|
||||
|
||||
### Example of aggregation across patches ########################################
|
||||
# Take [CLS]
|
||||
# embedding = out[:, :, 0, :] # [2, 3, 768]
|
||||
|
||||
# Mean pooling
|
||||
# embedding = out.mean(dim=2) # [2, 3, 768]
|
||||
|
||||
### Example of aggregation across channels #######################################
|
||||
# Concat
|
||||
# final_embedding = embedding.flatten(start_dim=1) # [2, 3*768]
|
||||
|
||||
# Mean
|
||||
# final_embedding = embedding.mean(dim=1) # [2, 768]
|
||||
```
|
||||
|
||||
### Zero shot inference
|
||||
|
||||
```python
|
||||
import torch
|
||||
from NormWear.zero_shot.msitf_fusion import NormWearZeroShot
|
||||
|
||||
# config
|
||||
device = torch.device('cpu')
|
||||
|
||||
### init model ##################################################################
|
||||
# weight_path = "weight path here"
|
||||
# msitf_ckpt = "fusion weight path here"
|
||||
|
||||
model = NormWearZeroShot(
|
||||
weight_path=weight_path,
|
||||
msitf_ckpt=msitf_ckpt
|
||||
).to(device)
|
||||
|
||||
### generate data ###############################################################
|
||||
sampling_rate = 64
|
||||
x = torch.rand(2, 3, sampling_rate*2).to(device) # test example: 2 samples, 3 sensor, sequence length of 2 seconds
|
||||
|
||||
# setup question and options
|
||||
task_of_interest = [
|
||||
"Is the person doing good?"
|
||||
]
|
||||
|
||||
options = [
|
||||
"The person is doing so so",
|
||||
"The person is under stress.",
|
||||
"The person is having fun.",
|
||||
]
|
||||
|
||||
### Inference ###################################################################
|
||||
# text encoding
|
||||
txt_embed = model.txt_encode(task_of_interest+options) # [4, 2048]
|
||||
|
||||
query_embed, option_embed = txt_embed[:1, :], txt_embed[1:, :]
|
||||
|
||||
# signal encoding
|
||||
signal_embed = model.signal_encode(x, query_embed, sampling_rate=sampling_rate) # bn, nvar, P, E
|
||||
|
||||
# calculate distance
|
||||
pred_prob = model.inference(signal_embed, option_embed) # bn, num_options
|
||||
pred = torch.argmax(pred_prob, dim=1).numpy()
|
||||
|
||||
### check output ################################################################
|
||||
for i in range(len(x)):
|
||||
print("Sample {} inference: {}".format(i, options[pred[i]]))
|
||||
|
||||
# log
|
||||
print("Input shape:", x.shape) # [2, 3, 128]
|
||||
print("Text embed shape:", txt_embed.shape) # [4, 2048]
|
||||
print("Signal embed shape:", signal_embed.shape) # [2, 3, P, 768]
|
||||
print("Inference probability shape:", pred_prob.shape) # # [2, num_options]
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> For the best performance, conduct prompt engineering on the query could be a good practice.
|
||||
|
||||
## 🔥 Pre-training
|
||||
To run the evaluation on the downstream datasets, run the following command:
|
||||
```sh
|
||||
python3 -m NormWear.pretrain_main
|
||||
```
|
||||
|
||||
|
||||
| Required Parameter | Type | Default | Description |
|
||||
|---------------------|-----------|-----------|-----------------------------------------------------------------------|
|
||||
| `--batch_size` | `<int>` | `4` | Number of input samples for each round of forward and backpropagation. |
|
||||
| `--epochs` | `<int>` | `400` | Number of epochs. |
|
||||
| `--blr` | `<float>` | `1e-3` | base learning rate: absolute_lr = base_lr * total_batch_size / 256 |
|
||||
| `--warmup_epochs` | `<int>` | `10` | Number of epochs to increase learning rate from a small number to `blr`. |
|
||||
| `--target_len` | `<int>` | `388` | Sequence length of the reconstructed time series |
|
||||
| `--weight_decay` | `<float>` | `5e-2` | Regularization coefficient of L2 penalty on model parameters. |
|
||||
| `--mask_scheme` | `<str>` | `random` | Masking scheme for pretext task (choose from 'random' and 'struc') |
|
||||
| `--mask__prob` | `<float>` | `0.8` | Masking ratio for random masking |
|
||||
| `--mask_t_prob` | `<float>` | `0.6` | Masking ratio along time axis of the scalogram. |
|
||||
| `--mask_f_prob` | `<float>` | `0.5` | Masking ratio along scale axis of the scalogram. |
|
||||
| `--remark` | `<string>` | `""` | Name to mark the current experimental trail. |
|
||||
|
||||
An example bash command would be:
|
||||
```sh
|
||||
torchrun --nproc_per_node=4 --master_port=12345 -m NormWear.pretrain_main --batch_size 256 --epochs 100 --warmup_epochs 4 --remark test_run
|
||||
```
|
||||
|
||||
|
||||
## ❄️ Downstream Evaluation
|
||||
|
||||
To run the evaluation on the downstream datasets, run the following command:
|
||||
```sh
|
||||
python3 -m NormWear.downstream_main
|
||||
```
|
||||
|
||||
|
||||
| Required Parameter | Type | Default | Description |
|
||||
|--------------------------|-----------|-----------|-----------------------------------------------------------------------------|
|
||||
| `--model_name` | `<string>` | `normwear` | Supported models are [stats, chronos, clap, tfc, normwear] |
|
||||
| `--model_weight_dir` | `<string>` | `""` | Path to the model checkpoint, only `normwear` need this parameter. |
|
||||
| `--group` | `<int>` | `0` | Run a group of downstream tasks. The group can be customized in `NormWear/downstream_main.py` |
|
||||
| `--data_path` | `<string>` | `../data` | Root path for where the downstream data is placed. |
|
||||
| `--num_runs` | `<int>` | `1` | Number of repetition for running the evaluation of each task. |
|
||||
| `--prepare_embed` | `<int>` | `1` | Run the inference and save the embeddings before sending them to evaluation. Set to `1` to overwrite previous saved embedding if there are any. |
|
||||
| `--remark` | `<string>` | `""` | Name to mark the current experimental trail. By default, all the embeddings are stored under a subfolder named as `--model_name` under the folder of each downstream data. |
|
||||
|
||||
An example bash command would be:
|
||||
```sh
|
||||
CUDA_VISIBLE_DEVICES=0 python3 -m NormWear.downstream_main --model_name normwear --model_weight_dir data/results/normwear_last_checkpoint-15470-correct.pth --group 0 --data_path ../data --num_runs 1 --prepare_embed 1 --remark test_run
|
||||
```
|
||||
|
||||
#### :floppy_disk: The processed clean downstream datasets can be downloaded from [here](https://drive.google.com/file/d/1Mojf_iby8FnUydogwUE-b321fB1V6SGK/view?usp=sharing).
|
||||
|
||||
### ✏️ For adding a downstream dataset, please following the format:
|
||||
```bash
|
||||
name_of_new_dataset/
|
||||
├── sample_for_downstream/
|
||||
│ ├── name_of_sample_0.pkl
|
||||
│ ├── name_of_sample_1.pkl
|
||||
│ ├── name_of_sample_2.pkl
|
||||
│ └── ...
|
||||
└── train_test_split.json
|
||||
```
|
||||
where the content in each file requires content in the following format:
|
||||
```python
|
||||
# data content in name_of_sample_i.pkl
|
||||
{
|
||||
"uid": "", # subject ID identifier
|
||||
"data": np.array(sensor_data_here).astype(np.float16), # float numpy array with shape of [num_channels, sequence_length]
|
||||
"sampling_rate": 64, # put the correct sampling rate of the sensor signal here.
|
||||
"label": [ # label for each task on this dataset. 'class' for classification and 'reg' for regression.
|
||||
{"class": label},
|
||||
{"reg": label},
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
# data content in train_test_split.json
|
||||
{
|
||||
'train': ["name_of_sample_i.pkl", "name_of_sample_j.pkl", "name_of_sample_k.pkl", ...],
|
||||
'test': ["name_of_sample_l.pkl", "name_of_sample_m.pkl", "name_of_sample_n.pkl", ...]
|
||||
}
|
||||
```
|
||||
### 🔥 Finetuning model for downstream datasets
|
||||
To run the evaluation on the downstream datasets, run the following command:
|
||||
```sh
|
||||
python -m main_finetune --ds_name <dataset_name> --checkpoint <weight_path>
|
||||
```
|
||||
For multiple gpus, run:
|
||||
```sh
|
||||
torchrun --nproc_per_node=<number of device> main_finetune.py --world_size <number of device> --ds_name <dataset_name> --checkpoint <weight_path>
|
||||
```
|
||||
## 📝 Citation
|
||||
|
||||
If you find NormWear model useful for your research, please consider citing the associated [paper]([https://arxiv.org/abs/2403.07815](https://TBD)):
|
||||
|
||||
```
|
||||
@misc{luo2024foundationmodelmultivariatewearable,
|
||||
title={Toward Foundation Model for Multivariate Wearable Sensing of Physiological Signals},
|
||||
author={Yunfei Luo and Yuliang Chen and Asif Salekin and Tauhidur Rahman},
|
||||
year={2024},
|
||||
eprint={2412.09758},
|
||||
archivePrefix={arXiv},
|
||||
primaryClass={cs.LG},
|
||||
url={https://arxiv.org/abs/2412.09758},
|
||||
}
|
||||
```
|
||||
|
||||
## 📃 License
|
||||
This project is licensed under the [Apache License 2.0](LICENSE).
|
||||
|
||||
k
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
"""This file aims to generate a different data split to evaluate the stability of models.
|
||||
In each split, we select 30 positive and 30 negative samples to form a training set (60 samples in total).
|
||||
This is an example on Epilepsy dataset. -- Xiang Zhang, Jan 16, 2023"""
|
||||
|
||||
import torch
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
targetdata_path = f"../../datasets/Epilepsy/"
|
||||
|
||||
finetune_dataset = torch.load(os.path.join(targetdata_path, "test.pt"))
|
||||
train_data = torch.load(os.path.join(targetdata_path, "train.pt"))
|
||||
Samples = torch.cat((finetune_dataset['samples'], train_data['samples']), dim=0)
|
||||
Labels = torch.cat((finetune_dataset['labels'], train_data['labels']), dim=0)
|
||||
|
||||
train_size = 30
|
||||
|
||||
"""Generate balanced training set"""
|
||||
id0 = Labels==0
|
||||
id1 = Labels==1
|
||||
|
||||
Samples_0, Samples_1 = Samples[id0], Samples[id1]
|
||||
Labels_0, Labels_1 = Labels[id0], Labels[id1]
|
||||
|
||||
Samples_train = torch.cat((Samples_0[:train_size], Samples_1[:train_size]))
|
||||
Samples_test = torch.cat((Samples_0[train_size:], Samples_1[train_size:]))
|
||||
|
||||
Labels_train = torch.cat((Labels_0[:train_size], Labels_1[:train_size]))
|
||||
Labels_test = torch.cat((Labels_0[train_size:], Labels_1[train_size:]))
|
||||
|
||||
# """Generate imbalanced training set"""
|
||||
# data = list(zip(Samples, Labels))
|
||||
# np.random.shuffle(data)
|
||||
# X, y = zip(*data)
|
||||
# X = torch.stack(list(X), dim=0)
|
||||
# y = torch.stack(list(y), dim=0)
|
||||
# Samples_train, Samples_test = X[:train_size], X[train_size:]
|
||||
# Labels_train, Labels_test = y[:train_size], y[train_size:]
|
||||
|
||||
train_dic = {'samples':Samples_train, 'labels':Labels_train}
|
||||
test_dic = {'samples':Samples_test, 'labels':Labels_test}
|
||||
torch.save(train_dic, os.path.join(targetdata_path,'train.pt'))
|
||||
torch.save(test_dic, os.path.join(targetdata_path,'test.pt'))
|
||||
|
||||
print('Re-split finished. Dataset saved to folder:', targetdata_path)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""It's a KNN baseline for prompt sanity check of the dataset. -- Xiang Zhang Jan 16, 2013"""
|
||||
|
||||
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix, \
|
||||
average_precision_score, accuracy_score, precision_score,f1_score,recall_score
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
import torch,os
|
||||
import numpy as np
|
||||
|
||||
|
||||
def one_hot_encoding(X):
|
||||
X = [int(x) for x in X]
|
||||
n_values = np.max(X) + 1
|
||||
b = np.eye(n_values)[X]
|
||||
return b
|
||||
|
||||
traindata = torch.load(os.path.join('../../datasets/Epilepsy', "test.pt"))
|
||||
valdata = torch.load(os.path.join('../../datasets/Epilepsy', "val.pt"))
|
||||
|
||||
train_fea, train_label = traindata['samples'].detach().cpu().numpy().squeeze(1), traindata['labels'].detach().cpu().numpy()
|
||||
val_fea, val_label = valdata['samples'].detach().cpu().numpy().squeeze(1), valdata['labels'].detach().cpu().numpy()
|
||||
|
||||
|
||||
# train classifier: KNN
|
||||
neigh = KNeighborsClassifier(n_neighbors=1)
|
||||
neigh.fit(train_fea, train_label) # .detach().cpu().numpy()
|
||||
knn_acc_train = neigh.score(train_fea, train_label) # .detach().cpu().numpy()
|
||||
print('KNN finetune acc:', knn_acc_train)
|
||||
# test the downstream classifier
|
||||
# representation_test = emb_test.detach().cpu().numpy()
|
||||
knn_result = neigh.predict(val_fea)
|
||||
knn_result_score = neigh.predict_proba(val_fea)
|
||||
one_hot_label_test = one_hot_encoding(val_label)
|
||||
print(classification_report(val_label, knn_result, digits=4))
|
||||
print(confusion_matrix(val_label, knn_result))
|
||||
knn_acc = accuracy_score(val_label, knn_result)
|
||||
precision = precision_score(val_label, knn_result, average='macro', )
|
||||
recall = recall_score(val_label, knn_result, average='macro', )
|
||||
F1 = f1_score(val_label, knn_result, average='macro')
|
||||
auc = roc_auc_score(knn_result_score, one_hot_label_test, average="macro", multi_class="ovr")
|
||||
prc = average_precision_score(knn_result_score, one_hot_label_test, average="macro")
|
||||
print("KNN Train Acc:{}. '\n' Test: acc {}, precision {}, Recall {}, F1 {}, AUROC {}, AUPRC {}"
|
||||
"".format(knn_acc_train, knn_acc, precision, recall, F1, auc, prc))
|
||||
Binary file not shown.
@@ -0,0 +1,133 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
def one_hot_encoding(X):
|
||||
X = [int(x) for x in X]
|
||||
n_values = np.max(X) + 1
|
||||
b = np.eye(n_values)[X]
|
||||
return b
|
||||
|
||||
def DataTransform(sample, config):
|
||||
"""Weak and strong augmentations"""
|
||||
weak_aug = scaling(sample, config.augmentation.jitter_scale_ratio)
|
||||
# weak_aug = permutation(sample, max_segments=config.augmentation.max_seg)
|
||||
strong_aug = jitter(permutation(sample, max_segments=config.augmentation.max_seg), config.augmentation.jitter_ratio)
|
||||
|
||||
return weak_aug, strong_aug
|
||||
|
||||
# def DataTransform_TD(sample, config):
|
||||
# """Weak and strong augmentations"""
|
||||
# weak_aug = sample
|
||||
# strong_aug = jitter(permutation(sample, max_segments=config.augmentation.max_seg), config.augmentation.jitter_ratio) #masking(sample)
|
||||
# return weak_aug, strong_aug
|
||||
#
|
||||
# def DataTransform_FD(sample, config):
|
||||
# """Weak and strong augmentations in Frequency domain """
|
||||
# # weak_aug = remove_frequency(sample, 0.1)
|
||||
# strong_aug = add_frequency(sample, 0.1)
|
||||
# return weak_aug, strong_aug
|
||||
def DataTransform_TD(sample, config):
|
||||
"""Simplely use the jittering augmentation. Feel free to add more autmentations you want,
|
||||
but we noticed that in TF-C framework, the augmentation has litter impact on the final tranfering performance."""
|
||||
aug = jitter(sample, config.augmentation.jitter_ratio)
|
||||
return aug
|
||||
|
||||
|
||||
def DataTransform_TD_bank(sample, config):
|
||||
"""Augmentation bank that includes four augmentations and randomly select one as the positive sample.
|
||||
You may use this one the replace the above DataTransform_TD function."""
|
||||
aug_1 = jitter(sample, config.augmentation.jitter_ratio)
|
||||
aug_2 = scaling(sample, config.augmentation.jitter_scale_ratio)
|
||||
aug_3 = permutation(sample, max_segments=config.augmentation.max_seg)
|
||||
aug_4 = masking(sample, keepratio=0.9)
|
||||
|
||||
li = np.random.randint(0, 4, size=[sample.shape[0]])
|
||||
li_onehot = one_hot_encoding(li)
|
||||
aug_1 = aug_1 * li_onehot[:, 0][:, None, None] # the rows that are not selected are set as zero.
|
||||
aug_2 = aug_2 * li_onehot[:, 0][:, None, None]
|
||||
aug_3 = aug_3 * li_onehot[:, 0][:, None, None]
|
||||
aug_4 = aug_4 * li_onehot[:, 0][:, None, None]
|
||||
aug_T = aug_1 + aug_2 + aug_3 + aug_4
|
||||
return aug_T
|
||||
|
||||
def DataTransform_FD(sample, config):
|
||||
"""Weak and strong augmentations in Frequency domain """
|
||||
aug_1 = remove_frequency(sample, pertub_ratio=0.1)
|
||||
aug_2 = add_frequency(sample, pertub_ratio=0.1)
|
||||
aug_F = aug_1 + aug_2
|
||||
return aug_F
|
||||
|
||||
def remove_frequency(x, pertub_ratio=0.0):
|
||||
mask = torch.cuda.FloatTensor(x.shape).uniform_() > pertub_ratio # maskout_ratio are False
|
||||
mask = mask.to(x.device)
|
||||
return x*mask
|
||||
|
||||
def add_frequency(x, pertub_ratio=0.0):
|
||||
|
||||
mask = torch.cuda.FloatTensor(x.shape).uniform_() > (1-pertub_ratio) # only pertub_ratio of all values are True
|
||||
mask = mask.to(x.device)
|
||||
max_amplitude = x.max()
|
||||
random_am = torch.rand(mask.shape)*(max_amplitude*0.1)
|
||||
pertub_matrix = mask*random_am
|
||||
return x+pertub_matrix
|
||||
|
||||
|
||||
def generate_binomial_mask(B, T, D, p=0.5): # p is the ratio of not zero
|
||||
return torch.from_numpy(np.random.binomial(1, p, size=(B, T, D))).to(torch.bool)
|
||||
|
||||
def masking(x, keepratio=0.9, mask= 'binomial'):
|
||||
global mask_id
|
||||
nan_mask = ~x.isnan().any(axis=-1)
|
||||
x[~nan_mask] = 0
|
||||
# x = self.input_fc(x) # B x T x Ch
|
||||
|
||||
if mask == 'binomial':
|
||||
mask_id = generate_binomial_mask(x.size(0), x.size(1), x.size(2), p=keepratio).to(x.device)
|
||||
# elif mask == 'continuous':
|
||||
# mask = generate_continuous_mask(x.size(0), x.size(1)).to(x.device)
|
||||
# elif mask == 'all_true':
|
||||
# mask = x.new_full((x.size(0), x.size(1)), True, dtype=torch.bool)
|
||||
# elif mask == 'all_false':
|
||||
# mask = x.new_full((x.size(0), x.size(1)), False, dtype=torch.bool)
|
||||
# elif mask == 'mask_last':
|
||||
# mask = x.new_full((x.size(0), x.size(1)), True, dtype=torch.bool)
|
||||
# mask[:, -1] = False
|
||||
|
||||
# mask &= nan_mask
|
||||
x[~mask_id] = 0
|
||||
return x
|
||||
|
||||
def jitter(x, sigma=0.8):
|
||||
# https://arxiv.org/pdf/1706.00527.pdf
|
||||
return x + np.random.normal(loc=0., scale=sigma, size=x.shape)
|
||||
|
||||
|
||||
def scaling(x, sigma=1.1):
|
||||
# https://arxiv.org/pdf/1706.00527.pdf
|
||||
factor = np.random.normal(loc=2., scale=sigma, size=(x.shape[0], x.shape[2]))
|
||||
ai = []
|
||||
for i in range(x.shape[1]):
|
||||
xi = x[:, i, :]
|
||||
ai.append(np.multiply(xi, factor[:, :])[:, np.newaxis, :])
|
||||
return np.concatenate((ai), axis=1)
|
||||
|
||||
def permutation(x, max_segments=5, seg_mode="random"):
|
||||
orig_steps = np.arange(x.shape[2])
|
||||
|
||||
num_segs = np.random.randint(1, max_segments, size=(x.shape[0]))
|
||||
|
||||
ret = np.zeros_like(x)
|
||||
for i, pat in enumerate(x):
|
||||
if num_segs[i] > 1:
|
||||
if seg_mode == "random":
|
||||
split_points = np.random.choice(x.shape[2] - 2, num_segs[i] - 1, replace=False)
|
||||
split_points.sort()
|
||||
splits = np.split(orig_steps, split_points)
|
||||
else:
|
||||
splits = np.array_split(orig_steps, num_segs[i])
|
||||
warp = np.concatenate(np.random.permutation(splits)).ravel()
|
||||
ret[i] = pat[0,warp]
|
||||
else:
|
||||
ret[i] = pat
|
||||
return torch.from_numpy(ret)
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import torch
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data import Dataset
|
||||
import os
|
||||
import numpy as np
|
||||
from augmentations import DataTransform_FD, DataTransform_TD
|
||||
import torch.fft as fft
|
||||
|
||||
def generate_freq(dataset, config):
|
||||
X_train = dataset["samples"]
|
||||
y_train = dataset['labels']
|
||||
# shuffle
|
||||
data = list(zip(X_train, y_train))
|
||||
np.random.shuffle(data)
|
||||
data = data[:10000] # take a subset for testing.
|
||||
X_train, y_train = zip(*data)
|
||||
X_train, y_train = torch.stack(list(X_train), dim=0), torch.stack(list(y_train), dim=0)
|
||||
|
||||
if len(X_train.shape) < 3:
|
||||
X_train = X_train.unsqueeze(2)
|
||||
|
||||
if X_train.shape.index(min(X_train.shape)) != 1: # make sure the Channels in second dim
|
||||
X_train = X_train.permute(0, 2, 1)
|
||||
|
||||
"""Align the TS length between source and target datasets"""
|
||||
X_train = X_train[:, :1, :int(config.TSlength_aligned)] # take the first 178 samples
|
||||
|
||||
if isinstance(X_train, np.ndarray):
|
||||
x_data = torch.from_numpy(X_train)
|
||||
else:
|
||||
x_data = X_train
|
||||
|
||||
"""Transfer x_data to Frequency Domain. If use fft.fft, the output has the same shape; if use fft.rfft,
|
||||
the output shape is half of the time window."""
|
||||
|
||||
x_data_f = fft.fft(x_data).abs() #/(window_length) # rfft for real value inputs.
|
||||
return (X_train, y_train, x_data_f)
|
||||
|
||||
class Load_Dataset(Dataset):
|
||||
# Initialize your data, download, etc.
|
||||
def __init__(self, dataset, config, training_mode, target_dataset_size=64, subset=False):
|
||||
super(Load_Dataset, self).__init__()
|
||||
self.training_mode = training_mode
|
||||
X_train = dataset["samples"]
|
||||
y_train = dataset["labels"]
|
||||
# shuffle
|
||||
data = list(zip(X_train, y_train))
|
||||
np.random.shuffle(data)
|
||||
X_train, y_train = zip(*data)
|
||||
X_train, y_train = torch.stack(list(X_train), dim=0), torch.stack(list(y_train), dim=0)
|
||||
|
||||
if len(X_train.shape) < 3:
|
||||
X_train = X_train.unsqueeze(2)
|
||||
|
||||
if X_train.shape.index(min(X_train.shape)) != 1: # make sure the Channels in second dim
|
||||
X_train = X_train.permute(0, 2, 1)
|
||||
|
||||
"""Align the TS length between source and target datasets"""
|
||||
X_train = X_train[:, :1, :int(config.TSlength_aligned)] # take the first 178 samples
|
||||
|
||||
"""Subset for debugging"""
|
||||
if subset == True:
|
||||
subset_size = target_dataset_size * 10 #30 #7 # 60*1
|
||||
"""if the dimension is larger than 178, take the first 178 dimensions. If multiple channels, take the first channel"""
|
||||
X_train = X_train[:subset_size]
|
||||
y_train = y_train[:subset_size]
|
||||
print('Using subset for debugging, the datasize is:', y_train.shape[0])
|
||||
|
||||
if isinstance(X_train, np.ndarray):
|
||||
self.x_data = torch.from_numpy(X_train)
|
||||
self.y_data = torch.from_numpy(y_train).long()
|
||||
else:
|
||||
self.x_data = X_train
|
||||
self.y_data = y_train
|
||||
|
||||
"""Transfer x_data to Frequency Domain. If use fft.fft, the output has the same shape; if use fft.rfft,
|
||||
the output shape is half of the time window."""
|
||||
|
||||
window_length = self.x_data.shape[-1]
|
||||
self.x_data_f = fft.fft(self.x_data).abs() #/(window_length) # rfft for real value inputs.
|
||||
self.len = X_train.shape[0]
|
||||
|
||||
"""Augmentation"""
|
||||
if training_mode == "pre_train": # no need to apply Augmentations in other modes
|
||||
self.aug1 = DataTransform_TD(self.x_data, config)
|
||||
self.aug1_f = DataTransform_FD(self.x_data_f, config) # [7360, 1, 90]
|
||||
|
||||
def __getitem__(self, index):
|
||||
if self.training_mode == "pre_train":
|
||||
return self.x_data[index], self.y_data[index], self.aug1[index], \
|
||||
self.x_data_f[index], self.aug1_f[index]
|
||||
else:
|
||||
return self.x_data[index], self.y_data[index], self.x_data[index], \
|
||||
self.x_data_f[index], self.x_data_f[index]
|
||||
|
||||
def __len__(self):
|
||||
return self.len
|
||||
|
||||
|
||||
def data_generator(sourcedata_path, targetdata_path, configs, training_mode, subset=True):
|
||||
train_dataset = torch.load(os.path.join(sourcedata_path, "train.pt"))
|
||||
finetune_dataset = torch.load(os.path.join(targetdata_path, "train.pt")) # train.pt
|
||||
test_dataset = torch.load(os.path.join(targetdata_path, "test.pt")) # test.pt
|
||||
"""In pre-training:
|
||||
train_dataset: [371055, 1, 178] from SleepEEG.
|
||||
finetune_dataset: [60, 1, 178], test_dataset: [11420, 1, 178] from Epilepsy"""
|
||||
|
||||
# subset = True # if true, use a subset for debugging.
|
||||
train_dataset = Load_Dataset(train_dataset, configs, training_mode, target_dataset_size=configs.batch_size, subset=subset) # for self-supervised, the data are augmented here
|
||||
finetune_dataset = Load_Dataset(finetune_dataset, configs, training_mode, target_dataset_size=configs.target_batch_size, subset=subset)
|
||||
test_dataset = Load_Dataset(test_dataset, configs, training_mode,
|
||||
target_dataset_size=configs.target_batch_size, subset=False)
|
||||
|
||||
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=configs.batch_size,
|
||||
shuffle=True, drop_last=configs.drop_last,
|
||||
num_workers=0)
|
||||
finetune_loader = torch.utils.data.DataLoader(dataset=finetune_dataset, batch_size=configs.target_batch_size,
|
||||
shuffle=True, drop_last=configs.drop_last,
|
||||
num_workers=0)
|
||||
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=configs.target_batch_size,
|
||||
shuffle=True, drop_last=False,
|
||||
num_workers=0)
|
||||
|
||||
return train_loader, finetune_loader, test_loader
|
||||
@@ -0,0 +1,193 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
class NTXentLoss(torch.nn.Module):
|
||||
def __init__(self, device, batch_size, temperature, use_cosine_similarity):
|
||||
super(NTXentLoss, self).__init__()
|
||||
self.batch_size = batch_size
|
||||
self.temperature = temperature
|
||||
self.device = device
|
||||
self.softmax = torch.nn.Softmax(dim=-1)
|
||||
self.mask_samples_from_same_repr = self._get_correlated_mask().type(torch.bool)
|
||||
self.similarity_function = self._get_similarity_function(use_cosine_similarity)
|
||||
self.criterion = torch.nn.CrossEntropyLoss(reduction="sum")
|
||||
|
||||
def _get_similarity_function(self, use_cosine_similarity):
|
||||
if use_cosine_similarity:
|
||||
self._cosine_similarity = torch.nn.CosineSimilarity(dim=-1)
|
||||
return self._cosine_simililarity
|
||||
else:
|
||||
return self._dot_simililarity
|
||||
|
||||
def _get_correlated_mask(self):
|
||||
diag = np.eye(2 * self.batch_size)
|
||||
l1 = np.eye((2 * self.batch_size), 2 * self.batch_size, k=-self.batch_size)
|
||||
l2 = np.eye((2 * self.batch_size), 2 * self.batch_size, k=self.batch_size)
|
||||
mask = torch.from_numpy((diag + l1 + l2))
|
||||
mask = (1 - mask).type(torch.bool)
|
||||
return mask.to(self.device)
|
||||
|
||||
@staticmethod
|
||||
def _dot_simililarity(x, y):
|
||||
v = torch.tensordot(x.unsqueeze(1), y.T.unsqueeze(0), dims=2)
|
||||
# x shape: (N, 1, C)
|
||||
# y shape: (1, C, 2N)
|
||||
# v shape: (N, 2N)
|
||||
return v
|
||||
|
||||
def _cosine_simililarity(self, x, y):
|
||||
# x shape: (N, 1, C)
|
||||
# y shape: (1, 2N, C)
|
||||
# v shape: (N, 2N)
|
||||
v = self._cosine_similarity(x.unsqueeze(1), y.unsqueeze(0))
|
||||
return v
|
||||
|
||||
def forward(self, zis, zjs):
|
||||
representations = torch.cat([zjs, zis], dim=0)
|
||||
|
||||
similarity_matrix = self.similarity_function(representations, representations)
|
||||
|
||||
# filter out the scores from the positive samples
|
||||
l_pos = torch.diag(similarity_matrix, self.batch_size)
|
||||
r_pos = torch.diag(similarity_matrix, -self.batch_size)
|
||||
positives = torch.cat([l_pos, r_pos]).view(2 * self.batch_size, 1)
|
||||
|
||||
negatives = similarity_matrix[self.mask_samples_from_same_repr].view(2 * self.batch_size, -1)
|
||||
|
||||
logits = torch.cat((positives, negatives), dim=1)
|
||||
logits /= self.temperature
|
||||
|
||||
"""Criterion has an internal one-hot function. Here, make all positives as 1 while all negatives as 0. """
|
||||
labels = torch.zeros(2 * self.batch_size).to(self.device).long()
|
||||
loss = self.criterion(logits, labels)
|
||||
|
||||
return loss / (2 * self.batch_size)
|
||||
|
||||
class NTXentLoss_poly(torch.nn.Module):
|
||||
|
||||
def __init__(self, device, batch_size, temperature, use_cosine_similarity):
|
||||
super(NTXentLoss_poly, self).__init__()
|
||||
self.batch_size = batch_size
|
||||
self.temperature = temperature
|
||||
self.device = device
|
||||
self.softmax = torch.nn.Softmax(dim=-1)
|
||||
self.mask_samples_from_same_repr = self._get_correlated_mask().type(torch.bool)
|
||||
self.similarity_function = self._get_similarity_function(use_cosine_similarity)
|
||||
self.criterion = torch.nn.CrossEntropyLoss(reduction="sum")
|
||||
|
||||
def _get_similarity_function(self, use_cosine_similarity):
|
||||
if use_cosine_similarity:
|
||||
self._cosine_similarity = torch.nn.CosineSimilarity(dim=-1)
|
||||
return self._cosine_simililarity
|
||||
else:
|
||||
return self._dot_simililarity
|
||||
|
||||
def _get_correlated_mask(self):
|
||||
diag = np.eye(2 * self.batch_size)
|
||||
l1 = np.eye((2 * self.batch_size), 2 * self.batch_size, k=-self.batch_size)
|
||||
l2 = np.eye((2 * self.batch_size), 2 * self.batch_size, k=self.batch_size)
|
||||
mask = torch.from_numpy((diag + l1 + l2))
|
||||
mask = (1 - mask).type(torch.bool)
|
||||
return mask.to(self.device)
|
||||
|
||||
@staticmethod
|
||||
def _dot_simililarity(x, y):
|
||||
v = torch.tensordot(x.unsqueeze(1), y.T.unsqueeze(0), dims=2)
|
||||
# x shape: (N, 1, C)
|
||||
# y shape: (1, C, 2N)
|
||||
# v shape: (N, 2N)
|
||||
return v
|
||||
|
||||
def _cosine_simililarity(self, x, y):
|
||||
# x shape: (N, 1, C)
|
||||
# y shape: (1, 2N, C)
|
||||
# v shape: (N, 2N)
|
||||
v = self._cosine_similarity(x.unsqueeze(1), y.unsqueeze(0))
|
||||
return v
|
||||
|
||||
def forward(self, zis, zjs):
|
||||
representations = torch.cat([zjs, zis], dim=0)
|
||||
|
||||
similarity_matrix = self.similarity_function(representations, representations)
|
||||
|
||||
# filter out the scores from the positive samples
|
||||
l_pos = torch.diag(similarity_matrix, self.batch_size)
|
||||
r_pos = torch.diag(similarity_matrix, -self.batch_size)
|
||||
positives = torch.cat([l_pos, r_pos]).view(2 * self.batch_size, 1)
|
||||
|
||||
negatives = similarity_matrix[self.mask_samples_from_same_repr].view(2 * self.batch_size, -1)
|
||||
|
||||
logits = torch.cat((positives, negatives), dim=1)
|
||||
logits /= self.temperature
|
||||
|
||||
"""Criterion has an internal one-hot function. Here, make all positives as 1 while all negatives as 0. """
|
||||
labels = torch.zeros(2 * self.batch_size).to(self.device).long()
|
||||
CE = self.criterion(logits, labels)
|
||||
|
||||
onehot_label = torch.cat((torch.ones(2 * self.batch_size, 1),torch.zeros(2 * self.batch_size, negatives.shape[-1])),dim=-1).to(self.device).long()
|
||||
# Add poly loss
|
||||
pt = torch.mean(onehot_label* torch.nn.functional.softmax(logits,dim=-1))
|
||||
|
||||
epsilon = self.batch_size
|
||||
# loss = CE/ (2 * self.batch_size) + epsilon*(1-pt) # replace 1 by 1/self.batch_size
|
||||
loss = CE / (2 * self.batch_size) + epsilon * (1/self.batch_size - pt)
|
||||
# loss = CE / (2 * self.batch_size)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
|
||||
class hierarchical_contrastive_loss(torch.nn.Module):
|
||||
|
||||
def __init__(self, device):
|
||||
super(hierarchical_contrastive_loss, self).__init__()
|
||||
self.device = device
|
||||
|
||||
def instance_contrastive_loss(self, z1, z2):
|
||||
B, T = z1.size(0), z1.size(1)
|
||||
if B == 1:
|
||||
return z1.new_tensor(0.)
|
||||
z = torch.cat([z1, z2], dim=0) # 2B x T x C
|
||||
z = z.transpose(0, 1) # T x 2B x C
|
||||
sim = torch.matmul(z, z.transpose(1, 2)) # T x 2B x 2B
|
||||
logits = torch.tril(sim, diagonal=-1)[:, :, :-1] # T x 2B x (2B-1)
|
||||
logits += torch.triu(sim, diagonal=1)[:, :, 1:]
|
||||
logits = -F.log_softmax(logits, dim=-1)
|
||||
|
||||
i = torch.arange(B)
|
||||
loss = (logits[:, i, B + i - 1].mean() + logits[:, B + i, i].mean()) / 2
|
||||
return loss
|
||||
|
||||
|
||||
def temporal_contrastive_loss(self, z1, z2):
|
||||
B, T = z1.size(0), z1.size(1)
|
||||
if T == 1:
|
||||
return z1.new_tensor(0.)
|
||||
z = torch.cat([z1, z2], dim=1) # B x 2T x C
|
||||
sim = torch.matmul(z, z.transpose(1, 2)) # B x 2T x 2T
|
||||
logits = torch.tril(sim, diagonal=-1)[:, :, :-1] # B x 2T x (2T-1)
|
||||
logits += torch.triu(sim, diagonal=1)[:, :, 1:]
|
||||
logits = -F.log_softmax(logits, dim=-1)
|
||||
|
||||
t = torch.arange(T)
|
||||
loss = (logits[:, t, T + t - 1].mean() + logits[:, T + t, t].mean()) / 2
|
||||
return loss
|
||||
def forward(self, z1, z2, alpha=0.5, temporal_unit=0):
|
||||
loss = torch.tensor(0., device=self.device) #, device=z1.device
|
||||
d = 0
|
||||
while z1.size(1) > 1:
|
||||
if alpha != 0:
|
||||
loss += alpha * self.instance_contrastive_loss(z1, z2)
|
||||
if d >= temporal_unit:
|
||||
if 1 - alpha != 0:
|
||||
loss += (1 - alpha) * self.temporal_contrastive_loss(z1, z2)
|
||||
d += 1
|
||||
z1 = F.max_pool1d(z1.transpose(1, 2), kernel_size=2).transpose(1, 2)
|
||||
z2 = F.max_pool1d(z2.transpose(1, 2), kernel_size=2).transpose(1, 2)
|
||||
if z1.size(1) == 1:
|
||||
if alpha != 0:
|
||||
loss += alpha * self.instance_contrastive_loss(z1, z2)
|
||||
d += 1
|
||||
return loss / d
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Updated implementation for TF-C -- Xiang Zhang, Jan 16, 2023"""
|
||||
|
||||
import os
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
import argparse
|
||||
from utils import _logger
|
||||
from model import *
|
||||
from dataloader import data_generator
|
||||
from trainer import Trainer
|
||||
|
||||
|
||||
|
||||
|
||||
# Args selections
|
||||
start_time = datetime.now()
|
||||
parser = argparse.ArgumentParser()
|
||||
######################## Model parameters ########################
|
||||
home_dir = os.getcwd()
|
||||
parser.add_argument('--run_description', default='run1', type=str,
|
||||
help='Experiment Description')
|
||||
parser.add_argument('--seed', default=42, type=int, help='seed value')
|
||||
|
||||
# 1. self_supervised pre_train; 2. finetune (itself contains finetune and test)
|
||||
parser.add_argument('--training_mode', default='fine_tune_test', type=str,
|
||||
help='pre_train, fine_tune_test')
|
||||
|
||||
parser.add_argument('--pretrain_dataset', default='SleepEEG', type=str,
|
||||
help='Dataset of choice: SleepEEG, FD_A, HAR, ECG')
|
||||
parser.add_argument('--target_dataset', default='Epilepsy', type=str,
|
||||
help='Dataset of choice: Epilepsy, FD_B, Gesture, EMG')
|
||||
|
||||
parser.add_argument('--logs_save_dir', default='../experiments_logs', type=str,
|
||||
help='saving directory')
|
||||
parser.add_argument('--device', default='cuda', type=str,
|
||||
help='cpu or cuda')
|
||||
parser.add_argument('--home_path', default=home_dir, type=str,
|
||||
help='Project home directory')
|
||||
args, unknown = parser.parse_known_args()
|
||||
|
||||
with_gpu = torch.cuda.is_available()
|
||||
if with_gpu:
|
||||
device = torch.device("cuda")
|
||||
else:
|
||||
device = torch.device("cpu")
|
||||
print('We are using %s now.' %device)
|
||||
|
||||
pretrain_dataset = args.pretrain_dataset
|
||||
targetdata = args.target_dataset
|
||||
experiment_description = str(pretrain_dataset) + '_2_' + str(targetdata)
|
||||
|
||||
|
||||
method = 'TF-C'
|
||||
training_mode = args.training_mode
|
||||
run_description = args.run_description
|
||||
logs_save_dir = args.logs_save_dir
|
||||
os.makedirs(logs_save_dir, exist_ok=True)
|
||||
exec(f'from config_files.{pretrain_dataset}_Configs import Config as Configs')
|
||||
configs = Configs()
|
||||
|
||||
# # ##### fix random seeds for reproducibility ########
|
||||
SEED = args.seed
|
||||
torch.manual_seed(SEED)
|
||||
torch.backends.cudnn.deterministic = False
|
||||
torch.backends.cudnn.benchmark = False
|
||||
np.random.seed(SEED)
|
||||
#####################################################
|
||||
|
||||
experiment_log_dir = os.path.join(logs_save_dir, experiment_description, run_description, training_mode + f"_seed_{SEED}_2layertransformer")
|
||||
# 'experiments_logs/Exp1/run1/train_linear_seed_0'
|
||||
os.makedirs(experiment_log_dir, exist_ok=True)
|
||||
|
||||
# loop through domains
|
||||
counter = 0
|
||||
src_counter = 0
|
||||
|
||||
|
||||
# Logging
|
||||
log_file_name = os.path.join(experiment_log_dir, f"logs_{datetime.now().strftime('%d_%m_%Y_%H_%M_%S')}.log")
|
||||
# 'experiments_logs/Exp1/run1/train_linear_seed_0/logs_14_04_2022_15_13_12.log'
|
||||
logger = _logger(log_file_name)
|
||||
logger.debug("=" * 45)
|
||||
logger.debug(f'Pre-training Dataset: {pretrain_dataset}')
|
||||
logger.debug(f'Target (fine-tuning) Dataset: {targetdata}')
|
||||
logger.debug(f'Method: {method}')
|
||||
logger.debug(f'Mode: {training_mode}')
|
||||
logger.debug("=" * 45)
|
||||
|
||||
# Load datasets
|
||||
sourcedata_path = f"../../datasets/{pretrain_dataset}"
|
||||
targetdata_path = f"../../datasets/{targetdata}"
|
||||
subset = True # if subset= true, use a subset for debugging.
|
||||
train_dl, valid_dl, test_dl = data_generator(sourcedata_path, targetdata_path, configs, training_mode, subset = subset)
|
||||
logger.debug("Data loaded ...")
|
||||
|
||||
# Load Model
|
||||
"""Here are two models, one basemodel, another is temporal contrastive model"""
|
||||
TFC_model = TFC(configs).to(device)
|
||||
classifier = target_classifier(configs).to(device)
|
||||
temporal_contr_model = None
|
||||
|
||||
|
||||
if training_mode == "fine_tune_test":
|
||||
# load saved model of this experiment
|
||||
load_from = os.path.join(os.path.join(logs_save_dir, experiment_description, run_description,
|
||||
f"pre_train_seed_{SEED}_2layertransformer", "saved_models"))
|
||||
print("The loading file path", load_from)
|
||||
chkpoint = torch.load(os.path.join(load_from, "ckp_last.pt"), map_location=device)
|
||||
pretrained_dict = chkpoint["model_state_dict"]
|
||||
TFC_model.load_state_dict(pretrained_dict)
|
||||
|
||||
model_optimizer = torch.optim.Adam(TFC_model.parameters(), lr=configs.lr, betas=(configs.beta1, configs.beta2), weight_decay=3e-4)
|
||||
classifier_optimizer = torch.optim.Adam(classifier.parameters(), lr=configs.lr, betas=(configs.beta1, configs.beta2), weight_decay=3e-4)
|
||||
|
||||
# Trainer
|
||||
Trainer(TFC_model, model_optimizer, classifier, classifier_optimizer, train_dl, valid_dl, test_dl, device,
|
||||
logger, configs, experiment_log_dir, training_mode)
|
||||
|
||||
logger.debug(f"Training time is : {datetime.now()-start_time}")
|
||||
@@ -0,0 +1,66 @@
|
||||
from torch import nn
|
||||
import torch
|
||||
from torch.nn import TransformerEncoder, TransformerEncoderLayer
|
||||
|
||||
"""Two contrastive encoders"""
|
||||
class TFC(nn.Module):
|
||||
# def __init__(self, configs):
|
||||
def __init__(self, TSlength_aligned):
|
||||
super(TFC, self).__init__()
|
||||
|
||||
# TSlength_aligned = configs.TSlength_aligned # original version
|
||||
|
||||
TSlength_aligned = TSlength_aligned # API version, because the config is missing from the git repo published by author: https://github.com/mims-harvard/TFC-pretraining/tree/main
|
||||
|
||||
encoder_layers_t = TransformerEncoderLayer(TSlength_aligned, dim_feedforward=2*TSlength_aligned, nhead=2, )
|
||||
self.transformer_encoder_t = TransformerEncoder(encoder_layers_t, 2)
|
||||
|
||||
self.projector_t = nn.Sequential(
|
||||
nn.Linear(TSlength_aligned, 256),
|
||||
nn.BatchNorm1d(256),
|
||||
nn.ReLU(),
|
||||
nn.Linear(256, 128)
|
||||
)
|
||||
|
||||
encoder_layers_f = TransformerEncoderLayer(TSlength_aligned, dim_feedforward=2*TSlength_aligned,nhead=2,)
|
||||
self.transformer_encoder_f = TransformerEncoder(encoder_layers_f, 2)
|
||||
|
||||
self.projector_f = nn.Sequential(
|
||||
nn.Linear(TSlength_aligned, 256),
|
||||
nn.BatchNorm1d(256),
|
||||
nn.ReLU(),
|
||||
nn.Linear(256, 128)
|
||||
)
|
||||
|
||||
|
||||
def forward(self, x_in_t, x_in_f):
|
||||
"""Use Transformer"""
|
||||
x = self.transformer_encoder_t(x_in_t)
|
||||
h_time = x.reshape(x.shape[0], -1)
|
||||
|
||||
"""Cross-space projector"""
|
||||
z_time = self.projector_t(h_time)
|
||||
|
||||
"""Frequency-based contrastive encoder"""
|
||||
f = self.transformer_encoder_f(x_in_f)
|
||||
h_freq = f.reshape(f.shape[0], -1)
|
||||
|
||||
"""Cross-space projector"""
|
||||
z_freq = self.projector_f(h_freq)
|
||||
|
||||
# return h_time, z_time, h_freq, z_freq
|
||||
return torch.concat((z_time, z_freq), dim=1)
|
||||
|
||||
|
||||
"""Downstream classifier only used in finetuning"""
|
||||
class target_classifier(nn.Module):
|
||||
def __init__(self, configs):
|
||||
super(target_classifier, self).__init__()
|
||||
self.logits = nn.Linear(2*128, 64)
|
||||
self.logits_simple = nn.Linear(64, configs.num_classes_target)
|
||||
|
||||
def forward(self, emb):
|
||||
emb_flat = emb.reshape(emb.shape[0], -1)
|
||||
emb = torch.sigmoid(self.logits(emb_flat))
|
||||
pred = self.logits_simple(emb)
|
||||
return pred
|
||||
@@ -0,0 +1,13 @@
|
||||
This is an updated version of the proposed TF-C model.
|
||||
|
||||
1. Fixed buggs
|
||||
|
||||
2. Replaced the CNN blocks with 2-layer transformer as the encoder architecture
|
||||
|
||||
3. Cleaned the codes and added comments for easy understanding
|
||||
|
||||
4. Uploaded the weights of an exampled pretrained model. The model is pretrained on SleepEEG with only 1280 samples (a small subset that only takes ~1% samples of the whole dataset).
|
||||
|
||||
5. For the downstream classifier, added a KNN classifier as an alternation of the MLP classifier.
|
||||
|
||||
6. Will share some ideas of how to further improve the TFC model.
|
||||
@@ -0,0 +1,309 @@
|
||||
import os
|
||||
import sys
|
||||
sys.path.append("..")
|
||||
|
||||
from loss import *
|
||||
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix, \
|
||||
average_precision_score, accuracy_score, precision_score,f1_score,recall_score
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
from model import *
|
||||
|
||||
def one_hot_encoding(X):
|
||||
X = [int(x) for x in X]
|
||||
n_values = np.max(X) + 1
|
||||
b = np.eye(n_values)[X]
|
||||
return b
|
||||
|
||||
def Trainer(model, model_optimizer, classifier, classifier_optimizer, train_dl, valid_dl, test_dl, device,
|
||||
logger, config, experiment_log_dir, training_mode):
|
||||
# Start training
|
||||
logger.debug("Training started ....")
|
||||
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model_optimizer, 'min')
|
||||
if training_mode == 'pre_train':
|
||||
print('Pretraining on source dataset')
|
||||
for epoch in range(1, config.num_epoch + 1):
|
||||
# Train and validate
|
||||
"""Train. In fine-tuning, this part is also trained???"""
|
||||
train_loss = model_pretrain(model, model_optimizer, criterion, train_dl, config, device, training_mode)
|
||||
logger.debug(f'\nPre-training Epoch : {epoch}', f'Train Loss : {train_loss:.4f}')
|
||||
|
||||
os.makedirs(os.path.join(experiment_log_dir, "saved_models"), exist_ok=True)
|
||||
chkpoint = {'model_state_dict': model.state_dict()}
|
||||
torch.save(chkpoint, os.path.join(experiment_log_dir, "saved_models", f'ckp_last.pt'))
|
||||
print('Pretrained model is stored at folder:{}'.format(experiment_log_dir+'saved_models'+'ckp_last.pt'))
|
||||
|
||||
"""Fine-tuning and Test"""
|
||||
if training_mode != 'pre_train':
|
||||
"""fine-tune"""
|
||||
print('Fine-tune on Fine-tuning set')
|
||||
performance_list = []
|
||||
total_f1 = []
|
||||
KNN_f1 = []
|
||||
global emb_finetune, label_finetune, emb_test, label_test
|
||||
|
||||
for epoch in range(1, config.num_epoch + 1):
|
||||
logger.debug(f'\nEpoch : {epoch}')
|
||||
|
||||
valid_loss, emb_finetune, label_finetune, F1 = model_finetune(model, model_optimizer, valid_dl, config,
|
||||
device, training_mode, classifier=classifier, classifier_optimizer=classifier_optimizer)
|
||||
scheduler.step(valid_loss)
|
||||
|
||||
|
||||
# save best fine-tuning model""
|
||||
global arch
|
||||
arch = 'sleepedf2eplipsy'
|
||||
if len(total_f1) == 0 or F1 > max(total_f1):
|
||||
print('update fine-tuned model')
|
||||
os.makedirs('experiments_logs/finetunemodel/', exist_ok=True)
|
||||
torch.save(model.state_dict(), 'experiments_logs/finetunemodel/' + arch + '_model.pt')
|
||||
torch.save(classifier.state_dict(), 'experiments_logs/finetunemodel/' + arch + '_classifier.pt')
|
||||
total_f1.append(F1)
|
||||
|
||||
# evaluate on the test set
|
||||
"""Testing set"""
|
||||
logger.debug('Test on Target datasts test set')
|
||||
model.load_state_dict(torch.load('experiments_logs/finetunemodel/' + arch + '_model.pt'))
|
||||
classifier.load_state_dict(torch.load('experiments_logs/finetunemodel/' + arch + '_classifier.pt'))
|
||||
test_loss, test_acc, test_auc, test_prc, emb_test, label_test, performance = model_test(model, test_dl, config, device, training_mode,
|
||||
classifier=classifier, classifier_optimizer=classifier_optimizer)
|
||||
performance_list.append(performance)
|
||||
|
||||
"""Use KNN as another classifier; it's an alternation of the MLP classifier in function model_test.
|
||||
Experiments show KNN and MLP may work differently in different settings, so here we provide both. """
|
||||
# train classifier: KNN
|
||||
neigh = KNeighborsClassifier(n_neighbors=5)
|
||||
neigh.fit(emb_finetune, label_finetune)
|
||||
knn_acc_train = neigh.score(emb_finetune, label_finetune)
|
||||
# print('KNN finetune acc:', knn_acc_train)
|
||||
representation_test = emb_test.detach().cpu().numpy()
|
||||
|
||||
knn_result = neigh.predict(representation_test)
|
||||
knn_result_score = neigh.predict_proba(representation_test)
|
||||
one_hot_label_test = one_hot_encoding(label_test)
|
||||
# print(classification_report(label_test, knn_result, digits=4))
|
||||
# print(confusion_matrix(label_test, knn_result))
|
||||
knn_acc = accuracy_score(label_test, knn_result)
|
||||
precision = precision_score(label_test, knn_result, average='macro', )
|
||||
recall = recall_score(label_test, knn_result, average='macro', )
|
||||
F1 = f1_score(label_test, knn_result, average='macro')
|
||||
auc = roc_auc_score(one_hot_label_test, knn_result_score, average="macro", multi_class="ovr")
|
||||
prc = average_precision_score(one_hot_label_test, knn_result_score, average="macro")
|
||||
print('KNN Testing: Acc=%.4f| Precision = %.4f | Recall = %.4f | F1 = %.4f | AUROC= %.4f | AUPRC=%.4f'%
|
||||
(knn_acc, precision, recall, F1, auc, prc))
|
||||
KNN_f1.append(F1)
|
||||
logger.debug("\n################## Best testing performance! #########################")
|
||||
performance_array = np.array(performance_list)
|
||||
best_performance = performance_array[np.argmax(performance_array[:,0], axis=0)]
|
||||
print('Best Testing Performance: Acc=%.4f| Precision = %.4f | Recall = %.4f | F1 = %.4f | AUROC= %.4f '
|
||||
'| AUPRC=%.4f' % (best_performance[0], best_performance[1], best_performance[2], best_performance[3],
|
||||
best_performance[4], best_performance[5]))
|
||||
print('Best KNN F1', max(KNN_f1))
|
||||
|
||||
logger.debug("\n################## Training is Done! #########################")
|
||||
|
||||
def model_pretrain(model, model_optimizer, criterion, train_loader, config, device, training_mode,):
|
||||
total_loss = []
|
||||
model.train()
|
||||
global loss, loss_t, loss_f, l_TF, loss_c, data_test, data_f_test
|
||||
|
||||
# optimizer
|
||||
model_optimizer.zero_grad()
|
||||
|
||||
for batch_idx, (data, labels, aug1, data_f, aug1_f) in enumerate(train_loader):
|
||||
data, labels = data.float().to(device), labels.long().to(device) # data: [128, 1, 178], labels: [128]
|
||||
aug1 = aug1.float().to(device) # aug1 = aug2 : [128, 1, 178]
|
||||
data_f, aug1_f = data_f.float().to(device), aug1_f.float().to(device) # aug1 = aug2 : [128, 1, 178]
|
||||
|
||||
"""Produce embeddings"""
|
||||
h_t, z_t, h_f, z_f = model(data, data_f)
|
||||
h_t_aug, z_t_aug, h_f_aug, z_f_aug = model(aug1, aug1_f)
|
||||
|
||||
"""Compute Pre-train loss"""
|
||||
"""NTXentLoss: normalized temperature-scaled cross entropy loss. From SimCLR"""
|
||||
nt_xent_criterion = NTXentLoss_poly(device, config.batch_size, config.Context_Cont.temperature,
|
||||
config.Context_Cont.use_cosine_similarity) # device, 128, 0.2, True
|
||||
|
||||
loss_t = nt_xent_criterion(h_t, h_t_aug)
|
||||
loss_f = nt_xent_criterion(h_f, h_f_aug)
|
||||
l_TF = nt_xent_criterion(z_t, z_f) # this is the initial version of TF loss
|
||||
|
||||
l_1, l_2, l_3 = nt_xent_criterion(z_t, z_f_aug), nt_xent_criterion(z_t_aug, z_f), nt_xent_criterion(z_t_aug, z_f_aug)
|
||||
loss_c = (1 + l_TF - l_1) + (1 + l_TF - l_2) + (1 + l_TF - l_3)
|
||||
|
||||
lam = 0.2
|
||||
loss = lam*(loss_t + loss_f) + l_TF
|
||||
|
||||
total_loss.append(loss.item())
|
||||
loss.backward()
|
||||
model_optimizer.step()
|
||||
|
||||
print('Pretraining: overall loss:{}, l_t: {}, l_f:{}, l_c:{}'.format(loss, loss_t, loss_f, l_TF))
|
||||
|
||||
ave_loss = torch.tensor(total_loss).mean()
|
||||
|
||||
return ave_loss
|
||||
|
||||
|
||||
def model_finetune(model, model_optimizer, val_dl, config, device, training_mode, classifier=None, classifier_optimizer=None):
|
||||
global labels, pred_numpy, fea_concat_flat
|
||||
model.train()
|
||||
classifier.train()
|
||||
|
||||
total_loss = []
|
||||
total_acc = []
|
||||
total_auc = [] # it should be outside of the loop
|
||||
total_prc = []
|
||||
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
outs = np.array([])
|
||||
trgs = np.array([])
|
||||
feas = np.array([])
|
||||
|
||||
for data, labels, aug1, data_f, aug1_f in val_dl:
|
||||
# print('Fine-tuning: {} of target samples'.format(labels.shape[0]))
|
||||
data, labels = data.float().to(device), labels.long().to(device)
|
||||
data_f = data_f.float().to(device)
|
||||
aug1 = aug1.float().to(device)
|
||||
aug1_f = aug1_f.float().to(device)
|
||||
|
||||
"""if random initialization:"""
|
||||
model_optimizer.zero_grad() # The gradients are zero, but the parameters are still randomly initialized.
|
||||
classifier_optimizer.zero_grad() # the classifier is newly added and randomly initialized
|
||||
|
||||
"""Produce embeddings"""
|
||||
h_t, z_t, h_f, z_f = model(data, data_f)
|
||||
h_t_aug, z_t_aug, h_f_aug, z_f_aug = model(aug1, aug1_f)
|
||||
nt_xent_criterion = NTXentLoss_poly(device, config.target_batch_size, config.Context_Cont.temperature,
|
||||
config.Context_Cont.use_cosine_similarity)
|
||||
loss_t = nt_xent_criterion(h_t, h_t_aug)
|
||||
loss_f = nt_xent_criterion(h_f, h_f_aug)
|
||||
l_TF = nt_xent_criterion(z_t, z_f)
|
||||
|
||||
l_1, l_2, l_3 = nt_xent_criterion(z_t, z_f_aug), nt_xent_criterion(z_t_aug, z_f), \
|
||||
nt_xent_criterion(z_t_aug, z_f_aug)
|
||||
loss_c = (1 + l_TF - l_1) + (1 + l_TF - l_2) + (1 + l_TF - l_3) #
|
||||
|
||||
|
||||
"""Add supervised classifier: 1) it's unique to finetuning. 2) this classifier will also be used in test."""
|
||||
fea_concat = torch.cat((z_t, z_f), dim=1)
|
||||
predictions = classifier(fea_concat)
|
||||
fea_concat_flat = fea_concat.reshape(fea_concat.shape[0], -1)
|
||||
loss_p = criterion(predictions, labels)
|
||||
|
||||
lam = 0.1
|
||||
loss = loss_p + l_TF + lam*(loss_t + loss_f)
|
||||
|
||||
acc_bs = labels.eq(predictions.detach().argmax(dim=1)).float().mean()
|
||||
onehot_label = F.one_hot(labels)
|
||||
pred_numpy = predictions.detach().cpu().numpy()
|
||||
|
||||
try:
|
||||
auc_bs = roc_auc_score(onehot_label.detach().cpu().numpy(), pred_numpy, average="macro", multi_class="ovr" )
|
||||
except:
|
||||
auc_bs = np.float(0)
|
||||
prc_bs = average_precision_score(onehot_label.detach().cpu().numpy(), pred_numpy)
|
||||
|
||||
total_acc.append(acc_bs)
|
||||
total_auc.append(auc_bs)
|
||||
total_prc.append(prc_bs)
|
||||
total_loss.append(loss.item())
|
||||
loss.backward()
|
||||
model_optimizer.step()
|
||||
classifier_optimizer.step()
|
||||
|
||||
if training_mode != "pre_train":
|
||||
pred = predictions.max(1, keepdim=True)[1] # get the index of the max log-probability
|
||||
outs = np.append(outs, pred.cpu().numpy())
|
||||
trgs = np.append(trgs, labels.data.cpu().numpy())
|
||||
feas = np.append(feas, fea_concat_flat.data.cpu().numpy())
|
||||
|
||||
feas = feas.reshape([len(trgs), -1]) # produce the learned embeddings
|
||||
|
||||
labels_numpy = labels.detach().cpu().numpy()
|
||||
pred_numpy = np.argmax(pred_numpy, axis=1)
|
||||
precision = precision_score(labels_numpy, pred_numpy, average='macro', )
|
||||
recall = recall_score(labels_numpy, pred_numpy, average='macro', )
|
||||
F1 = f1_score(labels_numpy, pred_numpy, average='macro', )
|
||||
ave_loss = torch.tensor(total_loss).mean()
|
||||
ave_acc = torch.tensor(total_acc).mean()
|
||||
ave_auc = torch.tensor(total_auc).mean()
|
||||
ave_prc = torch.tensor(total_prc).mean()
|
||||
|
||||
print(' Finetune: loss = %.4f| Acc=%.4f | Precision = %.4f | Recall = %.4f | F1 = %.4f| AUROC=%.4f | AUPRC = %.4f'
|
||||
% (ave_loss, ave_acc*100, precision * 100, recall * 100, F1 * 100, ave_auc * 100, ave_prc *100))
|
||||
|
||||
return ave_loss, feas, trgs, F1
|
||||
|
||||
|
||||
def model_test(model, test_dl, config, device, training_mode, classifier=None, classifier_optimizer=None):
|
||||
model.eval()
|
||||
classifier.eval()
|
||||
|
||||
total_loss = []
|
||||
total_acc = []
|
||||
total_auc = []
|
||||
total_prc = []
|
||||
|
||||
criterion = nn.CrossEntropyLoss() # the loss for downstream classifier
|
||||
outs = np.array([])
|
||||
trgs = np.array([])
|
||||
emb_test_all = []
|
||||
|
||||
with torch.no_grad():
|
||||
labels_numpy_all, pred_numpy_all = np.zeros(1), np.zeros(1)
|
||||
for data, labels, _,data_f, _ in test_dl:
|
||||
data, labels = data.float().to(device), labels.long().to(device)
|
||||
data_f = data_f.float().to(device)
|
||||
|
||||
"""Add supervised classifier: 1) it's unique to finetuning. 2) this classifier will also be used in test"""
|
||||
h_t, z_t, h_f, z_f = model(data, data_f)
|
||||
fea_concat = torch.cat((z_t, z_f), dim=1)
|
||||
predictions_test = classifier(fea_concat)
|
||||
fea_concat_flat = fea_concat.reshape(fea_concat.shape[0], -1)
|
||||
emb_test_all.append(fea_concat_flat)
|
||||
|
||||
loss = criterion(predictions_test, labels)
|
||||
acc_bs = labels.eq(predictions_test.detach().argmax(dim=1)).float().mean()
|
||||
onehot_label = F.one_hot(labels)
|
||||
pred_numpy = predictions_test.detach().cpu().numpy()
|
||||
labels_numpy = labels.detach().cpu().numpy()
|
||||
try:
|
||||
auc_bs = roc_auc_score(onehot_label.detach().cpu().numpy(), pred_numpy,
|
||||
average="macro", multi_class="ovr")
|
||||
except:
|
||||
auc_bs = np.float(0)
|
||||
prc_bs = average_precision_score(onehot_label.detach().cpu().numpy(), pred_numpy, average="macro")
|
||||
pred_numpy = np.argmax(pred_numpy, axis=1)
|
||||
|
||||
total_acc.append(acc_bs)
|
||||
total_auc.append(auc_bs)
|
||||
total_prc.append(prc_bs)
|
||||
|
||||
total_loss.append(loss.item())
|
||||
pred = predictions_test.max(1, keepdim=True)[1] # get the index of the max log-probability
|
||||
outs = np.append(outs, pred.cpu().numpy())
|
||||
trgs = np.append(trgs, labels.data.cpu().numpy())
|
||||
labels_numpy_all = np.concatenate((labels_numpy_all, labels_numpy))
|
||||
pred_numpy_all = np.concatenate((pred_numpy_all, pred_numpy))
|
||||
labels_numpy_all = labels_numpy_all[1:]
|
||||
pred_numpy_all = pred_numpy_all[1:]
|
||||
|
||||
# print('Test classification report', classification_report(labels_numpy_all, pred_numpy_all))
|
||||
# print(confusion_matrix(labels_numpy_all, pred_numpy_all))
|
||||
precision = precision_score(labels_numpy_all, pred_numpy_all, average='macro', )
|
||||
recall = recall_score(labels_numpy_all, pred_numpy_all, average='macro', )
|
||||
F1 = f1_score(labels_numpy_all, pred_numpy_all, average='macro', )
|
||||
acc = accuracy_score(labels_numpy_all, pred_numpy_all, )
|
||||
|
||||
total_loss = torch.tensor(total_loss).mean()
|
||||
total_acc = torch.tensor(total_acc).mean()
|
||||
total_auc = torch.tensor(total_auc).mean()
|
||||
total_prc = torch.tensor(total_prc).mean()
|
||||
|
||||
performance = [acc * 100, precision * 100, recall * 100, F1 * 100, total_auc * 100, total_prc * 100]
|
||||
print('MLP Testing: Acc=%.4f| Precision = %.4f | Recall = %.4f | F1 = %.4f | AUROC= %.4f | AUPRC=%.4f'
|
||||
% (acc*100, precision * 100, recall * 100, F1 * 100, total_auc*100, total_prc*100))
|
||||
emb_test_all = torch.concat(tuple(emb_test_all))
|
||||
return total_loss, total_acc, total_auc, total_prc, emb_test_all, trgs, performance
|
||||
@@ -0,0 +1,95 @@
|
||||
"""The utils are modified based on TS-TCC paper. -- Xiang Zhang, Jan 16, 2023"""
|
||||
|
||||
import torch
|
||||
import random
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
from sklearn.metrics import classification_report, cohen_kappa_score, confusion_matrix, accuracy_score
|
||||
from shutil import copy
|
||||
|
||||
def set_requires_grad(model, dict_, requires_grad=True):
|
||||
for param in model.named_parameters():
|
||||
if param[0] in dict_:
|
||||
param[1].requires_grad = requires_grad
|
||||
|
||||
|
||||
def fix_randomness(SEED):
|
||||
random.seed(SEED)
|
||||
np.random.seed(SEED)
|
||||
torch.manual_seed(SEED)
|
||||
torch.cuda.manual_seed(SEED)
|
||||
torch.backends.cudnn.deterministic = True
|
||||
|
||||
|
||||
def epoch_time(start_time, end_time):
|
||||
elapsed_time = end_time - start_time
|
||||
elapsed_mins = int(elapsed_time / 60)
|
||||
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
|
||||
return elapsed_mins, elapsed_secs
|
||||
|
||||
|
||||
def _calc_metrics(pred_labels, true_labels, log_dir, home_path):
|
||||
pred_labels = np.array(pred_labels).astype(int)
|
||||
true_labels = np.array(true_labels).astype(int)
|
||||
|
||||
# save targets
|
||||
labels_save_path = os.path.join(log_dir, "labels")
|
||||
os.makedirs(labels_save_path, exist_ok=True)
|
||||
np.save(os.path.join(labels_save_path, "predicted_labels.npy"), pred_labels)
|
||||
np.save(os.path.join(labels_save_path, "true_labels.npy"), true_labels)
|
||||
|
||||
r = classification_report(true_labels, pred_labels, digits=6, output_dict=True)
|
||||
cm = confusion_matrix(true_labels, pred_labels)
|
||||
df = pd.DataFrame(r)
|
||||
df["cohen"] = cohen_kappa_score(true_labels, pred_labels)
|
||||
df["accuracy"] = accuracy_score(true_labels, pred_labels)
|
||||
df = df * 100
|
||||
|
||||
# save classification report
|
||||
exp_name = os.path.split(os.path.dirname(log_dir))[-1]
|
||||
training_mode = os.path.basename(log_dir)
|
||||
file_name = f"{exp_name}_{training_mode}_classification_report.xlsx"
|
||||
report_Save_path = os.path.join(home_path, log_dir, file_name)
|
||||
df.to_excel(report_Save_path)
|
||||
|
||||
# save confusion matrix
|
||||
cm_file_name = f"{exp_name}_{training_mode}_confusion_matrix.torch"
|
||||
cm_Save_path = os.path.join(home_path, log_dir, cm_file_name)
|
||||
torch.save(cm, cm_Save_path)
|
||||
|
||||
|
||||
def _logger(logger_name, level=logging.DEBUG):
|
||||
"""
|
||||
Method to return a custom logger with the given name and level
|
||||
"""
|
||||
logger = logging.getLogger(logger_name)
|
||||
logger.setLevel(level)
|
||||
# format_string = ("%(asctime)s — %(name)s — %(levelname)s — %(funcName)s:"
|
||||
# "%(lineno)d — %(message)s")
|
||||
format_string = "%(message)s"
|
||||
log_format = logging.Formatter(format_string)
|
||||
# Creating and adding the console handler
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setFormatter(log_format)
|
||||
logger.addHandler(console_handler)
|
||||
# Creating and adding the file handler
|
||||
file_handler = logging.FileHandler(logger_name, mode='a')
|
||||
file_handler.setFormatter(log_format)
|
||||
logger.addHandler(file_handler)
|
||||
return logger
|
||||
|
||||
def copy_Files(destination, data_type):
|
||||
# destination: 'experiments_logs/Exp1/run1'
|
||||
destination_dir = os.path.join(destination, "model_files")
|
||||
os.makedirs(destination_dir, exist_ok=True)
|
||||
copy("main.py", os.path.join(destination_dir, "main.py"))
|
||||
copy("trainerfun/trainer.py", os.path.join(destination_dir, "trainerfun.py"))
|
||||
copy(f"config_files/{data_type}_Configs.py", os.path.join(destination_dir, f"{data_type}_Configs.py"))
|
||||
copy("dataloader/augmentations.py", os.path.join(destination_dir, "augmentations.py"))
|
||||
copy("dataloader/dataloader.py", os.path.join(destination_dir, "dataloader.py"))
|
||||
copy(f"models/model.py", os.path.join(destination_dir, f"model.py"))
|
||||
copy("models/loss.py", os.path.join(destination_dir, "loss.py"))
|
||||
copy("models/TC.py", os.path.join(destination_dir, "TC.py"))
|
||||
@@ -0,0 +1,56 @@
|
||||
class Config(object):
|
||||
def __init__(self):
|
||||
# model configs
|
||||
self.input_channels = 1
|
||||
self.kernel_size = 8
|
||||
self.stride = 1
|
||||
self.final_out_channels = 128
|
||||
|
||||
self.num_classes = 4
|
||||
self.dropout = 0.35
|
||||
self.features_len = 18
|
||||
|
||||
# training configs
|
||||
self.num_epoch = 100# 40
|
||||
|
||||
# optimizer parameters
|
||||
self.beta1 = 0.9
|
||||
self.beta2 = 0.99
|
||||
self.lr = 3e-6 # 3e-4
|
||||
|
||||
# data parameters
|
||||
self.drop_last = True
|
||||
self.batch_size = 128
|
||||
|
||||
self.Context_Cont = Context_Cont_configs()
|
||||
self.TC = TC()
|
||||
self.augmentation = augmentations()
|
||||
|
||||
"""New hyperparameters"""
|
||||
self.TSlength_aligned = 1500
|
||||
self.lr_f = self.lr
|
||||
self.target_batch_size = 41# 82 # 41
|
||||
self.increased_dim = 1
|
||||
self.final_out_channels = 128
|
||||
self.num_classes_target = 3
|
||||
self.features_len_f = self.features_len
|
||||
self.CNNoutput_channel = 190 # 751#
|
||||
|
||||
|
||||
class augmentations(object):
|
||||
def __init__(self):
|
||||
self.jitter_scale_ratio = 1.1
|
||||
self.jitter_ratio = 0.8
|
||||
self.max_seg = 8
|
||||
|
||||
|
||||
class Context_Cont_configs(object):
|
||||
def __init__(self):
|
||||
self.temperature = 0.2
|
||||
self.use_cosine_similarity = True
|
||||
|
||||
|
||||
class TC(object):
|
||||
def __init__(self):
|
||||
self.hidden_dim = 100
|
||||
self.timesteps = 6
|
||||
@@ -0,0 +1,51 @@
|
||||
class Config(object):
|
||||
def __init__(self):
|
||||
# model configs
|
||||
self.input_channels = 1
|
||||
self.kernel_size = 8
|
||||
self.stride = 1
|
||||
self.final_out_channels = 32 #128
|
||||
|
||||
self.num_classes = 2
|
||||
self.num_classes_target = 3
|
||||
self.dropout = 0.35
|
||||
self.features_len = 24
|
||||
self.features_len_f = 24 # 13 #self.features_len # the output results in time domain
|
||||
|
||||
# training configs
|
||||
self.num_epoch = 40 # 40
|
||||
|
||||
# optimizer parameters
|
||||
self.beta1 = 0.9
|
||||
self.beta2 = 0.99
|
||||
self.lr = 3e-4 # original lr: 3e-4
|
||||
self.lr_f = 3e-4
|
||||
|
||||
# data parameters
|
||||
self.drop_last = True
|
||||
self.batch_size = 32 #64 # 128
|
||||
self.target_batch_size = 16 # the size of target dataset (the # of samples used to fine-tune).
|
||||
|
||||
self.Context_Cont = Context_Cont_configs()
|
||||
self.TC = TC()
|
||||
self.augmentation = augmentations()
|
||||
|
||||
|
||||
class augmentations(object):
|
||||
def __init__(self):
|
||||
self.jitter_scale_ratio = 0.001
|
||||
self.jitter_ratio = 0.001
|
||||
self.max_seg = 5
|
||||
|
||||
|
||||
class Context_Cont_configs(object):
|
||||
def __init__(self):
|
||||
self.temperature = 0.2
|
||||
self.use_cosine_similarity = True
|
||||
self.use_cosine_similarity_f = True
|
||||
|
||||
|
||||
class TC(object):
|
||||
def __init__(self):
|
||||
self.hidden_dim = 100
|
||||
self.timesteps = 10
|
||||
@@ -0,0 +1,62 @@
|
||||
|
||||
class Config(object):
|
||||
def __init__(self):
|
||||
# model configs
|
||||
self.input_channels = 1
|
||||
self.kernel_size = 32
|
||||
self.stride = 4
|
||||
self.final_out_channels = 128
|
||||
self.features_len = 162
|
||||
|
||||
self.num_classes = 3
|
||||
self.dropout = 0.35
|
||||
|
||||
# for noisy labels experiment
|
||||
self.corruption_prob = 0.3
|
||||
|
||||
|
||||
|
||||
|
||||
# training configs
|
||||
self.num_epoch = 40
|
||||
self.batch_size = 64
|
||||
|
||||
# optimizer parameters
|
||||
self.optimizer = 'adam'
|
||||
self.beta1 = 0.9
|
||||
self.beta2 = 0.99
|
||||
self.lr = 3e-4
|
||||
|
||||
# data parameters
|
||||
self.drop_last = True
|
||||
|
||||
self.Context_Cont = Context_Cont_configs()
|
||||
self.TC = TC()
|
||||
self.augmentation = augmentations()
|
||||
|
||||
"""New hyperparameters"""
|
||||
self.TSlength_aligned = 5120
|
||||
self.lr_f = self.lr
|
||||
self.target_batch_size = 60
|
||||
self.increased_dim = 1
|
||||
self.final_out_channels = 128
|
||||
self.num_classes_target = 3
|
||||
self.features_len_f = self.features_len
|
||||
self.CNNoutput_channel = 162
|
||||
|
||||
class augmentations(object):
|
||||
def __init__(self):
|
||||
self.jitter_scale_ratio = 2
|
||||
self.jitter_ratio = 0.1
|
||||
self.max_seg = 5
|
||||
|
||||
|
||||
class Context_Cont_configs(object):
|
||||
def __init__(self):
|
||||
self.temperature = 0.2
|
||||
self.use_cosine_similarity = True
|
||||
|
||||
class TC(object):
|
||||
def __init__(self):
|
||||
self.hidden_dim = 64
|
||||
self.timesteps = 50
|
||||
@@ -0,0 +1,56 @@
|
||||
class Config(object):
|
||||
def __init__(self):
|
||||
# model configs
|
||||
self.input_channels = 1# 9
|
||||
self.kernel_size = 8
|
||||
self.stride = 1
|
||||
self.final_out_channels = 128
|
||||
|
||||
self.num_classes = 6
|
||||
self.dropout = 0.35
|
||||
self.features_len = 18
|
||||
|
||||
# training configs
|
||||
self.num_epoch = 40
|
||||
|
||||
# optimizer parameters
|
||||
self.beta1 = 0.9
|
||||
self.beta2 = 0.99
|
||||
self.lr = 3e-4
|
||||
|
||||
# data parameters
|
||||
self.drop_last = True
|
||||
self.batch_size = 128
|
||||
|
||||
self.Context_Cont = Context_Cont_configs()
|
||||
self.TC = TC()
|
||||
self.augmentation = augmentations()
|
||||
|
||||
"""New hyperparameters"""
|
||||
self.TSlength_aligned = 206
|
||||
self.lr_f = self.lr
|
||||
self.target_batch_size = 42# 84
|
||||
self.increased_dim = 1
|
||||
self.final_out_channels = 128
|
||||
self.num_classes_target = 2
|
||||
self.features_len_f = self.features_len
|
||||
self.CNNoutput_channel = 28# 104
|
||||
|
||||
|
||||
class augmentations(object):
|
||||
def __init__(self):
|
||||
self.jitter_scale_ratio = 1.1
|
||||
self.jitter_ratio = 0.8
|
||||
self.max_seg = 8
|
||||
|
||||
|
||||
class Context_Cont_configs(object):
|
||||
def __init__(self):
|
||||
self.temperature = 0.2
|
||||
self.use_cosine_similarity = True
|
||||
|
||||
|
||||
class TC(object):
|
||||
def __init__(self):
|
||||
self.hidden_dim = 100
|
||||
self.timesteps = 6
|
||||
@@ -0,0 +1,59 @@
|
||||
|
||||
class Config(object):
|
||||
def __init__(self):
|
||||
# model configs
|
||||
self.input_channels = 1
|
||||
self.increased_dim = 1
|
||||
self.final_out_channels = 128
|
||||
self.num_classes = 5
|
||||
self.num_classes_target = 2
|
||||
self.dropout = 0.35
|
||||
|
||||
|
||||
self.kernel_size = 25
|
||||
self.stride = 3
|
||||
self.features_len = 127
|
||||
self.features_len_f = self.features_len
|
||||
|
||||
self.TSlength_aligned = 178
|
||||
|
||||
self.CNNoutput_channel = 10 # 90 # 10 for Epilepsy model
|
||||
|
||||
# training configs
|
||||
self.num_epoch = 40
|
||||
|
||||
|
||||
# optimizer parameters
|
||||
self.optimizer = 'adam'
|
||||
self.beta1 = 0.9
|
||||
self.beta2 = 0.99
|
||||
self.lr = 3e-4 # 3e-4
|
||||
self.lr_f = self.lr
|
||||
|
||||
# data parameters
|
||||
self.drop_last = True
|
||||
self.batch_size = 128
|
||||
"""For Epilepsy, the target batchsize is 60"""
|
||||
self.target_batch_size = 60 # the size of target dataset (the # of samples used to fine-tune).
|
||||
|
||||
self.Context_Cont = Context_Cont_configs()
|
||||
self.TC = TC()
|
||||
self.augmentation = augmentations()
|
||||
|
||||
class augmentations(object):
|
||||
def __init__(self):
|
||||
self.jitter_scale_ratio = 1.5
|
||||
self.jitter_ratio = 2
|
||||
self.max_seg = 12
|
||||
|
||||
|
||||
class Context_Cont_configs(object):
|
||||
def __init__(self):
|
||||
self.temperature = 0.2
|
||||
self.use_cosine_similarity = True
|
||||
|
||||
|
||||
class TC(object):
|
||||
def __init__(self):
|
||||
self.hidden_dim = 64
|
||||
self.timesteps = 50
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
from .downstream_pipeline.prepare_embeds import *
|
||||
from .downstream_pipeline.linear_prob_main import *
|
||||
import gc
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# reset print format
|
||||
import sys
|
||||
sys.stdout = sys.__stdout__
|
||||
|
||||
# get command line arguments
|
||||
if __name__ == '__main__':
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
|
||||
save_remark = args.remark if len(args.remark) > 0 else args.model_name
|
||||
save_fname = "{}_results_all.pkl".format(save_remark)
|
||||
save_name = "../data/results/downstream_results/{}".format(save_fname) # full path
|
||||
pod_name = "physio-model-5d98486f85-ngv5t"
|
||||
|
||||
DATA_GROUPS = {
|
||||
0: [ # all downstream
|
||||
"wearable_downstream/PPG_HTN",
|
||||
"wearable_downstream/PPG_DM",
|
||||
"wearable_downstream/PPG_CVA",
|
||||
"wearable_downstream/PPG_CVD",
|
||||
"wearable_downstream/non_invasive_bp",
|
||||
"wearable_downstream/ppg_hgb",
|
||||
"wearable_downstream/indian-fPCG",
|
||||
"wearable_downstream/ecg_heart_cat", # **
|
||||
"wearable_downstream/emg-tfc",
|
||||
"wearable_downstream/gameemo", # **
|
||||
"wearable_downstream/Epilepsy",
|
||||
"wearable_downstream/drive_fatigue", # *
|
||||
"wearable_downstream/uci_har", # ***
|
||||
"wearable_downstream/wesad", # ***
|
||||
],
|
||||
1: [ # if test a subset of the tasks, specified them here, e.g.:
|
||||
"wearable_downstream/ecg",
|
||||
]
|
||||
}
|
||||
|
||||
# main iteration
|
||||
for dataset in tqdm(DATA_GROUPS[args.group]):
|
||||
|
||||
# manually update the dataset's name
|
||||
args.ds_name = dataset
|
||||
|
||||
# prepare embedding (comment out if embedding was ready)
|
||||
embed_root = '{}/{}/{}_wav_embed'.format(args.data_path, args.ds_name, save_remark)
|
||||
sample_root = '{}/{}/sample_for_downstream'.format(args.data_path, args.ds_name)
|
||||
all_sample_fns = os.listdir(sample_root)
|
||||
|
||||
# check if embedding ready
|
||||
embedding_ready = True
|
||||
if not os.path.isdir(embed_root):
|
||||
embedding_ready = False
|
||||
else:
|
||||
all_fns = sorted(os.listdir(embed_root))
|
||||
if abs(len(all_fns) - len(all_sample_fns)) > 1:
|
||||
embedding_ready = False
|
||||
|
||||
# prepare embed if not ready
|
||||
if args.prepare_embed or not embedding_ready:
|
||||
print("Preparing Embedding for {} ...".format(args.ds_name))
|
||||
root_prefix = "" if args.data_path == "data" else "../"
|
||||
audio_embedding_prepare(model_name=args.model_name, data_rootpath=dataset, root_prefix=root_prefix, remark=save_remark, args=args)
|
||||
# combine_normwear_ast(data_rootpath=dataset, root_prefix=root_prefix)
|
||||
|
||||
# fetch all file names
|
||||
all_fns = sorted(os.listdir(embed_root))
|
||||
|
||||
# linear prob
|
||||
# curr_res = main(args)
|
||||
curr_res = launch_linear_prob(args, embed_root, all_fns)
|
||||
|
||||
# save the results
|
||||
# fetch previous results
|
||||
all_results = dict()
|
||||
if Path(save_name).is_file():
|
||||
try:
|
||||
with open(save_name, 'rb') as f:
|
||||
all_results = pickle.load(f)
|
||||
except:
|
||||
all_results = dict()
|
||||
|
||||
all_results[dataset] = curr_res
|
||||
|
||||
# write new results
|
||||
with open(save_name, 'wb+') as f:
|
||||
pickle.dump(all_results, f)
|
||||
|
||||
# break
|
||||
# cleanup
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
# log for file transfer
|
||||
# print("kubectl cp {}:data/results/downstream_results/{} data/results/{}".format(pod_name, save_fname, save_fname))
|
||||
print("Evaluation process complete.")
|
||||
|
||||
# python3 -m downstream_all --model_name healthmae --num_runs 2 --group 2 --prepare_embed 1 --batch_size 256
|
||||
# CUDA_VISIBLE_DEVICES=1 python3 -m downstream_all --model_name healthmae --num_runs 2 --group 2 --prepare_embed 1 --batch_size 256
|
||||
|
||||
# kubectl cp physio-model-zs-589f54b445-b6vrs:data/results/downstream_results/stats_results_all.pkl data/results/stats_results_all.pkl
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,485 @@
|
||||
"""
|
||||
References:
|
||||
ConvTran
|
||||
|
||||
Collection of functions which enable the evaluation of a classifier's performance,
|
||||
by showing confusion matrix, accuracy, recall, precision etc.
|
||||
"""
|
||||
# analysis.py
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
from sklearn import metrics
|
||||
from tabulate import tabulate
|
||||
import math
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def acc_top_k(predictions, y_true):
|
||||
"""Accuracy when allowing for correct class being in the top k predictions.
|
||||
|
||||
Arguments:
|
||||
predictions: (N_samples, k) array of top class indices (pre-sorted class indices based on score) per sample
|
||||
y_true: N_samples 1D-array of ground truth labels (integer indices)
|
||||
Returns:
|
||||
length k 1D-array of accuracy when allowing for correct class being in top 1, 2, ... k predictions"""
|
||||
|
||||
y_true = y_true[:, np.newaxis]
|
||||
|
||||
# Create upper triangular matrix of ones, to be used in construction of V
|
||||
building_blocks = np.zeros((predictions.shape[1], predictions.shape[1]))
|
||||
building_blocks[np.triu_indices(predictions.shape[1])] = 1
|
||||
|
||||
# A matrix of the same shape as predictions. For each sample, the index corresponding
|
||||
# to a correct prediction is 1, as well as all following indices.
|
||||
# Example: y_true = [1,0], predictions = [[1 5 4],[2 0 3]]. Then: V = [[1 1 1],[0 1 1]]
|
||||
V = np.zeros_like(predictions, dtype=int) # validity matrix
|
||||
sample_ind, rank_ind = np.where(predictions == y_true)
|
||||
|
||||
V[sample_ind, :] = building_blocks[rank_ind, :]
|
||||
|
||||
return np.mean(V, axis=0)
|
||||
|
||||
|
||||
def accuracy(y_pred, y_true, excluded_labels=None):
|
||||
"""A simple accuracy calculator, which can ignore labels specified in a list"""
|
||||
|
||||
if excluded_labels is None:
|
||||
return np.mean(y_pred == y_true)
|
||||
else:
|
||||
included = (y_pred != excluded_labels[0]) & (y_true != excluded_labels[0])
|
||||
# The following extra check (rather than initializing with an array of ones)
|
||||
# is done because a single excluded label is the most common case
|
||||
if len(excluded_labels) > 1:
|
||||
for label in excluded_labels[1:]:
|
||||
included &= (y_pred != label) & (y_true != label)
|
||||
|
||||
return np.mean(y_pred[included] == y_true[included])
|
||||
|
||||
|
||||
def precision(y_true, y_pred, label):
|
||||
"""Returns precision for the specified class index"""
|
||||
|
||||
predicted_in_C = (y_pred == label)
|
||||
num_pred_in_C = np.sum(predicted_in_C)
|
||||
if num_pred_in_C == 0:
|
||||
return 0
|
||||
return np.sum(y_true[predicted_in_C] == label) / num_pred_in_C
|
||||
|
||||
|
||||
def recall(y_true, y_pred, label):
|
||||
"""Returns recall for the specified class index"""
|
||||
|
||||
truly_in_C = (y_true == label)
|
||||
num_truly_in_C = np.sum(truly_in_C)
|
||||
if num_truly_in_C == 0:
|
||||
return 0 # or NaN?
|
||||
return np.sum(y_pred[truly_in_C] == label) / num_truly_in_C
|
||||
|
||||
|
||||
def limiter(metric_functions, y_true, y_pred, y_scores, score_thr, label):
|
||||
"""Wraps a list of metric functions, i.e precison or recall, by ingoring predictions under the
|
||||
specified threshold for a specific class.
|
||||
"""
|
||||
|
||||
ltd_pred = np.copy(y_pred)
|
||||
ltd_pred[(ltd_pred == label) & (y_scores < score_thr)] = -1
|
||||
|
||||
output = [func(y_true, ltd_pred, label) for func in metric_functions]
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def prec_rec_parametrized_by_thr(y_true, y_pred, y_scores, label, Npoints, min_score=None, max_score=None):
|
||||
"""Returns an array showing for a specified class of interest, how precision and recall change as a function of
|
||||
the score threshold (parameter).
|
||||
|
||||
Input:
|
||||
y_true: 1D array of true labels (class indices)
|
||||
y_pred: 1D array of predicted labels (class indices)
|
||||
y_scores: 1D array of scores corresponding to predictions in y_pred
|
||||
label: class label of interest
|
||||
Npoints: number of score threshold points. Defines "resolution" of the parameter (score threshold)
|
||||
min_score, max_score: if specified, they impose lower and upper bound limits for the parameter (score thr.)
|
||||
Output:
|
||||
prec_rec: ndarray of shape (Npoints, 2), containing a precision (column 0) and recall (column 1) value for each
|
||||
score threshold value
|
||||
"""
|
||||
|
||||
if (min_score is None) or (max_score is None):
|
||||
predicted_in_C = (y_pred == label)
|
||||
min_score = 0.99 * np.amin(y_scores[predicted_in_C]) # guarantees that all predictions are kept
|
||||
max_score = 1.01 * np.amax(y_scores[predicted_in_C]) # guarantees that no prediction is kept
|
||||
|
||||
grid = np.linspace(min_score, max_score, Npoints)
|
||||
|
||||
measure = lambda x: limiter([precision, recall], y_true, y_pred, y_scores, x, label)
|
||||
|
||||
return np.array(map(measure, grid)), grid
|
||||
|
||||
'''
|
||||
def plot_prec_vs_rec(score_grid, rec, prec, prec_requirement=None, thr_opt=None, title=None, show=True, save_as=None):
|
||||
"""Plots a figure depicting precision and recall as a function of the score threshold.
|
||||
Optionally also depicts an imposed precision requirement and a chosen score threshold value."""
|
||||
|
||||
if not (thr_opt is None):
|
||||
thr_opt = thr_opt if not (math.isinf(thr_opt)) else None
|
||||
|
||||
plt.figure()
|
||||
if title:
|
||||
plt.suptitle(title)
|
||||
|
||||
# Recall and Precision vs. Score Threshold
|
||||
plt.subplot(211)
|
||||
l_rec, = plt.plot(score_grid, rec, '.-')
|
||||
|
||||
plt.hold(True)
|
||||
l_prec, = plt.plot(score_grid, prec, 'g.-')
|
||||
plt.ylim((0, 1.01))
|
||||
plt.xlabel('score threshold')
|
||||
|
||||
legend_lines = [l_rec, l_prec]
|
||||
legend_labels = ['recall', 'precision']
|
||||
|
||||
if prec_requirement:
|
||||
l_prec_req = plt.axhline(prec_requirement, color='r', linestyle='--')
|
||||
legend_lines.append(l_prec_req)
|
||||
legend_labels.append('prec. req.')
|
||||
|
||||
if not (thr_opt is None):
|
||||
l_score_thr = plt.axvline(thr_opt, color='r')
|
||||
legend_lines.append(l_score_thr)
|
||||
legend_labels.append('opt. thr.')
|
||||
|
||||
plt.legend(legend_lines, legend_labels, loc='lower right', fontsize=10)
|
||||
|
||||
# Recall vs. Precision
|
||||
plt.subplot(212)
|
||||
plt.plot(prec, rec, '.-')
|
||||
|
||||
plt.ylim((0, 1.01))
|
||||
plt.xlim((0, 1.01))
|
||||
plt.ylabel('recall')
|
||||
plt.xlabel('precision')
|
||||
|
||||
if prec_requirement:
|
||||
l_prec_req = plt.axvline(prec_requirement, color='r', linestyle='--')
|
||||
plt.legend([l_prec_req], ['precision req.'], loc='lower left', fontsize=10)
|
||||
|
||||
if save_as:
|
||||
plt.savefig(save_as, bbox_inches='tight', format='pdf')
|
||||
|
||||
if show:
|
||||
plt.tight_layout()
|
||||
plt.show(block=False)
|
||||
|
||||
|
||||
def plot_confusion_matrix(ConfMat, label_strings=None, title='Confusion matrix', cmap=plt.cm.get_cmap('Blues')):
|
||||
"""Plot confusion matrix in a separate window"""
|
||||
plt.imshow(ConfMat, interpolation='nearest', cmap=cmap)
|
||||
plt.title(title)
|
||||
plt.colorbar()
|
||||
if label_strings:
|
||||
tick_marks = np.arange(len(label_strings))
|
||||
plt.xticks(tick_marks, label_strings, rotation=90)
|
||||
plt.yticks(tick_marks, label_strings)
|
||||
plt.tight_layout()
|
||||
plt.ylabel('True label')
|
||||
plt.xlabel('Predicted label')
|
||||
|
||||
'''
|
||||
def print_confusion_matrix(ConfMat, label_strings=None, title='Confusion matrix'):
|
||||
"""Print confusion matrix as text to terminal"""
|
||||
|
||||
if label_strings is None:
|
||||
label_strings = ConfMat.shape[0] * ['']
|
||||
|
||||
print(title)
|
||||
print(len(title) * '-')
|
||||
# Make printable matrix:
|
||||
print_mat = []
|
||||
for i, row in enumerate(ConfMat):
|
||||
print_mat.append([label_strings[i]] + list(row))
|
||||
print(tabulate(print_mat, headers=['True\Pred'] + label_strings, tablefmt='orgtbl'))
|
||||
|
||||
|
||||
|
||||
class Analyzer(object):
|
||||
|
||||
def __init__(self, maxcharlength=35, plot=False, print_conf_mat=False, output_filepath=None):
|
||||
|
||||
self.maxcharlength = maxcharlength
|
||||
self.plot = plot
|
||||
self.print_conf_mat = print_conf_mat
|
||||
|
||||
# create logger
|
||||
self.logID = str(
|
||||
datetime.now()) # this is to enable individual logging configuration between different instances
|
||||
self.logger = logging.getLogger(self.logID)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
formatter = logging.Formatter('%(message)s')
|
||||
|
||||
# create console handler
|
||||
ch = logging.StreamHandler(sys.stdout)
|
||||
ch.setLevel(logging.INFO)
|
||||
ch.setFormatter(formatter)
|
||||
self.logger.addHandler(ch)
|
||||
|
||||
if output_filepath:
|
||||
# create file handler
|
||||
fh = logging.FileHandler(output_filepath)
|
||||
fh.setLevel(logging.INFO)
|
||||
fh.setFormatter(formatter)
|
||||
self.logger.addHandler(fh)
|
||||
|
||||
def show_acc_top_k_improvement(self, y_pred, y_true, k=5, inp='scores'):
|
||||
"""
|
||||
Show how accuracy improves when considering the event of the correct label being among the top k predictions as a successful prediction
|
||||
Arguments:
|
||||
k: integer k mentioned above
|
||||
inp: string, one of 'scores' or 'indices', defining assumptions for `y_pred`, see below
|
||||
y_pred: If inp is 'indices', then this is a (N_samples, k) array of top class indices (pre-sorted class indices based on score) per sample
|
||||
If inp is 'scores', then this is assummed to be a (N_samples, C) array of class scores per sample, where C is the number of classes
|
||||
y_true: (N_samples,) 1D numpy array of ground truth labels (integer indices)
|
||||
"""
|
||||
|
||||
print('How accuracy improves when allowing correct result being in the top 1, 2, ..., k predictions:\n')
|
||||
|
||||
if inp == 'scores':
|
||||
predictions = np.argsort(y_pred, axis=1)[:, ::-1] # sort in descending order
|
||||
else:
|
||||
predictions = y_pred
|
||||
|
||||
predictions = predictions[:, :min(k, predictions.shape[1])] # take top k
|
||||
|
||||
accuracy_per_rank = acc_top_k(predictions, y_true)
|
||||
|
||||
row1 = ['k'] + range(1, len(accuracy_per_rank) + 1)
|
||||
row2 = ['Accuracy'] + list(accuracy_per_rank)
|
||||
print(tabulate([row1, row2], tablefmt='orgtbl'))
|
||||
|
||||
if self.plot:
|
||||
from matplotlib.ticker import MaxNLocator
|
||||
|
||||
ax = plt.figure().gca()
|
||||
plt.plot(np.arange(1, k + 1, dtype=int), accuracy_per_rank, '.-')
|
||||
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
|
||||
plt.xlabel('Number of allowed predictions (k)')
|
||||
plt.ylabel('Cumulative accuracy\n(prob. of correct result being in top k pred.)')
|
||||
plt.title('Cumulative Accuracy vs Number of allowed predictions')
|
||||
|
||||
plt.show(block=False)
|
||||
|
||||
return accuracy_per_rank
|
||||
|
||||
def generate_classification_report(self, digits=3, number_of_thieves=2, maxcharlength=35):
|
||||
"""
|
||||
Returns a string of a report for given metric arrays (array length equals the number of classes).
|
||||
Called internally by `analyze_classification`.
|
||||
digits: number of digits after . for displaying results
|
||||
number_of_thieves: number of biggest thieves to report
|
||||
maxcharlength: max. number of characters to use when displaying thief names
|
||||
"""
|
||||
|
||||
relative_freq = self.support / np.sum(self.support) # relative frequencies of each class in the true lables
|
||||
sorted_class_indices = np.argsort(relative_freq)[
|
||||
::-1] # sort by "importance" of classes (i.e. occurance frequency)
|
||||
|
||||
last_line_heading = 'avg / total'
|
||||
|
||||
width = max(len(cn) for cn in self.existing_class_names)
|
||||
width = max(width, len(last_line_heading), digits)
|
||||
|
||||
headers = ["precision", "recall", "f1-score", "rel. freq.", "abs. freq.", "biggest thieves"]
|
||||
fmt = '%% %ds' % width # first column: class name
|
||||
fmt += ' '
|
||||
fmt += ' '.join(['% 10s' for _ in headers[:-1]])
|
||||
fmt += '|\t % 5s'
|
||||
fmt += '\n'
|
||||
|
||||
headers = [""] + headers
|
||||
report = fmt % tuple(headers)
|
||||
report += '\n'
|
||||
|
||||
for i in sorted_class_indices:
|
||||
values = [self.existing_class_names[i]]
|
||||
for v in (self.precision[i], self.recall[i], self.f1[i],
|
||||
relative_freq[i]): # v is NOT a tuple, just goes through this list 1 el. at a time
|
||||
values += ["{0:0.{1}f}".format(v, digits)]
|
||||
values += ["{}".format(self.support[i])]
|
||||
thieves = np.argsort(self.ConfMatrix_normalized_row[i, :])[::-1][
|
||||
:number_of_thieves + 1] # other class indices "stealing" from class. May still contain self
|
||||
thieves = thieves[thieves != i] # exclude self at this point
|
||||
steal_ratio = self.ConfMatrix_normalized_row[i, thieves]
|
||||
thieves_names = [
|
||||
self.existing_class_names[thief][:min(maxcharlength, len(self.existing_class_names[thief]))] for thief
|
||||
in thieves] # a little inefficient but inconsequential
|
||||
string_about_stealing = ""
|
||||
for j in range(len(thieves)):
|
||||
string_about_stealing += "{0}: {1:.3f},\t".format(thieves_names[j], steal_ratio[j])
|
||||
values += [string_about_stealing]
|
||||
|
||||
report += fmt % tuple(values)
|
||||
|
||||
report += '\n' + 100 * '-' + '\n'
|
||||
|
||||
# compute averages/sums
|
||||
values = [last_line_heading]
|
||||
for v in (
|
||||
np.average(self.precision, weights=relative_freq),
|
||||
np.average(self.recall, weights=relative_freq),
|
||||
np.average(self.f1, weights=relative_freq)):
|
||||
values += ["{0:0.{1}f}".format(v, digits)]
|
||||
values += ['{0}'.format(np.sum(relative_freq))]
|
||||
values += ['{0}'.format(np.sum(self.support))]
|
||||
values += ['']
|
||||
|
||||
# make last ("Total") line for report
|
||||
report += fmt % tuple(values)
|
||||
|
||||
return report
|
||||
|
||||
def get_avg_prec_recall(self, ConfMatrix, existing_class_names, excluded_classes=None):
|
||||
"""Get average recall and precision, using class frequencies as weights, optionally excluding
|
||||
specified classes"""
|
||||
|
||||
class2ind = dict(zip(existing_class_names, range(len(existing_class_names))))
|
||||
included_c = np.full(len(existing_class_names), 1, dtype=bool)
|
||||
|
||||
if not (excluded_classes is None):
|
||||
excl_ind = [class2ind[excl_class] for excl_class in excluded_classes]
|
||||
included_c[excl_ind] = False
|
||||
|
||||
pred_per_class = np.sum(ConfMatrix, axis=0)
|
||||
nonzero_pred = (pred_per_class > 0)
|
||||
|
||||
included = included_c & nonzero_pred
|
||||
support = np.sum(ConfMatrix, axis=1)
|
||||
weights = support[included] / np.sum(support[included])
|
||||
|
||||
prec = np.diag(ConfMatrix[included, :][:, included]) / pred_per_class[included]
|
||||
prec_avg = np.dot(weights, prec)
|
||||
|
||||
# rec = np.diag(ConfMatrix[included_c,:][:,included_c])/support[included_c]
|
||||
rec_avg = np.trace(ConfMatrix[included_c, :][:, included_c]) / np.sum(support[included_c])
|
||||
|
||||
return prec_avg, rec_avg
|
||||
|
||||
def prec_rec_histogram(self, precision, recall, binedges=None):
|
||||
"""Make a histogram with the distribution of classes with respect to precision and recall
|
||||
"""
|
||||
|
||||
if binedges is None:
|
||||
binedges = np.concatenate((np.arange(0, 0.6, 0.2), np.arange(0.6, 1.01, 0.1)), axis=0)
|
||||
binedges = np.append(binedges, binedges[-1] + 0.1) # add 1 extra bin at the end for >= 1
|
||||
|
||||
hist_precision, binedges = np.histogram(precision, binedges)
|
||||
hist_recall, binedges = np.histogram(recall, binedges)
|
||||
|
||||
print("\n\nDistribution of classes with respect to PRECISION: ")
|
||||
for b in range(len(binedges) - 1):
|
||||
print("[{:.1f}, {:.1f}): {}".format(binedges[b], binedges[b + 1], hist_precision[b]))
|
||||
|
||||
print("\n\nDistribution of classes with respect to RECALL: ")
|
||||
for b in range(len(binedges) - 1):
|
||||
print("[{:.1f}, {:.1f}): {}".format(binedges[b], binedges[b + 1], hist_recall[b]))
|
||||
|
||||
if self.plot:
|
||||
plt.figure()
|
||||
plt.subplot(121)
|
||||
widths = np.diff(binedges)
|
||||
plt.bar(binedges[:-1], hist_precision, width=widths, align='edge')
|
||||
plt.xlim(0, 1)
|
||||
ax = plt.gca()
|
||||
ax.set_xticks(binedges)
|
||||
plt.xlabel('Precision')
|
||||
plt.ylabel('Number of classes')
|
||||
plt.title("Distribution of classes with respect to precision")
|
||||
|
||||
plt.subplot(122)
|
||||
widths = np.diff(binedges)
|
||||
plt.bar(binedges[:-1], hist_recall, width=widths, align='edge')
|
||||
plt.xlim(0, 1)
|
||||
ax = plt.gca()
|
||||
ax.set_xticks(binedges)
|
||||
plt.xlabel('Recall')
|
||||
plt.ylabel('Number of classes')
|
||||
plt.title("Distribution of classes with respect to recall")
|
||||
|
||||
plt.show(block=False)
|
||||
|
||||
def analyze_classification(self, y_pred, y_true, class_names, excluded_classes=None):
|
||||
"""
|
||||
For an array of label predictions and the respective true labels, shows confusion matrix, accuracy, recall, precision etc:
|
||||
Input:
|
||||
y_pred: 1D array of predicted labels (class indices)
|
||||
y_true: 1D array of true labels (class indices)
|
||||
class_names: 1D array or list of class names in the order of class indices.
|
||||
Could also be integers [0, 1, ..., num_classes-1].
|
||||
excluded_classes: list of classes to be excluded from average precision, recall calculation (e.g. OTHER)
|
||||
"""
|
||||
|
||||
# Trim class_names to include only classes existing in y_pred OR y_true
|
||||
in_pred_labels = set(list(y_pred))
|
||||
in_true_labels = set(list(y_true))
|
||||
|
||||
self.existing_class_ind = sorted(list(in_pred_labels | in_true_labels))
|
||||
class_strings = [str(name) for name in class_names] # needed in case `class_names` elements are not strings
|
||||
self.existing_class_names = [class_strings[ind][:min(self.maxcharlength, len(class_strings[ind]))] for ind in
|
||||
self.existing_class_ind] # a little inefficient but inconsequential
|
||||
|
||||
# Confusion matrix
|
||||
ConfMatrix = metrics.confusion_matrix(y_true, y_pred)
|
||||
|
||||
if self.print_conf_mat:
|
||||
print_confusion_matrix(ConfMatrix, label_strings=self.existing_class_names, title='Confusion matrix')
|
||||
print('\n')
|
||||
if self.plot:
|
||||
plt.figure()
|
||||
plot_confusion_matrix(ConfMatrix, self.existing_class_names)
|
||||
|
||||
# Normalize the confusion matrix by row (i.e by the number of samples in each class)
|
||||
self.ConfMatrix_normalized_row = ConfMatrix.astype('float') / ConfMatrix.sum(axis=1)[:, np.newaxis]
|
||||
|
||||
if self.print_conf_mat:
|
||||
print_confusion_matrix(self.ConfMatrix_normalized_row, label_strings=self.existing_class_names,
|
||||
title='Confusion matrix normalized by row')
|
||||
print('\n')
|
||||
if self.plot:
|
||||
plt.figure()
|
||||
plot_confusion_matrix(self.ConfMatrix_normalized_row, label_strings=self.existing_class_names,
|
||||
title='Confusion matrix normalized by row')
|
||||
|
||||
plt.show(block=False)
|
||||
|
||||
# Analyze results
|
||||
self.total_accuracy = np.trace(ConfMatrix) / len(y_true)
|
||||
# print('Overall accuracy: {:.3f}\n'.format(self.total_accuracy))
|
||||
|
||||
# returns metrics for each class, in the same order as existing_class_names
|
||||
self.precision, self.recall, self.f1, self.support = metrics.precision_recall_fscore_support(y_true, y_pred,labels=self.existing_class_ind)
|
||||
|
||||
# Print report
|
||||
if self.print_conf_mat:
|
||||
print(self.generate_classification_report())
|
||||
|
||||
# Calculate average precision and recall
|
||||
self.prec_avg, self.rec_avg = self.get_avg_prec_recall(ConfMatrix, self.existing_class_names, excluded_classes)
|
||||
if excluded_classes:
|
||||
print(
|
||||
"\nAverage PRECISION: {:.2f}\n(using class frequencies as weights, excluding classes with no predictions and predictions in '{}')".format(
|
||||
self.prec_avg, ', '.join(excluded_classes)))
|
||||
print(
|
||||
"\nAverage RECALL (= ACCURACY): {:.2f}\n(using class frequencies as weights, excluding classes in '{}')".format(
|
||||
self.rec_avg, ', '.join(excluded_classes)))
|
||||
|
||||
# Make a histogram with the distribution of classes with respect to precision and recall
|
||||
#self.prec_rec_histogram(self.precision, self.recall)
|
||||
|
||||
return {"total_accuracy": self.total_accuracy, "precision": self.precision, "recall": self.recall,
|
||||
"f1": self.f1, "support": self.support, "prec_avg": self.prec_avg, "rec_avg": self.rec_avg,
|
||||
"ConfMatrix": ConfMatrix}
|
||||
@@ -0,0 +1,37 @@
|
||||
MODEL_CONFIG = {
|
||||
"cv": {"ts": False, "cwt": True, "cwtp": False, "nlp": False},
|
||||
"chronos": {"ts": True, "cwt": False, "cwtp": False, "nlp": False},
|
||||
"moirai": {"ts": True, "cwt": False, "cwtp": False, "nlp": False},
|
||||
"pretrain": {"ts": False, "cwt": False, "cwtp": True, "nlp": True},
|
||||
"nlp": {"ts": False, "cwt": False, "cwtp": False, "nlp": True},
|
||||
}
|
||||
|
||||
DATASET_CONFIG = {
|
||||
"wesad": {"n_ch": 10, "n_cl": 3, "task": "class", "lr": 1e-2,'bs':8,'max_len':390},
|
||||
"gameemo": {"n_ch": 4, "n_cl": 4, "task": "class", "lr": 1e-1,'bs':128},
|
||||
"uci_har": {"n_ch": 6, "n_cl": 6, "task": "class", "lr": 1e-1,'bs':32,'max_len':165},
|
||||
"non_invasive_bp": {"n_ch": 3, "n_cl": 2, "task": "reg", "lr": 1e-3,'bs':64},
|
||||
"ppg_hgb": {"n_ch": 2, "n_cl": 1, "task": "reg", "lr": 1e-2,'bs':8},
|
||||
"ecg_heart_cat": {"n_ch": 1, "n_cl": 2, "task": "class", "lr": 1e-2,'bs':128,'max_len':186},
|
||||
"PPG_HTN": {"n_ch": 1, "n_cl": 4, "task": "class", "lr": 7e-1,'bs':64,'max_len':271},
|
||||
"PPG_DM": {"n_ch": 1, "n_cl": 2, "task": "class", "lr": 1e-3,'bs':64,'max_len':271},
|
||||
"PPG_CVA": {"n_ch": 1, "n_cl": 2, "task": "class", "lr": 1e-4,'bs':64,'max_len':271},
|
||||
"PPG_CVD": {"n_ch": 1, "n_cl": 3, "task": "class", "lr": 1e-3,'bs':128,'max_len':271},
|
||||
"maus": {"n_ch": 3, "n_cl": 2, "task": "reg", "lr": 1e-2, 'y_range':(0,100)},
|
||||
'dalia':{'n_ch':6,'n_cl':9,'task':'class',"lr": 1e-2},
|
||||
'drive_fatigue':{'n_ch':4,'n_cl':2,'task':'class',"lr": 1e-2,'bs':16,'max_len':390},
|
||||
'indian-fPCG':{'n_ch':1,'n_cl':1,'task':'reg',"lr": 1e-2,'bs':2,}, #for mean pooling
|
||||
'Epilepsy':{'n_ch':1,'n_cl':2,'task':'class',"lr": 1e-2,'bs':64,'max_len':178},
|
||||
'ecg':{'n_ch': 1, 'n_cl': 9, 'task':"cls",'lr': 1e-3,'bs': 40,'max_len':390},
|
||||
'ppg22':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 128,'max_len':390},
|
||||
'ecg390_final':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 32,'max_len':390},
|
||||
'ecg66':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 36,'max_len':390},
|
||||
'ecg222':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 36,'max_len':390},
|
||||
'ecg661':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 36,'max_len':390},
|
||||
'ecg_binary5':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 40,'max_len':390},
|
||||
'ecg_binary6':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 40,'max_len':390},
|
||||
'ecg_binary7':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 40,'max_len':390},
|
||||
'ecg_binary8':{'n_ch': 1, 'n_cl': 2, 'task':"cls",'lr': 1e-3,'bs': 32,'max_len':390},
|
||||
|
||||
# Example: 'dataset_name': {'n_ch': num_of_channel, 'n_cl': num_of_class, 'task': 'class' or 'reg', 'lr': flot, 'bs': int, 'max_len': max_len_of_sequence}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
# corrected_linear_prob.py
|
||||
import time
|
||||
import numpy as np
|
||||
# from scipy import stats # 在此代码片段中未使用
|
||||
|
||||
from sklearn.multioutput import MultiOutputRegressor
|
||||
# from sklearn.linear_model import LogisticRegression, LinearRegression, SGDRegressor, Ridge
|
||||
from sklearn.linear_model import LogisticRegression, Ridge
|
||||
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score, balanced_accuracy_score, precision_score, recall_score
|
||||
|
||||
# from sklearn.preprocessing import MinMaxScaler
|
||||
|
||||
def linear_prob(
|
||||
x_train,
|
||||
y_train,
|
||||
x_test,
|
||||
y_test,
|
||||
task_type='class',
|
||||
random_state=42 # 注意:此处的random_state主要影响LogisticRegression的求解器,如果求解器本身是确定性的,则效果有限
|
||||
):
|
||||
# 初始化线性模型
|
||||
if task_type == 'class':
|
||||
lp = LogisticRegression(
|
||||
max_iter=500,
|
||||
solver='newton-cg',
|
||||
C=1e0,
|
||||
# random_state=random_state, # 如果求解器涉及随机性,可以保留
|
||||
# class_weight='balanced' # 如果类别不平衡,可以考虑使用
|
||||
)
|
||||
else: # 回归任务
|
||||
lp = Ridge(
|
||||
max_iter=500,
|
||||
solver="cholesky",
|
||||
alpha=1e0
|
||||
)
|
||||
if len(y_test.shape) > 1 and y_test.shape[1] > 1: # 多输出回归
|
||||
lp = MultiOutputRegressor(lp)
|
||||
|
||||
# 对回归任务的标签进行log(y+1)变换
|
||||
y_train = np.nan_to_num(np.log(y_train+1))
|
||||
y_test = np.nan_to_num(np.log(y_test+1))
|
||||
|
||||
# 将输入特征中的NaN替换为0
|
||||
x_train = np.nan_to_num(x_train)
|
||||
x_test = np.nan_to_num(x_test)
|
||||
|
||||
# 训练线性模型
|
||||
lp = lp.fit(x_train, y_train)
|
||||
|
||||
# 计算并返回分数
|
||||
return calculate_score(lp, x_test, y_test, task_type, y_train=y_train)
|
||||
|
||||
def calculate_score(lp, x_test, y_true, task_type, y_train=None):
|
||||
if task_type == "reg": # 回归任务
|
||||
y_pred_reg = lp.predict(x_test)
|
||||
|
||||
# 将预测值中的NaN替换为训练集y_train的均值(y_train此时是log变换后的)
|
||||
nan_to_mean = np.isnan(y_pred_reg) * np.mean(y_train, axis=0)
|
||||
y_pred_reg = np.nan_to_num(y_pred_reg) + nan_to_mean
|
||||
|
||||
# 将预测值裁剪到log变换后的训练标签的范围内
|
||||
y_pred_reg = np.clip(y_pred_reg, np.min(y_train), np.max(y_train))
|
||||
|
||||
# y_true 在 linear_prob 函数中已经被log变换了
|
||||
# 计算相对准确率: 1 - mean(|(y_true - y_pred) / y_true|)
|
||||
# 为避免 y_true 为0时除零错误,给分母加上一个极小值 epsilon
|
||||
epsilon = 1e-9
|
||||
error_ratio = np.absolute((y_true - y_pred_reg) / (y_true + epsilon))
|
||||
final_scores = [1 - np.mean(error_ratio)]
|
||||
return final_scores
|
||||
else: # 分类任务
|
||||
y_pred_proba = lp.predict_proba(x_test) # 模型输出的原始概率,列对应 lp.classes_
|
||||
model_classes = lp.classes_ # 模型训练时学习到的类别标签 (例如: [0, 1, ..., 7])
|
||||
|
||||
# 获取测试集真实标签中的唯一类别,并排序以保证一致性
|
||||
# (例如: y_true 中可能有 [0, 1, ..., 7, 8])
|
||||
unique_true_labels = sorted(list(set(y_true)))
|
||||
|
||||
# 创建一个新的概率矩阵,其列与 unique_true_labels 对齐
|
||||
# y_pred_aligned_proba 的列将对应 unique_true_labels 中的每个类别
|
||||
y_pred_aligned_proba = np.zeros((y_pred_proba.shape[0], len(unique_true_labels)))
|
||||
|
||||
# 构建一个从模型类别到其在 y_pred_proba 中列索引的映射
|
||||
model_class_to_idx = {cls_label: i for i, cls_label in enumerate(model_classes)}
|
||||
|
||||
for i, target_label in enumerate(unique_true_labels):
|
||||
if target_label in model_class_to_idx:
|
||||
# 如果当前真实类别是模型已知的,则从 y_pred_proba 中获取其概率
|
||||
source_col_idx = model_class_to_idx[target_label]
|
||||
y_pred_aligned_proba[:, i] = y_pred_proba[:, source_col_idx]
|
||||
else:
|
||||
# 如果当前真实类别是模型未知的,则其概率设为0
|
||||
y_pred_aligned_proba[:, i] = 0.0
|
||||
# print(f"警告: 真实标签 {target_label} 出现在 y_true 中,但模型未学习过该类别 {model_classes}。已将该类别的预测概率设为0。")
|
||||
|
||||
# 对齐后的概率按行归一化,确保每个样本的各类别概率和为1
|
||||
sum_scores = np.sum(y_pred_aligned_proba, axis=1, keepdims=True)
|
||||
# 避免除以0(如果一个样本所有对齐后的概率都为0)
|
||||
y_pred_final_proba = np.divide(y_pred_aligned_proba, sum_scores,
|
||||
out=np.zeros_like(y_pred_aligned_proba),
|
||||
where=sum_scores != 0)
|
||||
|
||||
final_scores = list()
|
||||
|
||||
# 计算 ROC AUC 和 Average Precision (AP)
|
||||
if len(unique_true_labels) <= 1:
|
||||
# 如果真实标签中只有一个或没有类别,无法计算AUC/AP,用0填充
|
||||
final_scores.extend([0.0, 0.0]) # AUC 和 AP 的占位符
|
||||
print(f"警告: y_true 中仅存在一个唯一类别 ({unique_true_labels})。无法有效计算AUC/AP。")
|
||||
elif len(unique_true_labels) == 2: # 二分类情况
|
||||
# roc_auc_score 期望的是正类的概率。
|
||||
# y_pred_final_proba 有两列,对应 unique_true_labels[0] 和 unique_true_labels[1]。
|
||||
# 约定第二列 (索引1) 对应 "正类" unique_true_labels[1]。
|
||||
try:
|
||||
final_scores.append(roc_auc_score(y_true, y_pred_final_proba[:, 1]))
|
||||
final_scores.append(average_precision_score(y_true, y_pred_final_proba[:, 1]))
|
||||
except ValueError as e:
|
||||
print(f"计算二分类AUC/AP时出错: {e}。添加占位符。")
|
||||
final_scores.extend([0.0, 0.0])
|
||||
else: # 多分类情况
|
||||
try:
|
||||
final_scores.append(roc_auc_score(y_true, y_pred_final_proba, multi_class="ovo", average="macro", labels=unique_true_labels))
|
||||
final_scores.append(average_precision_score(y_true, y_pred_final_proba, average="macro")) # AP的labels参数用法不同
|
||||
except ValueError as e:
|
||||
print(f"计算多分类AUC/AP时出错: {e}。添加占位符。")
|
||||
final_scores.extend([0.0, 0.0])
|
||||
|
||||
# 获取预测的类别标签(这些是实际的类别值,而不是索引)
|
||||
# np.argmax 返回的是 y_pred_final_proba 列的索引
|
||||
idx_pred_class = np.argmax(y_pred_final_proba, axis=1)
|
||||
# 将这些索引映射回 unique_true_labels 中的实际类别值
|
||||
actual_pred_labels = np.array(unique_true_labels)[idx_pred_class]
|
||||
|
||||
# 计算准确率 (Accuracy), 精确率 (Precision), 召回率 (Recall), F1分数
|
||||
# 确保用于指标计算的标签是 y_true 中实际存在的标签
|
||||
try:
|
||||
final_scores.append(np.mean((y_true == actual_pred_labels))) # 准确率
|
||||
final_scores.append(precision_score(y_true, actual_pred_labels, average='macro', labels=unique_true_labels, zero_division=0))
|
||||
final_scores.append(recall_score(y_true, actual_pred_labels, average='macro', labels=unique_true_labels, zero_division=0))
|
||||
final_scores.append(f1_score(y_true, actual_pred_labels, average="macro", labels=unique_true_labels, zero_division=0))
|
||||
except Exception as e: # 捕获其他可能的指标计算错误
|
||||
print(f"计算其他分类指标时出错: {e}。添加占位符。")
|
||||
# 如果前面的AUC/AP也失败了,需要补齐6个指标;否则补齐4个
|
||||
num_expected_metrics = 6
|
||||
final_scores.extend([0.0] * (num_expected_metrics - len(final_scores)))
|
||||
|
||||
return final_scores
|
||||
@@ -0,0 +1,301 @@
|
||||
#data_clean.py
|
||||
import os
|
||||
import pickle
|
||||
import numpy as np
|
||||
from tqdm import tqdm
|
||||
import json
|
||||
|
||||
# ===== HELPER function ======================================================================
|
||||
|
||||
'''
|
||||
Unified Format:
|
||||
|
||||
{
|
||||
"uid": subject ID,
|
||||
"data": [n_channel, L],
|
||||
"sampling_rate": 16000,
|
||||
"label": [
|
||||
{"class": label},
|
||||
{"reg": label},
|
||||
...
|
||||
]
|
||||
}
|
||||
|
||||
'''
|
||||
|
||||
def noisemic_format(origin_data):
|
||||
# # check keys
|
||||
# print(origin_data.keys()) # ['uid', 'run_state', 'resp_rate', 'audio']
|
||||
# exit()
|
||||
|
||||
# new format
|
||||
return {
|
||||
"uid": origin_data["uid"],
|
||||
"data": np.expand_dims(origin_data["data"], axis=0), # [1, L]
|
||||
"sampling_rate": 16000,
|
||||
"label": [
|
||||
{"class": origin_data['run_state']},
|
||||
{"reg": origin_data['resp_rate']}
|
||||
]
|
||||
}
|
||||
|
||||
def kauh_format(origin_data):
|
||||
return {
|
||||
"uid": origin_data["patient_id"],
|
||||
"data": np.stack([origin_data["filter_E"], origin_data["filter_B"], origin_data["filter_D"]]), # [3, L]
|
||||
"sampling_rate": 16000,
|
||||
"label": [
|
||||
{"class": origin_data['label']},
|
||||
]
|
||||
}
|
||||
|
||||
def respTR_format(origin_data):
|
||||
return {
|
||||
"uid": origin_data["subject_id"],
|
||||
"data": np.stack([origin_data[k] for k in origin_data.keys() if k not in ["subject_id", 'label']]), # [12, L]
|
||||
"sampling_rate": 16000,
|
||||
"label": [
|
||||
{"class": origin_data['label']},
|
||||
]
|
||||
}
|
||||
|
||||
def fsd50k_format(origin_data):
|
||||
return {
|
||||
"uid": origin_data["subject_id"],
|
||||
"data": np.expand_dims(origin_data["audio_data"], axis=0), # [1, L]
|
||||
"sampling_rate": 16000,
|
||||
"label": [
|
||||
{"class": origin_data['breathing']},
|
||||
{"class": origin_data['cough']},
|
||||
{"class": origin_data['laughter']},
|
||||
{"class": origin_data['sneeze']},
|
||||
{"class": origin_data['speech']}
|
||||
]
|
||||
}
|
||||
|
||||
def coswara_format(origin_data):
|
||||
all_keys = origin_data.keys()
|
||||
# for edge case
|
||||
for k in [
|
||||
"breathing-deep",
|
||||
"breathing-shallow",
|
||||
"cough-heavy",
|
||||
"cough-shallow",
|
||||
"counting-fast",
|
||||
"counting-normal",
|
||||
"vowel-a",
|
||||
"vowel-e",
|
||||
"vowel-o"
|
||||
]:
|
||||
if k not in all_keys:
|
||||
return None
|
||||
|
||||
# regular return
|
||||
return {
|
||||
"uid": origin_data["subject_id"],
|
||||
"data": np.stack([origin_data[k] for k in [
|
||||
"breathing-deep",
|
||||
"breathing-shallow",
|
||||
"cough-heavy",
|
||||
"cough-shallow",
|
||||
"counting-fast",
|
||||
"counting-normal",
|
||||
"vowel-a",
|
||||
"vowel-e",
|
||||
"vowel-o"
|
||||
]]), # [1, L]
|
||||
"sampling_rate": 16000,
|
||||
"label": [{"class": origin_data[k]} for k in [
|
||||
"smoker",
|
||||
"cold",
|
||||
"ht",
|
||||
"diabetes",
|
||||
"cough",
|
||||
"diarrhoea",
|
||||
"fever",
|
||||
"loss_of_smell",
|
||||
"bd",
|
||||
"st",
|
||||
"ihd",
|
||||
"asthma",
|
||||
"cld",
|
||||
"pneumonia",
|
||||
"ftg",
|
||||
"mp",
|
||||
]]
|
||||
}
|
||||
|
||||
def wearable_format(origin_data, task_type='class'):
|
||||
return {
|
||||
"uid": "",
|
||||
"data": origin_data["tss"], # TODO
|
||||
"sampling_rate": 65,
|
||||
"label": [{task_type: origin_data["label"]}] # TODO
|
||||
}
|
||||
|
||||
# def gameemo_format(origin_data, task_type='class'):
|
||||
# # print(origin_data.keys())
|
||||
# # print(origin_data["label"])
|
||||
# # exit()
|
||||
# return {
|
||||
# "uid": "",
|
||||
# "data": origin_data["tss"], # TODO
|
||||
# "sampling_rate": 65,
|
||||
# "label": [{task_type: origin_data["label"]}] # TODO
|
||||
# }
|
||||
|
||||
# ==============================================================================================
|
||||
|
||||
def clean_data(dataset='audio_downstream/NoseMic', sample_folder="sample", task_type='class'):
|
||||
# init
|
||||
root = "../data/{}/{}".format(dataset, sample_folder)
|
||||
save_to = "../data/{}/sample_for_downstream".format(dataset)
|
||||
os.makedirs(save_to, exist_ok=True)
|
||||
|
||||
# iterate over files
|
||||
for fn in tqdm(sorted(os.listdir(root))):
|
||||
if fn[0] == ".":
|
||||
continue
|
||||
|
||||
# # if exist, pass
|
||||
# if os.path.isfile(os.path.join(save_to, fn)):
|
||||
# continue
|
||||
|
||||
with open(os.path.join(root, fn), 'rb') as f:
|
||||
origin_data = pickle.load(f)
|
||||
|
||||
# new format
|
||||
# new_data = noisemic_format(origin_data)
|
||||
# new_data = kauh_format(origin_data)
|
||||
# new_data = respTR_format(origin_data)
|
||||
# new_data = fsd50k_format(origin_data)
|
||||
# new_data = coswara_format(origin_data)
|
||||
new_data = wearable_format(origin_data, task_type=task_type)
|
||||
|
||||
# new_data = gameemo_format(origin_data, task_type=task_type)
|
||||
|
||||
if new_data is None:
|
||||
continue
|
||||
|
||||
# # check
|
||||
# print(new_data['data'].shape)
|
||||
# print(new_data['label'])
|
||||
# exit()
|
||||
|
||||
# save
|
||||
with open(os.path.join(save_to, fn), 'wb') as f:
|
||||
pickle.dump(new_data, f)
|
||||
|
||||
def clean_train_test_split_format():
|
||||
read_old = lambda s: pickle.load(open("{}/splits".format(s), 'rb'))
|
||||
clean_old = lambda s: {"train": [fn.replace("\\", "/").split("/")[-1] for fn in s["train_fnames"]], "test": [fn.replace("\\", "/").split("/")[-1] for fn in s["test_fnames"]]}
|
||||
write_new = lambda s, name: json.dump(s, open("{}/train_test_split.json".format(name), 'w'))
|
||||
clean_one = lambda s: write_new(clean_old(read_old(s)), s)
|
||||
|
||||
# clean_one("PPG_DM")
|
||||
|
||||
def check_bound_for_reg(dataset="clinic_data/opioid_misuse"):
|
||||
ranges = dict()
|
||||
for fn in tqdm(os.listdir(os.path.join("../data", dataset, "sample_for_downstream"))):
|
||||
# fn = fn_obj.name
|
||||
|
||||
with open(os.path.join("../data", dataset, "sample_for_downstream", fn), 'rb') as f:
|
||||
data = pickle.load(f)
|
||||
label = data["label"]
|
||||
for l_i in range(len(label)):
|
||||
if label[l_i].get("reg") is None:
|
||||
continue
|
||||
else:
|
||||
val = label[l_i]["reg"]
|
||||
# print(label)
|
||||
# exit()
|
||||
if ranges.get(l_i) is None:
|
||||
ranges[l_i] = [val, val]
|
||||
ranges[l_i][0] = min(ranges[l_i][0], val)
|
||||
ranges[l_i][1] = max(ranges[l_i][1], val)
|
||||
|
||||
for i in ranges:
|
||||
print(i, ":", ranges[i])
|
||||
|
||||
def split_by_subject_id(dataset="clinic_data/studentlife", check_label_dist=False):
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# collect data for each subject
|
||||
sub_to_fns = dict()
|
||||
labels = dict()
|
||||
for fn_obj in os.scandir(os.path.join("data", dataset, "sample_for_downstream")):
|
||||
fn = fn_obj.name
|
||||
sub_id = fn.split("_")[0]
|
||||
|
||||
if sub_to_fns.get(sub_id) is None:
|
||||
sub_to_fns[sub_id] = list()
|
||||
labels[sub_id] = list()
|
||||
|
||||
if check_label_dist:
|
||||
with open(os.path.join("data", dataset, "sample_for_downstream", fn), 'rb') as f:
|
||||
data = pickle.load(f)
|
||||
labels[sub_id].append(data["label"][-1]["class"]) # -1, -3, 0
|
||||
|
||||
sub_to_fns[sub_id].append(fn)
|
||||
|
||||
# split the subjects
|
||||
all_subs = [k for k in sub_to_fns.keys()]
|
||||
np.random.shuffle(all_subs)
|
||||
|
||||
split_p = int(0.8*len(all_subs))
|
||||
train_subs = all_subs[:split_p]
|
||||
test_subs = all_subs[split_p:]
|
||||
|
||||
# integrate file names
|
||||
train_labels, test_labels = list(), list()
|
||||
train_test_split = {"train": list(), "test": list()}
|
||||
for sub in train_subs:
|
||||
train_test_split["train"] += sub_to_fns[sub]
|
||||
if check_label_dist:
|
||||
train_labels += labels[sub]
|
||||
for sub in test_subs:
|
||||
train_test_split["test"] += sub_to_fns[sub]
|
||||
if check_label_dist:
|
||||
test_labels += labels[sub]
|
||||
# print(train_labels)
|
||||
# print(test_labels)
|
||||
|
||||
if check_label_dist:
|
||||
fig = plt.figure()
|
||||
|
||||
plt.subplot(2, 1, 1)
|
||||
plt.hist(train_labels)
|
||||
plt.title("Train distribution")
|
||||
|
||||
plt.subplot(2, 1, 2)
|
||||
plt.hist(test_labels)
|
||||
plt.title("Test distribution")
|
||||
|
||||
plt.show()
|
||||
|
||||
# # check
|
||||
print(len(train_test_split["train"]), len(train_test_split["test"]))
|
||||
# exit()
|
||||
# for sub in sub_to_fns:
|
||||
# print(sub, ":", len(sub_to_fns[sub]))
|
||||
|
||||
# write to file
|
||||
with open(os.path.join("data", dataset, 'train_test_split.json'), 'w') as f:
|
||||
json.dump(train_test_split, f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
# python3 -m src.downstream.data_clean
|
||||
|
||||
# clean_data(dataset='downstream/PPG_HTN', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/PPG_DM', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/PPG_CVA', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/PPG_CVD', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/indian-fPCG', sample_folder="samples", task_type='reg')
|
||||
# clean_data(dataset='downstream/ppg_hgb', sample_folder="samples", task_type='reg')
|
||||
# clean_data(dataset='downstream/non_invasive_bp', sample_folder="samples", task_type='reg')
|
||||
# clean_data(dataset='downstream/drive_fatigue', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/ecg_heart_cat', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/gameemo', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/uci_har', sample_folder="samples", task_type='class')
|
||||
# clean_data(dataset='downstream/wesad', sample_folder="samples", task_type='class')
|
||||
@@ -0,0 +1,233 @@
|
||||
# --- START OF FILE engine_finetune (1).py (MODIFIED) ---
|
||||
|
||||
import torch.distributed as dist
|
||||
import math
|
||||
import sys
|
||||
from typing import Iterable, Optional
|
||||
import torch
|
||||
import sklearn
|
||||
import pandas as pd # <-- [ADDED] Import pandas for saving CSV
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
# Assuming these imports are correct in your project structure
|
||||
import NormWear.downstream_pipeline.analysis as analysis
|
||||
import NormWear.pretrain_pipeline.misc as misc
|
||||
import NormWear.modules.lr_sched as lr_sched
|
||||
|
||||
|
||||
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
|
||||
data_loader: Iterable, optimizer: torch.optim.Optimizer,
|
||||
device: torch.device, epoch: int, loss_scaler, max_norm: Optional[float] = None,
|
||||
log_writer=None,
|
||||
args=None):
|
||||
model.train(True)
|
||||
metric_logger = misc.MetricLogger(delimiter=" ")
|
||||
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
|
||||
header = 'Epoch: [{}]'.format(epoch)
|
||||
print_freq = 20
|
||||
accum_iter = args.accum_iter if args else 1
|
||||
optimizer.zero_grad()
|
||||
|
||||
if log_writer is not None:
|
||||
print('log_dir: {}'.format(log_writer.log_dir))
|
||||
|
||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||
# Adjust learning rate
|
||||
if args and (data_iter_step % accum_iter == 0):
|
||||
# Note: The original code had a check for lr_sched, which is good practice.
|
||||
if lr_sched:
|
||||
current_progress = data_iter_step / len(data_loader) + epoch
|
||||
lr_sched.adjust_learning_rate(optimizer, current_progress, args)
|
||||
|
||||
samples = batch['input'].to(device, non_blocking=True)
|
||||
targets = batch['label'].to(device, non_blocking=True)
|
||||
|
||||
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp):
|
||||
outputs, z = model(samples)
|
||||
loss = criterion(outputs, targets)
|
||||
|
||||
loss_value = loss.item()
|
||||
if not math.isfinite(loss_value):
|
||||
print(f"Loss is {loss_value}, stopping training at Epoch {epoch}, Step {data_iter_step}")
|
||||
sys.exit(1)
|
||||
|
||||
loss_to_scale = loss / accum_iter
|
||||
|
||||
# Using the callable NativeScaler for cleaner code
|
||||
loss_scaler(
|
||||
loss_to_scale,
|
||||
optimizer,
|
||||
clip_grad=max_norm,
|
||||
parameters=model.parameters(),
|
||||
update_grad=(data_iter_step + 1) % accum_iter == 0
|
||||
)
|
||||
|
||||
if (data_iter_step + 1) % accum_iter == 0:
|
||||
optimizer.zero_grad()
|
||||
|
||||
metric_logger.update(loss=loss_value)
|
||||
current_lr = optimizer.param_groups[0]["lr"]
|
||||
metric_logger.update(lr=current_lr)
|
||||
|
||||
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
|
||||
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
|
||||
log_writer.add_scalar('train/loss', loss_value, epoch_1000x)
|
||||
log_writer.add_scalar('train/lr', current_lr, epoch_1000x)
|
||||
|
||||
metric_logger.synchronize_between_processes()
|
||||
print("Averaged stats for epoch {}:".format(epoch), metric_logger)
|
||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, epoch=None, plot_save_dir=None):
|
||||
# The 'analysis' module might not be available, handle it gracefully.
|
||||
try:
|
||||
analyzer = analysis.Analyzer(print_conf_mat=print_analyzer)
|
||||
except (NameError, AttributeError):
|
||||
analyzer = None
|
||||
|
||||
metric_logger = misc.MetricLogger(delimiter=" ")
|
||||
header = 'Test:'
|
||||
model.eval()
|
||||
|
||||
all_targets = []
|
||||
all_predictions = []
|
||||
all_session_ids = []
|
||||
all_sample_ids = []
|
||||
|
||||
for batch_content in metric_logger.log_every(data_loader, 10, header):
|
||||
images = batch_content['input'].to(device, non_blocking=True)
|
||||
target = batch_content['label'].to(device, non_blocking=True)
|
||||
session_ids = batch_content['session_id']
|
||||
sample_ids = batch_content['sample_id']
|
||||
|
||||
with torch.amp.autocast(device_type=device.type, enabled=args.use_amp):
|
||||
output, z = model(images)
|
||||
loss = criterion(output, target)
|
||||
|
||||
all_targets.append(target)
|
||||
all_predictions.append(output)
|
||||
all_session_ids.extend(session_ids)
|
||||
all_sample_ids.extend(sample_ids)
|
||||
metric_logger.update(loss=loss.item())
|
||||
|
||||
metric_logger.synchronize_between_processes()
|
||||
epoch_loss = metric_logger.loss.global_avg
|
||||
print(f"[*] Synchronized loss: {epoch_loss:.4f}")
|
||||
|
||||
predictions_cat = torch.cat(all_predictions, dim=0)
|
||||
targets_cat = torch.cat(all_targets, dim=0)
|
||||
|
||||
if misc.is_dist_avail_and_initialized():
|
||||
dist.barrier()
|
||||
predictions_list = [torch.zeros_like(predictions_cat) for _ in range(misc.get_world_size())]
|
||||
targets_list = [torch.zeros_like(targets_cat) for _ in range(misc.get_world_size())]
|
||||
dist.all_gather(predictions_list, predictions_cat)
|
||||
dist.all_gather(targets_list, targets_cat)
|
||||
|
||||
session_ids_list = [None] * misc.get_world_size()
|
||||
sample_ids_list = [None] * misc.get_world_size()
|
||||
dist.all_gather_object(session_ids_list, all_session_ids)
|
||||
dist.all_gather_object(sample_ids_list, all_sample_ids)
|
||||
|
||||
if misc.is_main_process():
|
||||
predictions_np = torch.cat(predictions_list, dim=0).cpu().numpy()
|
||||
targets_np = torch.cat(targets_list, dim=0).cpu().numpy()
|
||||
all_session_ids = [item for sublist in session_ids_list for item in sublist]
|
||||
all_sample_ids = [item for sublist in sample_ids_list for item in sublist]
|
||||
else:
|
||||
return {'loss': epoch_loss}, {}
|
||||
else:
|
||||
predictions_np = predictions_cat.cpu().numpy()
|
||||
targets_np = targets_cat.cpu().numpy()
|
||||
|
||||
if not misc.is_main_process():
|
||||
return {'loss': epoch_loss}, {}
|
||||
|
||||
# Truncate to actual dataset size to handle drop_last=False in distributed mode
|
||||
num_samples = len(data_loader.dataset)
|
||||
targets_np = targets_np[:num_samples]
|
||||
predictions_np = predictions_np[:num_samples]
|
||||
all_session_ids = all_session_ids[:num_samples]
|
||||
all_sample_ids = all_sample_ids[:num_samples]
|
||||
|
||||
metrics_dict = {'loss': epoch_loss}
|
||||
per_sample_results = {}
|
||||
|
||||
if args.task == 'cls' and args.num_classes == 2:
|
||||
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
||||
positive_probs = probs_np[:, 1]
|
||||
|
||||
best_f1 = 0.0
|
||||
best_threshold = 0.5
|
||||
thresholds = np.arange(0.05, 0.96, 0.01)
|
||||
for threshold in thresholds:
|
||||
pred_labels_at_thresh = (positive_probs >= threshold).astype(int)
|
||||
f1 = sklearn.metrics.f1_score(targets_np, pred_labels_at_thresh, pos_label=1, zero_division=0)
|
||||
if f1 > best_f1:
|
||||
best_f1 = f1
|
||||
best_threshold = threshold
|
||||
|
||||
print(f"[*] Optimal threshold search: Best F1-score = {best_f1:.4f} at threshold = {best_threshold:.2f}")
|
||||
|
||||
pred_labels_np = (positive_probs >= best_threshold).astype(int)
|
||||
|
||||
accuracy = sklearn.metrics.accuracy_score(targets_np, pred_labels_np)
|
||||
precision = sklearn.metrics.precision_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
||||
recall = sklearn.metrics.recall_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
|
||||
f1 = best_f1
|
||||
|
||||
unique_targets = np.unique(targets_np)
|
||||
roc_auc, ap = 0.0, 0.0
|
||||
if len(unique_targets) > 1:
|
||||
try:
|
||||
roc_auc = sklearn.metrics.roc_auc_score(targets_np, positive_probs)
|
||||
ap = sklearn.metrics.average_precision_score(targets_np, positive_probs)
|
||||
except ValueError as e:
|
||||
print(f"Warning: Could not compute AUC/AP: {e}")
|
||||
|
||||
metrics_dict.update({
|
||||
'roc_auc': roc_auc, 'ap': ap, 'accuracy': accuracy,
|
||||
'precision': precision, 'recall': recall, 'f1_score': f1,
|
||||
'best_threshold': best_threshold
|
||||
})
|
||||
|
||||
print(f"* Test Metrics (Optimal Threshold): Loss {metrics_dict['loss']:.4f}, Accuracy {accuracy:.4f}, ROC_AUC {roc_auc:.4f}, AP {ap:.4f}")
|
||||
print(f"* Precision {precision:.4f}, Recall {recall:.4f}, F1-Score {f1:.4f}")
|
||||
|
||||
per_sample_results = {
|
||||
'session_id': all_session_ids, 'sample_id': all_sample_ids,
|
||||
'label': targets_np.tolist(), 'predicted_label': pred_labels_np.tolist(),
|
||||
'positive_prob': positive_probs.tolist()
|
||||
}
|
||||
|
||||
if analyzer:
|
||||
classification_metrics = analyzer.analyze_classification(pred_labels_np, targets_np, np.arange(args.num_classes))
|
||||
metrics_dict.update(classification_metrics)
|
||||
|
||||
elif args.task == 'cls':
|
||||
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
|
||||
pred_labels_np = np.argmax(probs_np, axis=1)
|
||||
metrics_dict['accuracy'] = np.mean(pred_labels_np == targets_np)
|
||||
|
||||
elif args.task == 'reg':
|
||||
# Assuming predictions_np is the output for regression
|
||||
mae = sklearn.metrics.mean_absolute_error(targets_np, predictions_np)
|
||||
metrics_dict['mae'] = mae
|
||||
|
||||
# --- [OPTIMIZED] Save raw, per-sample data for accurate plotting ---
|
||||
if plot_save_dir and misc.is_main_process() and args.task == 'cls' and args.num_classes == 2:
|
||||
raw_df = pd.DataFrame({
|
||||
'true_label': targets_np,
|
||||
'positive_prob': positive_probs
|
||||
})
|
||||
raw_output_path = os.path.join(plot_save_dir, f'raw_predictions_epoch_{epoch}.csv')
|
||||
raw_df.to_csv(raw_output_path, index=False)
|
||||
print(f"[*] Saved RAW per-sample predictions to {raw_output_path}")
|
||||
# --- [OPTIMIZED END] ---
|
||||
|
||||
return metrics_dict, per_sample_results
|
||||
|
||||
# --- END OF FILE engine_finetune (1).py (MODIFIED) ---
|
||||
@@ -0,0 +1,212 @@
|
||||
# linear_prob_main.py
|
||||
import os
|
||||
import json
|
||||
import pickle
|
||||
import argparse
|
||||
from tqdm import tqdm
|
||||
|
||||
from .task_specification import *
|
||||
from .corrected_linear_prob import *
|
||||
|
||||
# # basic setting
|
||||
# np.random.seed(42)
|
||||
# torch.manual_seed(42)
|
||||
|
||||
# DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device("cpu")
|
||||
# print("DEVICE:", DEVICE)
|
||||
|
||||
# get command line arguments
|
||||
def get_args_parser():
|
||||
parser = argparse.ArgumentParser('HealthMAE linear probing', add_help=False)
|
||||
|
||||
# basic parameters
|
||||
parser.add_argument('--remark', default='',
|
||||
help='model_remark')
|
||||
parser.add_argument('--prepare_embed', type=int, default=0)
|
||||
parser.add_argument('--group', type=int, default=0)
|
||||
|
||||
# Model parameters
|
||||
parser.add_argument('--model_weight_dir', default='data/results/job_rand_maskv3_checkpoint-15470-correct.pth', type=str,
|
||||
help='path of model weight')
|
||||
parser.add_argument('--model_name', type=str,
|
||||
help='Name of model to train')
|
||||
parser.add_argument('--eval', default=False,type=bool,
|
||||
help='Perform evaluation only')
|
||||
parser.add_argument('--log_dir', default='../../data/audio_results/log',
|
||||
help='path where to tensorboard log')
|
||||
parser.add_argument('--num_runs', default=1, type=int,
|
||||
help='number of runs to perform')
|
||||
|
||||
# Optimizer parameters
|
||||
parser.add_argument('--batch_size', default=64, type=int,
|
||||
help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
|
||||
parser.add_argument('--epochs', default=50, type=int)
|
||||
parser.add_argument('--warmup_epochs', type=int, default=0, metavar='N',
|
||||
help='epochs to warmup LR')
|
||||
parser.add_argument('--weight_decay', type=float, default=0,
|
||||
help='weight decay (default: 0 for linear probe following MoCo v1)')
|
||||
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR',
|
||||
help='base learning rate: absolute_lr = base_lr * total_batch_size / 256')
|
||||
|
||||
# Dataset parameters
|
||||
parser.add_argument('--data_path', default='../data', type=str,
|
||||
help='dataset path')
|
||||
parser.add_argument('--ds_name', type=str,
|
||||
help='dataset name')
|
||||
parser.add_argument('--output_dir', default='../data/audio_results/linprob_ckpt',
|
||||
help='path where to save, empty for no saving')
|
||||
parser.add_argument('--device', default='cuda',
|
||||
help='device to use for training / testing')
|
||||
|
||||
# distributed training parameters
|
||||
parser.add_argument('--world_size', default=1, type=int,
|
||||
help='number of distributed processes')
|
||||
parser.add_argument('--local_rank', default=-1, type=int)
|
||||
parser.add_argument('--dist_on_itp', action='store_true')
|
||||
parser.add_argument('--dist_url', default='env://',
|
||||
help='url used to set up distributed training')
|
||||
|
||||
|
||||
return parser
|
||||
|
||||
# def launch_linear_prob(model_name, dataset, repeat_num=3):
|
||||
def launch_linear_prob(args, embed_root, all_fns):
|
||||
# get task types
|
||||
# print("Fetching basic information...")
|
||||
with open(os.path.join(embed_root, all_fns[0]), 'rb') as f:
|
||||
sample = pickle.load(f)
|
||||
|
||||
label_types = [list(k.items())[0][0] for k in sample['label']] # ['class', 'class', 'reg', ...]
|
||||
feature_size = len(sample['embed'])
|
||||
|
||||
del sample # clear cache
|
||||
|
||||
# get split
|
||||
# print("Fetching data split...")
|
||||
split = json.load(open("../data/{}/train_test_split.json".format(args.ds_name)))
|
||||
|
||||
# load data
|
||||
x_train, y_train, x_test, y_test = list(), dict(), list(), dict()
|
||||
print("Loading {} Embedding for {} ...".format(args.model_name, args.ds_name))
|
||||
for fn in tqdm(os.listdir(embed_root)):
|
||||
with open(os.path.join(embed_root, fn), 'rb') as f:
|
||||
data = pickle.load(f)
|
||||
|
||||
if fn in split['test']:
|
||||
x_test.append(data['embed'])
|
||||
for task_idx in range(len(label_types)):
|
||||
if y_test.get(task_idx) is None:
|
||||
y_test[task_idx] = list()
|
||||
y_test[task_idx].append(data['label'][task_idx][label_types[task_idx]])
|
||||
# y_test.append(data['label'][task_idx][task_type])
|
||||
else:
|
||||
x_train.append(data['embed'])
|
||||
for task_idx in range(len(label_types)):
|
||||
if y_train.get(task_idx) is None:
|
||||
y_train[task_idx] = list()
|
||||
y_train[task_idx].append(data['label'][task_idx][label_types[task_idx]])
|
||||
# y_train.append(data['label'][task_idx][task_type])
|
||||
|
||||
x_train = np.nan_to_num(np.stack(x_train))
|
||||
x_test = np.nan_to_num(np.stack(x_test))
|
||||
# y_train = np.stack(y_train)
|
||||
# y_test = np.stack(y_test)
|
||||
for task_idx in range(len(label_types)):
|
||||
y_train[task_idx] = np.stack(y_train[task_idx])
|
||||
y_test[task_idx] = np.stack(y_test[task_idx])
|
||||
|
||||
# for score log
|
||||
task_scores = dict()
|
||||
|
||||
for type_i in range(len(label_types)):
|
||||
print("{}: Task {}/{}".format(args.ds_name, type_i+1, len(label_types)))
|
||||
for n_ in tqdm(range(args.num_runs)):
|
||||
# print("{}: Training for task {}/{}, run {}/{}...".format(args.ds_name, type_i+1, len(label_types), n_+1, args.num_runs))
|
||||
# score = linear_prob_one_task(
|
||||
# args,
|
||||
# task_idx=type_i,
|
||||
# task_type=label_types[type_i],
|
||||
# train_fns=split['train'],
|
||||
# val_fns=split['test'],
|
||||
# root_path=embed_root,
|
||||
# feature_size=feature_size,
|
||||
# num_classes=CLASS_NUM[args.ds_name]["nums"][type_i],
|
||||
# )
|
||||
|
||||
# TODO if args.group != 0: use old pipeline
|
||||
|
||||
score = linear_prob(
|
||||
x_train,
|
||||
y_train[type_i],
|
||||
x_test,
|
||||
y_test[type_i],
|
||||
task_type=label_types[type_i],
|
||||
random_state=n_
|
||||
)
|
||||
|
||||
# save the score
|
||||
if task_scores.get(CLASS_NUM[args.ds_name]["names"][type_i]) is None:
|
||||
task_scores[CLASS_NUM[args.ds_name]["names"][type_i]] = list()
|
||||
task_scores[CLASS_NUM[args.ds_name]["names"][type_i]].append(score)
|
||||
|
||||
print("Curr scores:", [round(100*s[0], 3) for s in task_scores[CLASS_NUM[args.ds_name]["names"][type_i]]])
|
||||
|
||||
# log
|
||||
for task in task_scores:
|
||||
# task_scores[task]: [n, num_score]
|
||||
all_scores_m = 100*np.mean(np.array(task_scores[task]), axis=0) # num_score
|
||||
all_scores_s = 100*np.std(np.array(task_scores[task]), axis=0) # num_score
|
||||
|
||||
scores = ""
|
||||
if len(all_scores_m) > 1:
|
||||
print("Scores following order: AUC ROC, AP, Accuracy, Precision, Recall, F1-score")
|
||||
else:
|
||||
print("Mean relative accuracy:")
|
||||
|
||||
# print
|
||||
for s_i in range(len(all_scores_m)):
|
||||
scores += "{} +- {}, ".format(
|
||||
round(all_scores_m[s_i], 3),
|
||||
round(all_scores_s[s_i], 3),
|
||||
)
|
||||
|
||||
print(task, scores)
|
||||
|
||||
return task_scores
|
||||
|
||||
# def linear_prob_one_task(args, task_idx=0, task_type='class', train_fns=list(), val_fns=list(), root_path="", feature_size=512, num_classes=2):
|
||||
# # init linear prob
|
||||
# lp_model = LinearProb(
|
||||
# lr=args.blr if task_type == 'class' else 5e-3, # 1e-3
|
||||
# weight_decay=1e-5, # 1e-5
|
||||
# epochs=args.epochs, # 50
|
||||
# batch_size=args.batch_size, # 64
|
||||
# step_size=10, # 10
|
||||
# # data related
|
||||
# num_classes=num_classes,
|
||||
# feature_size=feature_size,
|
||||
# out_range = None if task_type == 'class' else CLASS_NUM[args.ds_name]["ranges"][task_idx]
|
||||
# )
|
||||
|
||||
# # fit model
|
||||
# record = lp_model.fit(
|
||||
# task_idx,
|
||||
# train_fns,
|
||||
# val_fns=val_fns,
|
||||
# task_type=task_type,
|
||||
# root_path=root_path,
|
||||
# device=DEVICE
|
||||
# )
|
||||
|
||||
# return record["score"]
|
||||
|
||||
# save record
|
||||
|
||||
if __name__ == '__main__':
|
||||
# get command line arguments
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
|
||||
# python -m src.downstream.linear_prob_main --ds_name wearable_downstream/uci_har --model_name normwear --num_runs 100
|
||||
|
||||
launch_linear_prob(args)
|
||||
@@ -0,0 +1,64 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
class FocalLoss(nn.Module):
|
||||
"""
|
||||
A flexible Focal Loss implementation.
|
||||
Can be used for both binary and multi-class classification.
|
||||
"""
|
||||
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
|
||||
"""
|
||||
Args:
|
||||
alpha (float, list, or Tensor): Weighting factor for classes.
|
||||
If a float, it is the weight for the positive class (1).
|
||||
If a list or Tensor, it should have one weight per class.
|
||||
If None, no class weighting is applied.
|
||||
gamma (float): Focusing parameter. Higher values give more weight to hard examples.
|
||||
reduction (str): 'mean', 'sum', or 'none'.
|
||||
"""
|
||||
super(FocalLoss, self).__init__()
|
||||
if isinstance(alpha, (float, int)):
|
||||
# For binary case, alpha is weight for positive class
|
||||
self.alpha = torch.tensor([1 - alpha, alpha], dtype=torch.float)
|
||||
elif isinstance(alpha, (list, tuple, torch.Tensor)):
|
||||
self.alpha = torch.tensor(alpha, dtype=torch.float)
|
||||
else:
|
||||
self.alpha = None
|
||||
|
||||
self.gamma = gamma
|
||||
self.reduction = reduction
|
||||
|
||||
def forward(self, inputs, targets):
|
||||
"""
|
||||
Args:
|
||||
inputs (Tensor): Logits from the model, shape (N, C).
|
||||
targets (Tensor): Ground truth labels, shape (N,). Must be integer type.
|
||||
"""
|
||||
# Ensure alpha is on the same device as inputs
|
||||
if self.alpha is not None:
|
||||
if self.alpha.device != inputs.device:
|
||||
self.alpha = self.alpha.to(inputs.device)
|
||||
|
||||
# Calculate Cross Entropy loss without reduction
|
||||
ce_loss = F.cross_entropy(inputs, targets, reduction='none')
|
||||
|
||||
# Get the probability of the correct class
|
||||
pt = torch.exp(-ce_loss)
|
||||
|
||||
# Calculate Focal Loss
|
||||
focal_loss = (1 - pt) ** self.gamma * ce_loss
|
||||
|
||||
# Apply alpha weighting
|
||||
if self.alpha is not None:
|
||||
# Get alpha weight for each sample
|
||||
alpha_t = self.alpha[targets]
|
||||
focal_loss = alpha_t * focal_loss
|
||||
|
||||
# Apply reduction
|
||||
if self.reduction == 'mean':
|
||||
return focal_loss.mean()
|
||||
elif self.reduction == 'sum':
|
||||
return focal_loss.sum()
|
||||
else:
|
||||
return focal_loss
|
||||
@@ -0,0 +1,324 @@
|
||||
# --- START OF FILE main_finetune (1).py (MODIFIED) ---
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import numpy as np
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
import pandas as pd # <-- [ADDED] Import pandas
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.backends.cudnn as cudnn
|
||||
from torch.utils.data import DataLoader
|
||||
import torch.distributed as dist
|
||||
from tqdm import tqdm
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
|
||||
# Assuming project structure allows these imports
|
||||
from .config import DATASET_CONFIG
|
||||
from NormWear.modules.normwear import NormWear
|
||||
from NormWear.modules.head import RegressionHead, MLPClassificationHeadWithMeanPatchPooling, ClassificationHead
|
||||
from .engine_finetune import train_one_epoch, evaluate
|
||||
import NormWear.pretrain_pipeline.misc as misc
|
||||
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
||||
from NormWear.pretrain_pipeline.dataset import dataset_class
|
||||
|
||||
def str2bool(v):
|
||||
if isinstance(v, bool): return v
|
||||
if v.lower() in ('yes', 'true', 't', 'y', '1'): return True
|
||||
elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False
|
||||
else: raise argparse.ArgumentTypeError('Boolean value expected.')
|
||||
|
||||
def parse_tuple(arg_str):
|
||||
if arg_str.startswith('(') and arg_str.endswith(')'): arg_str = arg_str[1:-1]
|
||||
return tuple(map(int, arg_str.split(',')))
|
||||
|
||||
class FocalLoss(nn.Module):
|
||||
# ... (FocalLoss class remains unchanged) ...
|
||||
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
|
||||
super(FocalLoss, self).__init__()
|
||||
self.alpha = alpha
|
||||
self.gamma = gamma
|
||||
self.reduction = reduction
|
||||
def forward(self, inputs, targets):
|
||||
ce_loss = F.cross_entropy(inputs, targets, reduction='none')
|
||||
pt = torch.exp(-ce_loss)
|
||||
focal_term = (1 - pt).pow(self.gamma)
|
||||
loss = focal_term * ce_loss
|
||||
if self.alpha is not None:
|
||||
if self.alpha.device != loss.device: self.alpha = self.alpha.to(loss.device)
|
||||
alpha_t = self.alpha.gather(0, targets)
|
||||
loss = alpha_t * loss
|
||||
if self.reduction == 'mean': return loss.mean()
|
||||
elif self.reduction == 'sum': return loss.sum()
|
||||
else: return loss
|
||||
|
||||
class LinearProb(nn.Module):
|
||||
# ... (LinearProb class remains unchanged) ...
|
||||
def __init__(self, backbone, num_classes, num_channel, embed_size, task='reg', y_range=None):
|
||||
super().__init__()
|
||||
self.backbone = backbone
|
||||
if task == 'reg':
|
||||
self.head = RegressionHead(n_vars=num_channel, d_model=embed_size, y_range=y_range, output_dim=num_classes)
|
||||
else:
|
||||
self.head = ClassificationHead(n_vars=num_channel, d_model=embed_size, n_classes=num_classes, head_dropout=0.3)
|
||||
self.embed_size = embed_size
|
||||
|
||||
def forward(self, x):
|
||||
z = self.backbone.get_signal_embedding(x, device=x.device)
|
||||
x_out = self.head(z)
|
||||
return x_out, z
|
||||
|
||||
def get_args_parser():
|
||||
# ... (get_args_parser function remains unchanged) ...
|
||||
parser = argparse.ArgumentParser('NormWear Fine-tuning', add_help=False)
|
||||
parser.add_argument('--ds_name', default='ecg_binary8', type=str, help='dataset name')
|
||||
parser.add_argument('--data_dir', default='../data', type=str, help='dataset path')
|
||||
parser.add_argument('--output_dir', default='../data/results_finetune', help='path where to save, empty for no saving')
|
||||
parser.add_argument('--log_dir', default='../data/results_finetune/logs', help='path where to tensorboard log')
|
||||
parser.add_argument('--device', default='cuda', help='device to use for training / testing')
|
||||
parser.add_argument('--eval', action='store_true', help='Perform evaluation only')
|
||||
parser.add_argument('--checkpoint', default='../data/results/model_moco_amp_float16/run_14/checkpoint-199.pth', type=str, help='model checkpoint for fine-tuning')
|
||||
parser.add_argument('--embed_dim', type=int, default=256, help='Embedding dimension of the backbone')
|
||||
parser.add_argument('--depth', type=int, default=8, help='Depth of the transformer backbone')
|
||||
parser.add_argument('--num_heads', type=int, default=8, help='Number of attention heads in the backbone')
|
||||
parser.add_argument('--use_meanpooling', type=int, default=0, help='meanpooling cls fusion in backbone')
|
||||
parser.add_argument('--batch_size', default=128, type=int)
|
||||
parser.add_argument('--epochs', default=100, type=int)
|
||||
parser.add_argument('--accum_iter', default=1, type=int)
|
||||
parser.add_argument('--lr', type=float, default=None, metavar='LR')
|
||||
parser.add_argument('--blr', type=float, default=1e-4, metavar='LR')
|
||||
parser.add_argument('--weight_decay', type=float, default=0.05)
|
||||
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
|
||||
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
|
||||
parser.add_argument('--use_focal_loss', action='store_true', help='Use Focal Loss for classification')
|
||||
parser.add_argument('--focal_gamma', type=float, default=2.0, help='Gamma for Focal Loss')
|
||||
parser.add_argument('--use_amp', action='store_true', help='Enable Automatic Mixed Precision (AMP) training.')
|
||||
parser.add_argument('--no_amp', action='store_false', dest='use_amp', help='Disable Automatic Mixed Precision (AMP) training.')
|
||||
parser.set_defaults(use_amp=True)
|
||||
parser.add_argument('--remark', default='finetune_moco', help='A remark for the run')
|
||||
parser.add_argument('--seed', default=42, type=int)
|
||||
parser.add_argument('--num_workers', default=4, type=int)
|
||||
parser.add_argument('--pin_mem', action='store_true')
|
||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
||||
parser.set_defaults(pin_mem=True)
|
||||
parser.add_argument('--world_size', default=1, type=int)
|
||||
parser.add_argument('--local_rank', default=-1, type=int)
|
||||
parser.add_argument('--dist_on_itp', action='store_true')
|
||||
parser.add_argument('--dist_url', default='env://')
|
||||
return parser
|
||||
|
||||
# --- [OPTIMIZED] Encapsulated and corrected CSV saving logic ---
|
||||
def save_prediction_summary(per_sample_results, output_dir, epoch):
|
||||
"""
|
||||
Aggregates per-sample results, calculates statistics, and saves to a CSV file.
|
||||
This version correctly calculates 'positive_rate' based on the mean of raw probabilities.
|
||||
"""
|
||||
if not per_sample_results or 'session_id' not in per_sample_results:
|
||||
print(f"Warning: No per-sample results to save for epoch {epoch}.")
|
||||
return
|
||||
|
||||
df = pd.DataFrame(per_sample_results)
|
||||
|
||||
summary_df = df.groupby('session_id').agg(
|
||||
# Count 0/1 predictions based on the optimal threshold
|
||||
positive_preds=('predicted_label', lambda x: (x == 1).sum()),
|
||||
negative_preds=('predicted_label', lambda x: (x == 0).sum()),
|
||||
# CORRECTED: Calculate positive rate from the mean of raw probabilities
|
||||
positive_rate=('positive_prob', 'mean'),
|
||||
# Get the ground truth label for the group
|
||||
label=('label', 'first')
|
||||
).reset_index()
|
||||
|
||||
summary_df['negative_rate'] = 1.0 - summary_df['positive_rate']
|
||||
|
||||
summary_df = summary_df.rename(columns={
|
||||
'session_id': '人物唯一ID_时间戳',
|
||||
'positive_preds': '正例样本数',
|
||||
'negative_preds': '负例样本数',
|
||||
'positive_rate': '阳性率',
|
||||
'negative_rate': '阴性率',
|
||||
'label': '真实标签'
|
||||
})
|
||||
|
||||
final_df = summary_df[[
|
||||
'人物唯一ID_时间戳', '真实标签', '正例样本数',
|
||||
'负例样本数', '阳性率', '阴性率'
|
||||
]]
|
||||
|
||||
csv_path = os.path.join(output_dir, f'summary_epoch_{epoch:03d}.csv')
|
||||
final_df.to_csv(csv_path, index=False, encoding='utf-8-sig')
|
||||
print(f"Saved aggregated prediction summary to {csv_path}")
|
||||
# --- [OPTIMIZED END] ---
|
||||
|
||||
def main(args):
|
||||
misc.init_distributed_mode(args)
|
||||
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
|
||||
print("{}".format(args).replace(', ', ',\n'))
|
||||
|
||||
device = torch.device(args.device)
|
||||
seed = args.seed + misc.get_rank()
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
cudnn.benchmark = True
|
||||
|
||||
# === [OPTIMIZED] Setup Logging and Directories ===
|
||||
log_writer = None
|
||||
plot_save_dir = None
|
||||
summary_save_dir = None
|
||||
if misc.is_main_process():
|
||||
run_name = f"{args.remark}_{args.ds_name}_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
||||
args.output_dir = os.path.join(args.output_dir, run_name)
|
||||
args.log_dir = os.path.join(args.output_dir, 'logs')
|
||||
|
||||
os.makedirs(args.output_dir, exist_ok=True)
|
||||
os.makedirs(args.log_dir, exist_ok=True)
|
||||
|
||||
log_writer = SummaryWriter(log_dir=args.log_dir)
|
||||
|
||||
# Directory for raw per-sample data (for accurate plotting)
|
||||
plot_save_dir = os.path.join(args.output_dir, 'raw_predictions_per_epoch')
|
||||
os.makedirs(plot_save_dir, exist_ok=True)
|
||||
|
||||
# Directory for aggregated summary CSVs
|
||||
summary_save_dir = os.path.join(args.output_dir, 'prediction_summary_csv')
|
||||
os.makedirs(summary_save_dir, exist_ok=True)
|
||||
# === [OPTIMIZED END] ===
|
||||
|
||||
# === Dataset and DataLoader ===
|
||||
# ... (This section remains unchanged) ...
|
||||
dataset_config = DATASET_CONFIG[args.ds_name]
|
||||
args.num_channel = dataset_config["n_ch"]
|
||||
args.num_classes = dataset_config["n_cl"]
|
||||
args.task = dataset_config.get("task", "cls")
|
||||
args.max_len = dataset_config.get("max_len", 390)
|
||||
args.img_size = (args.max_len - 2, 65)
|
||||
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
|
||||
train_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name), is_train=True, max_len=args.max_len, use_spec=True, augmentations=train_augmentations, img_size=args.img_size)
|
||||
test_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name), is_train=False, max_len=args.max_len, use_spec=True, augmentations=None, img_size=args.img_size)
|
||||
if args.distributed:
|
||||
sampler_train = torch.utils.data.DistributedSampler(train_dataset, shuffle=True)
|
||||
sampler_val = torch.utils.data.DistributedSampler(test_dataset, shuffle=False)
|
||||
else:
|
||||
sampler_train = torch.utils.data.RandomSampler(train_dataset)
|
||||
sampler_val = torch.utils.data.SequentialSampler(test_dataset)
|
||||
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
|
||||
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
|
||||
|
||||
# === Model Loading and Weight Extraction ===
|
||||
# ... (This section remains unchanged) ...
|
||||
print(f"Loading pre-trained MoCo checkpoint from: {args.checkpoint}")
|
||||
backbone = NormWear(img_size=args.img_size, patch_size=(9, 5), nvar=5, embed_dim=args.embed_dim, depth=args.depth, num_heads=args.num_heads, is_pretrain=False, mean_fuse=bool(args.use_meanpooling))
|
||||
checkpoint = torch.load(args.checkpoint, map_location='cpu')
|
||||
print("Extracting 'encoder_q' weights from the MoCo checkpoint...")
|
||||
full_moco_state_dict = checkpoint['model']
|
||||
encoder_q_state_dict = {k.replace('encoder_q.', ''): v for k, v in full_moco_state_dict.items() if k.startswith('encoder_q.')}
|
||||
msg = backbone.load_state_dict(encoder_q_state_dict, strict=True)
|
||||
print("Backbone loading message:", msg)
|
||||
model = LinearProb(backbone, num_classes=args.num_classes, num_channel=args.num_channel, embed_size=args.embed_dim, task=args.task, y_range=dataset_config.get("y_range"))
|
||||
model.to(device)
|
||||
|
||||
# === Optimizer, Loss, and Training Setup ===
|
||||
# ... (This section remains unchanged) ...
|
||||
model_without_ddp = model
|
||||
if args.distributed:
|
||||
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
|
||||
model_without_ddp = model.module
|
||||
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
||||
print('Number of trainable params: %.2f M' % (n_parameters / 1.e6))
|
||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
||||
if args.lr is None: args.lr = args.blr * eff_batch_size / 256
|
||||
print("LR: %.2e" % args.lr)
|
||||
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
|
||||
loss_scaler = NativeScaler()
|
||||
if args.task == 'cls':
|
||||
criterion = FocalLoss(gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
|
||||
else:
|
||||
criterion = torch.nn.L1Loss()
|
||||
print("Using criterion:", str(criterion))
|
||||
|
||||
# === Training Loop ===
|
||||
print(f"Start fine-tuning for {args.epochs} epochs")
|
||||
start_time = time.time()
|
||||
max_metric = -float('inf')
|
||||
best_epoch = 0
|
||||
|
||||
for epoch in tqdm(range(args.epochs), disable=not misc.is_main_process()):
|
||||
if args.distributed:
|
||||
train_loader.sampler.set_epoch(epoch)
|
||||
|
||||
train_stats = train_one_epoch(model, criterion, train_loader, optimizer, device, epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
|
||||
|
||||
test_stats, per_sample_results = evaluate(args, test_loader, model, device, criterion, print_analyzer=False, epoch=epoch, plot_save_dir=plot_save_dir)
|
||||
|
||||
if misc.is_main_process():
|
||||
# --- [OPTIMIZED] Call the new function to save the aggregated summary ---
|
||||
save_prediction_summary(per_sample_results, summary_save_dir, epoch)
|
||||
|
||||
if args.task == 'cls':
|
||||
current_metric = test_stats.get('roc_auc', 0.0)
|
||||
metric_name = 'roc_auc'
|
||||
else:
|
||||
current_metric = -test_stats.get('mae', float('inf'))
|
||||
metric_name = 'mae'
|
||||
|
||||
print(
|
||||
f"Epoch {epoch}: Test Loss: {test_stats.get('loss', 0):.4f}, "
|
||||
f"AUC: {test_stats.get('roc_auc', 0):.4f}, "
|
||||
f"AP: {test_stats.get('ap', 0):.4f}, "
|
||||
f"F1: {test_stats.get('f1_score', 0):.4f}, "
|
||||
f"Accuracy: {test_stats.get('accuracy', 0):.4f}"
|
||||
)
|
||||
|
||||
if current_metric > max_metric:
|
||||
max_metric = current_metric
|
||||
best_epoch = epoch
|
||||
if args.output_dir:
|
||||
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch="best")
|
||||
|
||||
print(f'Max {metric_name}: {abs(max_metric):.4f} at epoch {best_epoch}')
|
||||
|
||||
if log_writer is not None:
|
||||
log_writer.add_scalar(f'perf/test_{metric_name}', abs(current_metric), epoch)
|
||||
log_writer.add_scalar('perf/test_loss', test_stats.get('loss', 0.0), epoch)
|
||||
log_writer.add_scalar('train/loss', train_stats.get('loss', 0.0), epoch)
|
||||
|
||||
if args.distributed:
|
||||
dist.barrier()
|
||||
|
||||
# === Final Evaluation ===
|
||||
# ... (This section remains unchanged) ...
|
||||
if misc.is_main_process():
|
||||
print('\n####### Loading the best model for final evaluation ######')
|
||||
best_model_path = os.path.join(args.output_dir, 'checkpoint-best.pth') # Corrected filename based on misc.save_model
|
||||
if os.path.exists(best_model_path):
|
||||
print(f'Loading best model from epoch {best_epoch}')
|
||||
checkpoint = torch.load(best_model_path, map_location='cpu')
|
||||
model_without_ddp.load_state_dict(checkpoint['model'])
|
||||
|
||||
final_plot_dir = os.path.join(args.output_dir, 'final_plots')
|
||||
os.makedirs(final_plot_dir, exist_ok=True)
|
||||
|
||||
test_stats_best, _ = evaluate(args, test_loader, model, device, criterion, print_analyzer=True, epoch="best", plot_save_dir=final_plot_dir)
|
||||
|
||||
print(f"\n--- Final Evaluation (Best Model from Epoch {best_epoch}) ---")
|
||||
for metric, value in test_stats_best.items():
|
||||
print(f" {metric.capitalize()}: {value:.5f}")
|
||||
else:
|
||||
print(f"Warning: Best model checkpoint {best_model_path} not found. Skipping final evaluation.")
|
||||
|
||||
total_time = time.time() - start_time
|
||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||
if misc.is_main_process():
|
||||
print('Training time {}'.format(total_time_str))
|
||||
print('Done!')
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
main(args)
|
||||
|
||||
# --- END OF FILE main_finetune (1).py (MODIFIED) ---
|
||||
@@ -0,0 +1,458 @@
|
||||
# model_apis.py
|
||||
import os
|
||||
import pickle
|
||||
import torch
|
||||
import numpy as np
|
||||
import torch.nn as nn
|
||||
from scipy import signal
|
||||
from scipy.ndimage import gaussian_filter
|
||||
|
||||
import torchaudio.transforms as T
|
||||
|
||||
from transformers import ClapAudioModelWithProjection, ClapProcessor, AutoTokenizer, ClapTextModelWithProjection
|
||||
|
||||
import time
|
||||
|
||||
from scipy.stats import skew, kurtosis
|
||||
|
||||
def freeze_model(model):
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
return model
|
||||
|
||||
def unfreeze_model(model):
|
||||
for param in model.parameters():
|
||||
param.requires_grad = True
|
||||
return model
|
||||
|
||||
def extract_stat_features(ts, sampling_rate):
|
||||
# time domain
|
||||
feats = [ts.mean(), ts.std(), ts.max(), ts.min(), skew(ts), kurtosis(ts)]
|
||||
feats += [np.quantile(ts, 0.25), np.quantile(ts, 0.5), np.quantile(ts, 0.75)]
|
||||
|
||||
# freq domain
|
||||
ts = torch.from_numpy(ts).float()
|
||||
# Perform the Fourier Transform
|
||||
spectrum = torch.fft.fft(ts)
|
||||
magnitude_spectrum = torch.abs(spectrum)
|
||||
|
||||
# Only keep the positive frequencies (up to Nyquist frequency)
|
||||
magnitude_spectrum = magnitude_spectrum[:len(magnitude_spectrum) // 2]
|
||||
|
||||
# Frequency bins
|
||||
freqs = torch.fft.fftfreq(len(ts), d=1/sampling_rate)[:len(magnitude_spectrum)]
|
||||
|
||||
# Normalized magnitude spectrum for weighted calculations
|
||||
normalized_magnitude = magnitude_spectrum / magnitude_spectrum.sum()
|
||||
|
||||
# Centroid (weighted mean frequency)
|
||||
centroid = torch.sum(freqs * normalized_magnitude)
|
||||
|
||||
# Mean Frequency (unweighted mean)
|
||||
mean_freq = torch.mean(freqs)
|
||||
|
||||
# Peak Frequency (frequency with the maximum magnitude)
|
||||
peak_freq = freqs[torch.argmax(magnitude_spectrum)]
|
||||
|
||||
# Spread (standard deviation around the centroid)
|
||||
spread = torch.sqrt(torch.sum(((freqs - centroid) ** 2) * normalized_magnitude))
|
||||
|
||||
# Quantiles (25%, median (50%), 75%)
|
||||
cumulative_magnitude = torch.cumsum(normalized_magnitude, dim=0)
|
||||
quantile_25 = freqs[min(torch.searchsorted(cumulative_magnitude, 0.25), len(freqs)-1)]
|
||||
median_freq = freqs[min(torch.searchsorted(cumulative_magnitude, 0.5), len(freqs)-1)]
|
||||
quantile_75 = freqs[min(torch.searchsorted(cumulative_magnitude, 0.75), len(freqs)-1)]
|
||||
|
||||
freq_feats = [centroid, spread, mean_freq, peak_freq, quantile_25, median_freq, quantile_75]
|
||||
|
||||
feats += [feat.item() for feat in freq_feats]
|
||||
|
||||
return feats
|
||||
|
||||
|
||||
#### More Baseline Models ################
|
||||
class Demogr_API(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.demo_size = -1
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu'), sub_info=None):
|
||||
ds_name, fn, root_prefix = sub_info
|
||||
sub_id = fn.split("_")[0]
|
||||
|
||||
# edge filename case for indian-fPCG
|
||||
if sub_id == 'subject':
|
||||
sub_id = fn
|
||||
# sub_id = fn.split(".")[0] # if it is indian-fPCG
|
||||
|
||||
# load demographic info
|
||||
with open("{}data/{}/demo.pkl".format(root_prefix, ds_name), 'rb') as f:
|
||||
demo_vec = pickle.load(f)[sub_id] # D
|
||||
return torch.from_numpy(demo_vec)
|
||||
|
||||
# from tsfresh import extract_features
|
||||
# import pandas as pd
|
||||
class STAT_API(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu')):
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
|
||||
# tokenization
|
||||
embeds = list()
|
||||
for i in range(len(sample_data)):
|
||||
features = extract_stat_features(sample_data[i], sampling_rate)
|
||||
|
||||
# df = pd.DataFrame({"value": sample_data[i].astype(np.float32), "time": np.arange(len(sample_data[i])), "id": 1})
|
||||
|
||||
# # Extract features
|
||||
# features = extract_features(df, column_id="id", column_sort="time", disable_progressbar=True).to_numpy().squeeze()
|
||||
|
||||
# take log for numerical stability
|
||||
features = np.sign(features) * np.log1p(np.abs(features))
|
||||
embeds.append(np.nan_to_num(features))
|
||||
audio_embedding = torch.from_numpy(np.stack(embeds))
|
||||
# audio_embedding = torch.mean(audio_embedding, dim=0) # [783]
|
||||
audio_embedding = audio_embedding.flatten() # [16*nvar]
|
||||
|
||||
# print(audio_embedding.shape, audio_embedding.mean(), audio_embedding.min(), audio_embedding.max())
|
||||
# exit()
|
||||
|
||||
return audio_embedding
|
||||
|
||||
import torch.fft as fft
|
||||
from ..baseline_models.tfc.TFC.model import *
|
||||
class TFC_API(nn.Module):
|
||||
def __init__(self, sampling_rate=65):
|
||||
super().__init__()
|
||||
|
||||
self.sampling_rate = sampling_rate
|
||||
|
||||
state_dict = torch.load("NormWear/modules/model_ckpts/ckp_last.pt")["model_state_dict"]
|
||||
|
||||
# configs.TSlength_aligned = 178
|
||||
# for k in state_dict:
|
||||
# # print(k)
|
||||
# print(k, state_dict[k].shape)
|
||||
|
||||
self.backbone = TFC(178)
|
||||
self.backbone.load_state_dict(state_dict)
|
||||
|
||||
print("Load Success.")
|
||||
# exit()
|
||||
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu')):
|
||||
# sample_data: [nvar, L]
|
||||
# need x_in_t, x_in_f
|
||||
if not torch.is_tensor(sample_data):
|
||||
sample_data = torch.from_numpy(sample_data)
|
||||
|
||||
x_in_t = sample_data.unsqueeze(1)[:, :1, -178:].to(device).float() # [nvar, 1, L]
|
||||
if x_in_t.shape[-1] < 178:
|
||||
x_in_t = torch.concat((torch.zeros(x_in_t.shape[0], x_in_t.shape[1], 178-x_in_t.shape[-1]).to(device), x_in_t), dim=-1)
|
||||
x_in_f = fft.fft(x_in_t).abs().float()
|
||||
out = self.backbone(x_in_t, x_in_f)
|
||||
|
||||
# audio_embedding = torch.mean(out, dim=0) # [256]
|
||||
audio_embedding = out.flatten()
|
||||
|
||||
# print(audio_embedding.shape, audio_embedding.mean(), audio_embedding.min(), audio_embedding.max())
|
||||
# exit()
|
||||
|
||||
return audio_embedding
|
||||
|
||||
# ======= NEED SPECIAL DEPENDENCIES ========================================================
|
||||
# from msclap import CLAP
|
||||
# https://github.com/microsoft/CLAP
|
||||
class CLAP_API(nn.Module):
|
||||
def __init__(self, sampling_rate=48000):
|
||||
super().__init__()
|
||||
self.backbone = freeze_model(ClapAudioModelWithProjection.from_pretrained("laion/clap-htsat-fused"))
|
||||
self.processor = ClapProcessor.from_pretrained("laion/clap-htsat-fused")
|
||||
|
||||
self.nlp_model = freeze_model(ClapTextModelWithProjection.from_pretrained("laion/clap-htsat-fused"))
|
||||
self.tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-fused")
|
||||
|
||||
self.sampling_rate = sampling_rate
|
||||
|
||||
def txt_encode(self, sentences):
|
||||
inputs = self.tokenizer(text=sentences, return_tensors="pt", padding=True).to(self.nlp_model.device)
|
||||
return self.nlp_model(**inputs).text_embeds # [n, 512]
|
||||
|
||||
def forward(self, x, task, label=None):
|
||||
# x: [updated] [bn, nvar, L]
|
||||
# task, label: string for sentence template match
|
||||
# label: None if query only
|
||||
device = x.device
|
||||
|
||||
# resample
|
||||
bn, nvar, L = x.shape
|
||||
resampler = T.Resample(65, self.sampling_rate) # currently hardcode to 65hz
|
||||
# print("Resampling...")
|
||||
x = resampler(x.reshape(bn*nvar, L).cpu()).float()
|
||||
|
||||
# calculate spectrogram
|
||||
# print("Calculate spec...")
|
||||
inputs = self.processor(audios=x.cpu().numpy(), return_tensors="pt", sampling_rate=self.sampling_rate)
|
||||
for k in inputs:
|
||||
inputs[k] = inputs[k].to(device)
|
||||
# print("Forward...")
|
||||
outputs = self.backbone(**inputs)
|
||||
audio_embeds = outputs.audio_embeds.reshape(bn, nvar, -1).mean(dim=1) # [bn*nvar, 512]
|
||||
|
||||
return audio_embeds
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu')):
|
||||
# data: [nvar, L]
|
||||
if sampling_rate != self.sampling_rate:
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
resampler = T.Resample(sampling_rate, self.sampling_rate)
|
||||
sample_data = resampler(torch.from_numpy(sample_data.astype(np.float32))).numpy()
|
||||
|
||||
# tokenization
|
||||
inputs = self.processor(audios=sample_data, return_tensors="pt", sampling_rate=self.sampling_rate)
|
||||
for k in inputs:
|
||||
inputs[k] = inputs[k].to(device)
|
||||
|
||||
outputs = self.backbone(**inputs)
|
||||
audio_embeds = outputs.audio_embeds # [nvar, 512]
|
||||
# audio_embedding = torch.mean(audio_embeds, dim=0) # E
|
||||
audio_embedding = audio_embeds.flatten()
|
||||
|
||||
return audio_embedding
|
||||
|
||||
class Chronos_API(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
# import required lib
|
||||
from chronos import ChronosPipeline
|
||||
|
||||
self.backbone = ChronosPipeline.from_pretrained(
|
||||
"amazon/chronos-t5-large",
|
||||
device_map="cuda", # use "cpu" for CPU inference and "mps" for Apple Silicon
|
||||
torch_dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu')):
|
||||
# data: [nvar, L]
|
||||
|
||||
# forward
|
||||
embeddings, tokenizer_state = self.backbone.embed(torch.tensor(sample_data).float()) # [nvar, L, 768]
|
||||
# embeddings = torch.mean(embeddings, dim=1) # take the mean, [nvar, E]
|
||||
embeddings = embeddings[:, -1, :] # taken the representation at last state (because chronos is trained for forecasting, the last state is the key representation for the start of generation)
|
||||
# audio_embeddings = torch.mean(embeddings, dim=0) # E (768)
|
||||
audio_embeddings = embeddings.flatten() # E (768)
|
||||
return audio_embeddings.float()
|
||||
|
||||
def forward(self, x):
|
||||
pass
|
||||
|
||||
#==========================================================================================
|
||||
|
||||
# ===== BASELINE END ======================================================================
|
||||
|
||||
from ..modules.normwear import *
|
||||
|
||||
def wt(ts, lf=0.1, hf=65, wl='gaus1', method='fft'):
|
||||
# in: L
|
||||
# out: FxL
|
||||
# cwtmatr, freqs = pywt.cwt(ts, np.arange(lf, hf), wl, method=method)
|
||||
cwtmatr = signal.cwt(ts, signal.ricker, np.arange(lf, hf))
|
||||
return cwtmatr #[F, L]
|
||||
|
||||
def spec_cwt(audio_data): # [nvar, L]
|
||||
x1 = audio_data[:, 1:] - audio_data[:, :-1]
|
||||
x2 = x1[:, 1:] - x1[:, :-1]
|
||||
|
||||
all_specs = list()
|
||||
for c_i in range(audio_data.shape[0]):
|
||||
all_specs.append(torch.stack([
|
||||
torch.from_numpy(wt(audio_data[c_i, 2:])).permute(1, 0), # [L, n_mels]
|
||||
torch.from_numpy(wt(x1[c_i, 1:])).permute(1, 0),
|
||||
torch.from_numpy(wt(x2[c_i])).permute(1, 0)
|
||||
])) # [3, L, n_mels]
|
||||
|
||||
all_specs = torch.stack(all_specs) # [nvar, 3, L, n_mels]
|
||||
|
||||
return all_specs
|
||||
|
||||
class NormWear_API(nn.Module):
|
||||
def __init__(self, weight_path="data/results/job_rand_maskv3_checkpoint-15470-correct.pth"):
|
||||
super().__init__()
|
||||
self.backbone = NormWear(img_size=(387,65), patch_size=(9,5),mask_scheme='random',mask_prob=0.8,use_cwt=True,nvar=4, comb_freq=False)
|
||||
|
||||
# weight_path = '../data/results/NormWear_Huge_job_resume_checkpoint-1-correct.pth'
|
||||
# weight_path = '../data/results/model_mae_checkpoint-140.pth'
|
||||
# '../data/results/NormWear_Huge_job_resume_checkpoint-1-correct.pth' # 2.5m
|
||||
# ../data/results/NormWear_Huge_job_checkpoint-0.pth # train from scratch on 1.5Tb
|
||||
# weight_path = '../data/results/NormWear_Large_checkpoint-10.pth' # 24w (Currently reproducible the best)
|
||||
# weight_path = 'data/results/job_rand_maskv3_checkpoint-15470-correct.pth' # 1.5Tb (Currently reproducible the best)
|
||||
# weight_path = '../data/results/meanfusion_checkpoint-12000.pth'
|
||||
# weight_path = '../data/results/freqmask-scratch_checkpoint-13470.pth'
|
||||
# weight_path = '../data/results/timemask-scratch_checkpoint-13470.pth'
|
||||
# weight_path = '../data/results/job_rand_maskv3_checkpoint-0epoch-6000_correct.pth'
|
||||
# '../data/results/model_mae_checkpoint-140.pth' # 37k
|
||||
|
||||
# load pretrained checkpoint
|
||||
stat_dict = torch.load(weight_path, map_location=torch.device('cpu'))['model']
|
||||
|
||||
# stat_dict = torch.load('../data/results/model_mae_checkpoint-140.pth', map_location=torch.device('cpu'))['model']
|
||||
self.backbone.load_state_dict(stat_dict)
|
||||
print("Model load successfull.")
|
||||
|
||||
self.sampling_rate = 65
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu'), sub_info=None):
|
||||
# data: [nvar, L]
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
sample_data = torch.from_numpy(sample_data.astype(np.float32))
|
||||
|
||||
# resample
|
||||
if sampling_rate != self.sampling_rate:
|
||||
if sampling_rate > 256:
|
||||
resampler = T.Resample(sampling_rate, self.sampling_rate)
|
||||
sample_data = resampler(sample_data) # [nvar, L]
|
||||
|
||||
# calculate spectrogram
|
||||
spec = spec_cwt(sample_data.numpy()).float().unsqueeze(0).to(device) # [1, nvar, 3, L, n_mels]
|
||||
# ====================================================================
|
||||
|
||||
# forward
|
||||
out, hiddens = self.backbone.get_signal_embedding(spec, hidden_out=True, device=device) # 1, nvar, P, E
|
||||
# hidden: list([1, nvar, P, E])
|
||||
|
||||
out = torch.mean(out[0, :, :, :], dim=1) # nvar, E
|
||||
# out = out[0, :, 0, :] # nvar, E
|
||||
|
||||
# # aggregate
|
||||
# out_prev = torch.mean(hiddens[-2][0, :, :, :], dim=1) # nvar, E
|
||||
# out = torch.concat((out, out_prev), dim=1) # nvar, E*2
|
||||
|
||||
# audio_embeddings = torch.mean(out, dim=0)
|
||||
audio_embeddings = out.flatten()
|
||||
# audio_embeddings = torch.mean(out[0, :, 0, :], dim=0) # take the [CLS]: [512]
|
||||
|
||||
# concat demo
|
||||
if sub_info is not None:
|
||||
ds_name, fn, root_prefix = sub_info
|
||||
sub_id = fn.split("_")[0]
|
||||
|
||||
# edge filename case for indian-fPCG
|
||||
if sub_id == 'subject':
|
||||
sub_id = fn
|
||||
# sub_id = fn.split(".")[0] # if it is indian-fPCG
|
||||
|
||||
with open("{}data/{}/demo.pkl".format(root_prefix, ds_name), 'rb') as f:
|
||||
demo_vec = pickle.load(f)[sub_id] # D
|
||||
demo_vec = torch.from_numpy(demo_vec).to(device)
|
||||
audio_embeddings = torch.concat((demo_vec, audio_embeddings)).flatten()
|
||||
|
||||
return audio_embeddings
|
||||
|
||||
def encode(self, x, device=torch.device('cpu')):
|
||||
# x: [bn, nvar, L]
|
||||
# calculate cwt
|
||||
bn, nvar, L = x.shape
|
||||
cwt_res = cwt_wrap(x.view(bn*nvar, L), 0.1, 64) # bn*nvar, 3, L, n_mels
|
||||
_, n_, new_L, n_scale = cwt_res.shape
|
||||
cwt_res = cwt_res.view(bn, nvar, n_, new_L, n_scale) # bn, nvar, 3, L, n_mels
|
||||
|
||||
# forward
|
||||
out = self.backbone.forward_all(cwt_res, hidden_out=False, device=device) # bn, nvar, P, E
|
||||
return out
|
||||
|
||||
def forward(self, x):
|
||||
pass
|
||||
|
||||
from ..baseline_models.crossvit.crossvit import *
|
||||
# model_apis.py
|
||||
|
||||
# ... (其他代码) ...
|
||||
|
||||
class CrossVitAPI(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.sampling_rate = 65
|
||||
|
||||
# 定义 CrossSignalViT 模型实例
|
||||
# 注意:CrossSignalViT 的 __init__ 方法中 self.vit 已经加载了预训练权重并冻结了。
|
||||
# 所以,理论上,我们在这里加载的外部权重文件应该是针对 CrossSignalViT 整体的,
|
||||
# 或者我们根本不需要从外部文件加载 self.vit 的部分,因为它已经在 CrossSignalViT 内部处理了。
|
||||
#
|
||||
# 假设 model_checkpoint_cross_freeze_vit100_99.pth 是整个 CrossSignalViT 训练后的权重。
|
||||
self.encoder = CrossSignalViT(device='cuda') # CrossSignalViT 内部会处理 self.vit 的预训练
|
||||
|
||||
weight_path_original = '../data/results/model_checkpoint_cross_freeze_vit100_99.pth'
|
||||
|
||||
actual_path_to_load = None
|
||||
local_weight_path = weight_path_original.replace("../", "")
|
||||
if os.path.isfile(local_weight_path):
|
||||
actual_path_to_load = local_weight_path
|
||||
print(f"Loading CrossVit weights from local path: {actual_path_to_load}")
|
||||
elif os.path.isfile(weight_path_original):
|
||||
actual_path_to_load = weight_path_original
|
||||
print(f"Loading CrossVit weights from original path: {actual_path_to_load}")
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
f"CrossVit weight file not found at '{local_weight_path}' or '{weight_path_original}'."
|
||||
)
|
||||
|
||||
print(f"Attempting to load weights for the entire CrossSignalViT model from: {actual_path_to_load}")
|
||||
# 加载的应该是整个 CrossSignalViT 的 state_dict
|
||||
loaded_full_model_stat_dict = torch.load(actual_path_to_load, map_location=torch.device('cpu'), weights_only=True)
|
||||
print("Full model weights loaded successfully. Attempting to load into self.encoder...")
|
||||
|
||||
try:
|
||||
# 直接加载,因为我们期望这个文件是 CrossSignalViT 完整的 state_dict
|
||||
self.encoder.load_state_dict(loaded_full_model_stat_dict)
|
||||
print("CrossVitAPI: Full model weights loaded into self.encoder successfully.")
|
||||
except RuntimeError as e:
|
||||
print(f"CrossVitAPI: Error loading full model state_dict into self.encoder: {e}")
|
||||
print("This might indicate a mismatch between the CrossSignalViT architecture and the checkpoint.")
|
||||
# 调试信息
|
||||
print("\nKeys expected by self.encoder (CrossSignalViT):")
|
||||
for k in self.encoder.state_dict().keys():
|
||||
print(f" - {k}")
|
||||
print("\nKeys in loaded_full_model_stat_dict:")
|
||||
for k in loaded_full_model_stat_dict.keys():
|
||||
print(f" - {k}")
|
||||
raise e
|
||||
|
||||
self.encoder = self.encoder.bfloat16()
|
||||
|
||||
# ... (get_embedding 和 forward 方法不变) ...
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=16000, device=torch.device('cpu')):
|
||||
# data: [nvar, L]
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
sample_data = torch.from_numpy(sample_data.astype(np.float32))
|
||||
|
||||
# resample
|
||||
if sampling_rate != self.sampling_rate:
|
||||
if sampling_rate > 256:
|
||||
resampler = T.Resample(sampling_rate, self.sampling_rate)
|
||||
sample_data = resampler(sample_data) # [nvar, L]
|
||||
|
||||
# calculate spectrogram
|
||||
spec = spec_cwt(sample_data.numpy()).float().unsqueeze(0).to(device) # [1, nvar, 3, L, n_mels]
|
||||
# ====================================================================
|
||||
|
||||
# forward
|
||||
# x: [1, nvar, 3, L, n_mels]
|
||||
# N, C, L, 65, 3
|
||||
out = self.encoder.forward_all(spec.bfloat16()) # 1, C, L, 768
|
||||
out = torch.mean(out, dim=2).float() # 1, C, 768
|
||||
|
||||
return out.flatten() # 768
|
||||
|
||||
def forward(self, x):
|
||||
pass
|
||||
@@ -0,0 +1,149 @@
|
||||
import os
|
||||
import sys
|
||||
import pickle
|
||||
import pandas as pd
|
||||
from .model_apis import *
|
||||
|
||||
DEVICE = torch.device('cuda:0') if torch.cuda.is_available() else torch.device("cpu")
|
||||
print("DEVICE:", DEVICE)
|
||||
|
||||
# ============= helper functions ================================================
|
||||
def load_model(model_name='stats', args=None):
|
||||
# all models should follows the function structure of AST_API
|
||||
if model_name == 'clap':
|
||||
model = CLAP_API()
|
||||
elif model_name == 'normwear':
|
||||
model = NormWear_API(weight_path=args.model_weight_dir)
|
||||
elif model_name == 'chronos':
|
||||
model = Chronos_API()
|
||||
# added baselines
|
||||
elif model_name == 'stats':
|
||||
model = STAT_API()
|
||||
elif model_name == 'tfc':
|
||||
model = TFC_API()
|
||||
elif model_name == 'demo':
|
||||
model = Demogr_API()
|
||||
elif model_name == 'crossvit':
|
||||
model = CrossVitAPI()
|
||||
else:
|
||||
print("Model not supported. ")
|
||||
exit()
|
||||
|
||||
# return
|
||||
model = model.to(DEVICE)
|
||||
model.eval()
|
||||
|
||||
# # check number of parameters
|
||||
# total_params = sum(p.numel() for p in model.parameters())
|
||||
# print(f"{model_name} Number of parameters: {total_params}")
|
||||
# exit()
|
||||
|
||||
return model
|
||||
|
||||
def audio_embedding_prepare(data_rootpath="audio_downstream/Coswara", model_name='ast', root_prefix="../", remark="", args=None):
|
||||
# construct model
|
||||
model = load_model(model_name=model_name, args=args)
|
||||
|
||||
save_remark = remark if len(remark) > 0 else model_name
|
||||
|
||||
# initialize folder for save all the embedding
|
||||
os.makedirs('{}data/{}/{}_wav_embed'.format(root_prefix, data_rootpath, save_remark), exist_ok=True)
|
||||
|
||||
# get embedding for each sample
|
||||
for fn in tqdm(sorted(os.listdir('{}data/{}/sample_for_downstream'.format(root_prefix, data_rootpath)))):
|
||||
# edge case
|
||||
if fn[0] == '.':
|
||||
continue
|
||||
|
||||
# load sample
|
||||
# read data
|
||||
with open(os.path.join('{}data/{}/sample_for_downstream'.format(root_prefix, data_rootpath), fn), 'rb') as f:
|
||||
sample = pickle.load(f) # ['uid', 'data', 'label', 'sampling_rate']
|
||||
|
||||
# expand 1 dimension if only single dimension
|
||||
if len(sample['data'].shape) == 1:
|
||||
sample['data'] = np.expand_dims(sample['data'], axis=0)
|
||||
|
||||
# test clap pipeline
|
||||
with torch.no_grad():
|
||||
# if model_name in["demo", "normwear"]:
|
||||
if model_name in["demo"]: # normal demographic test
|
||||
embed = model.get_embedding(
|
||||
sample['data'],
|
||||
sampling_rate=sample['sampling_rate'],
|
||||
device=DEVICE,
|
||||
sub_info=(data_rootpath, fn, root_prefix) # comment out if not demographic
|
||||
) # E
|
||||
else:
|
||||
embed = model.get_embedding(
|
||||
sample['data'],
|
||||
sampling_rate=sample['sampling_rate'],
|
||||
device=DEVICE,
|
||||
) # E
|
||||
|
||||
# # check
|
||||
# print(embed.shape)
|
||||
# print(torch.mean(embed))
|
||||
# # print(sample['label'])
|
||||
# exit()
|
||||
|
||||
# save the embedding
|
||||
with open(os.path.join('{}data/{}/{}_wav_embed'.format(root_prefix, data_rootpath, save_remark), fn), 'wb') as f:
|
||||
pickle.dump({
|
||||
"uid": sample["uid"],
|
||||
"sampling_rate": sample['sampling_rate'],
|
||||
"embed": embed.cpu().numpy().astype(np.float16), # E
|
||||
"label": sample['label']
|
||||
}, f)
|
||||
|
||||
def combine_normwear_ast(data_rootpath="audio_downstream/Coswara", root_prefix="../"):
|
||||
# initialize folder for save all the embedding
|
||||
os.makedirs('{}data/{}/nacombine_wav_embed'.format(root_prefix, data_rootpath), exist_ok=True)
|
||||
|
||||
# get embedding for each sample
|
||||
for fn in tqdm(sorted(os.listdir('{}data/{}/sample_for_downstream'.format(root_prefix, data_rootpath)))):
|
||||
# edge case
|
||||
if fn[0] == '.':
|
||||
continue
|
||||
|
||||
# load sample
|
||||
# read data
|
||||
with open(os.path.join('{}data/{}/sample_for_downstream'.format(root_prefix, data_rootpath), fn), 'rb') as f:
|
||||
sample = pickle.load(f) # ['uid', 'data', 'label', 'sampling_rate']
|
||||
|
||||
# TODO combine embeds
|
||||
with open(os.path.join('{}data/{}/normwear_wav_embed'.format(root_prefix, data_rootpath), fn), 'rb') as f:
|
||||
normwear_embed = pickle.load(f)["embed"]
|
||||
with open(os.path.join('{}data/{}/ast_wav_embed'.format(root_prefix, data_rootpath), fn), 'rb') as f:
|
||||
ast_embed = pickle.load(f)["embed"]
|
||||
embed = np.concatenate((normwear_embed, ast_embed), axis=0)
|
||||
|
||||
# # check
|
||||
# print(embed.shape)
|
||||
# print(np.mean(embed), np.std(embed), np.min(embed), np.max(embed))
|
||||
# exit()
|
||||
|
||||
# save the embedding
|
||||
with open(os.path.join('{}data/{}/nacombine_wav_embed'.format(root_prefix, data_rootpath), fn), 'wb') as f:
|
||||
pickle.dump({
|
||||
"uid": sample["uid"],
|
||||
"sampling_rate": sample['sampling_rate'],
|
||||
"embed": embed, # E*2
|
||||
"label": sample['label']
|
||||
}, f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
# python3 -m src.downstream.prepare_embeds chronos audio_downstream/KAUH
|
||||
# python3 -m src.downstream.prepare_embeds ast downstream/PPG_DM
|
||||
|
||||
# input model name
|
||||
model_name = sys.argv[1] # ast, clap, opera, normwear
|
||||
data_rootpath = sys.argv[2] # e.g. audio_downstream/KAUH
|
||||
|
||||
# process to get all embeds
|
||||
audio_embedding_prepare(model_name=model_name, data_rootpath=data_rootpath)
|
||||
|
||||
# # combine embeds
|
||||
# # python3 -m src.downstream.prepare_embeds audio_downstream/KAUH
|
||||
# data_rootpath = sys.argv[1] # e.g. audio_downstream/KAUH
|
||||
# combine_normwear_ast(data_rootpath=data_rootpath)
|
||||
@@ -0,0 +1,177 @@
|
||||
MODEL_LIST = ['ast', 'clap', 'opera', 'normwear', 'chronos']
|
||||
|
||||
CLASS_NUM = {
|
||||
"audio_downstream/KAUH": {
|
||||
"nums": [8],
|
||||
"names": ["single task"]
|
||||
},
|
||||
"audio_downstream/RespiratoryDatabase@TR": {
|
||||
"nums": [5],
|
||||
"names": ["single task"]
|
||||
},
|
||||
"audio_downstream/FSD50K": {
|
||||
"nums": [2 for _ in range(5)],
|
||||
"names": ["breathing", "cough", "laughter", "sneeze", "speech"]
|
||||
},
|
||||
"audio_downstream/NoseMic": {
|
||||
"nums": [2, 1],
|
||||
"ranges": [None, [1, 60]],
|
||||
"names": ["run_state", "resp_rate"]
|
||||
},
|
||||
"audio_downstream/Coswara": {
|
||||
"nums": [2 for _ in range(16)],
|
||||
"names": [
|
||||
"smoker",
|
||||
"cold",
|
||||
"ht",
|
||||
"diabetes",
|
||||
"cough",
|
||||
"diarrhoea",
|
||||
"fever",
|
||||
"loss_of_smell",
|
||||
"bd",
|
||||
"st",
|
||||
"ihd",
|
||||
"asthma",
|
||||
"cld",
|
||||
"pneumonia",
|
||||
"ftg",
|
||||
"mp",
|
||||
]
|
||||
},
|
||||
"audio_downstream/FluSense": {
|
||||
"nums": [2 for _ in range(7)],
|
||||
"names": [
|
||||
"sneeze",
|
||||
"sniffle",
|
||||
"cough",
|
||||
"gasp",
|
||||
"breathe",
|
||||
"speech",
|
||||
"throat-clearing"
|
||||
]
|
||||
},
|
||||
# ===== WEARABLE STARTING HERE ============================
|
||||
"wearable_downstream/PPG_HTN": {
|
||||
"nums": [4],
|
||||
"names": ["PPG_HTN"]
|
||||
},
|
||||
"wearable_downstream/ecg": {
|
||||
"nums": [9],
|
||||
"names": ["ecg"]
|
||||
},
|
||||
"wearable_downstream/PPG_DM": {
|
||||
"nums": [2],
|
||||
"names": ["PPG_DM"]
|
||||
},
|
||||
"wearable_downstream/PPG_CVA": {
|
||||
"nums": [2],
|
||||
"names": ["PPG_CVA"]
|
||||
},
|
||||
"wearable_downstream/PPG_CVD": {
|
||||
"nums": [3],
|
||||
"names": ["PPG_CVD"]
|
||||
},
|
||||
"wearable_downstream/indian-fPCG": {
|
||||
"nums": [1],
|
||||
"ranges": [[60, 200]],
|
||||
"names": ["indian-fPCG"]
|
||||
},
|
||||
"wearable_downstream/ppg_hgb": {
|
||||
"nums": [1],
|
||||
"ranges": [[1, 20]],
|
||||
"names": ["ppg_hgb"]
|
||||
},
|
||||
"wearable_downstream/non_invasive_bp": {
|
||||
"nums": [2],
|
||||
"ranges": [[-4, 3]],
|
||||
"names": ["non_invasive_bp"]
|
||||
},
|
||||
"wearable_downstream/drive_fatigue": {
|
||||
"nums": [2],
|
||||
"names": ["drive_fatigue"]
|
||||
},
|
||||
"wearable_downstream/ecg_heart_cat": {
|
||||
"nums": [2],
|
||||
"names": ["ecg_heart_cat"]
|
||||
},
|
||||
"wearable_downstream/gameemo": {
|
||||
"nums": [4],
|
||||
"names": ["gameemo"]
|
||||
},
|
||||
"wearable_downstream/uci_har": {
|
||||
"nums": [6],
|
||||
"names": ["uci_har"]
|
||||
},
|
||||
"wearable_downstream/wesad": {
|
||||
"nums": [3],
|
||||
"names": ["wesad"]
|
||||
},
|
||||
"wearable_downstream/Epilepsy": {
|
||||
"nums": [2 for _ in range(5)],
|
||||
"names": [
|
||||
"A_Z_eye_open",
|
||||
"B_O_eye_close",
|
||||
"C_N_health",
|
||||
"D_F_tumor",
|
||||
"E_S_seizure"
|
||||
]
|
||||
},
|
||||
"wearable_downstream/emg-tfc": {
|
||||
"nums": [3],
|
||||
"names": ["emg-tfc"]
|
||||
},
|
||||
"wearable_downstream/ecg-tfc": {
|
||||
"nums": [4],
|
||||
"names": ["ecg-tfc"]
|
||||
},
|
||||
# ===== CLINIC STARTING HERE ============================
|
||||
"clinic_data/swallow_data": {
|
||||
"nums": [3],
|
||||
"names": ["single task"]
|
||||
},
|
||||
"clinic_data/studentlife": { # every 6 hours as a unit, i.e. sr=6 (1 data point is of 1 hour)
|
||||
"nums": [3],
|
||||
"names": ["single task"]
|
||||
},
|
||||
"clinic_data/opioid_misuse": { # every 15 mins as an unit, i.e. sr=6 (1 data point is of 2.5 mins)
|
||||
"nums": [1, 1, 1, 2],
|
||||
"ranges": [[1, 11] for _ in range(3)],
|
||||
"names": [
|
||||
"stress",
|
||||
"pain",
|
||||
"craving",
|
||||
"misuse_risk"
|
||||
]
|
||||
},
|
||||
"clinic_data/IDH_risk": { # every 1 hour as a unit, i.e. sr=12 (1 data point is of 5 mins)
|
||||
"nums": [2 for _ in range(5)],
|
||||
"names": [
|
||||
"fall20",
|
||||
"fall30",
|
||||
"nadir90",
|
||||
"nadir100",
|
||||
"hemo"
|
||||
]
|
||||
},
|
||||
# ===== RADAR STARTING HERE ============================
|
||||
"radar_data/radar_9_subjects": { # every 1 hour as a unit, i.e. sr=12 (1 data point is of 5 mins)
|
||||
"nums": [1, 1, 2],
|
||||
"names": [
|
||||
"hr",
|
||||
"resp_r",
|
||||
"resp_abnormal"
|
||||
]
|
||||
},
|
||||
"radar_data/radar_30_subjects": { # every 1 hour as a unit, i.e. sr=12 (1 data point is of 5 mins)
|
||||
"nums": [5, 1, 1, 4, 1, 2],
|
||||
"names": [
|
||||
"action",
|
||||
"sysbp",
|
||||
"diabp",
|
||||
"bp_abnormal",
|
||||
"hr",
|
||||
"hr_abnormal"
|
||||
]
|
||||
},
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,131 @@
|
||||
from scipy import signal
|
||||
import torchaudio.transforms as T
|
||||
|
||||
from .modules.normwear import *
|
||||
|
||||
def wt(ts, lf=0.1, hf=65):
|
||||
# in: L
|
||||
# out: FxL
|
||||
cwtmatr = signal.cwt(ts, signal.ricker, np.arange(lf, hf))
|
||||
return cwtmatr #[F, L]
|
||||
|
||||
def spec_cwt(audio_data): # [nvar, L]
|
||||
x1 = audio_data[:, 1:] - audio_data[:, :-1]
|
||||
x2 = x1[:, 1:] - x1[:, :-1]
|
||||
|
||||
all_specs = list()
|
||||
for c_i in range(audio_data.shape[0]):
|
||||
all_specs.append(torch.stack([
|
||||
torch.from_numpy(wt(audio_data[c_i, 2:])).permute(1, 0), # [L, n_mels]
|
||||
torch.from_numpy(wt(x1[c_i, 1:])).permute(1, 0),
|
||||
torch.from_numpy(wt(x2[c_i])).permute(1, 0)
|
||||
])) # [3, L, n_mels]
|
||||
|
||||
all_specs = torch.stack(all_specs) # [nvar, 3, L, n_mels]
|
||||
|
||||
return all_specs
|
||||
|
||||
class NormWearModel(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
optimized_cwt=False,
|
||||
use_cwt=True,
|
||||
weight_path=""
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
# # weight path note
|
||||
# weight_path = '../data/results/model_mae_checkpoint-140.pth' # 37k
|
||||
# weight_path = '../data/results/NormWear_Large_checkpoint-10.pth' # 24w
|
||||
# weight_path = '../data/results/job_rand_maskv3_checkpoint-15470.pth' # 1.5Tb
|
||||
# 'modules/normwear_ckpt-15470.pth'
|
||||
|
||||
self.optimized_cwt = optimized_cwt
|
||||
|
||||
# construct encoder
|
||||
self.backbone = NormWear(img_size=(387,65), patch_size=(9,5),mask_scheme='random',mask_prob=0.8,use_cwt=use_cwt,nvar=4, comb_freq=False)
|
||||
|
||||
# load pretrained checkpoint
|
||||
if len(weight_path) > 0:
|
||||
try:
|
||||
stat_dict = torch.load(weight_path, map_location=torch.device('cpu'))['model']
|
||||
self.backbone.load_state_dict(stat_dict)
|
||||
print("Model Checkpoint is successfully loaded!")
|
||||
except:
|
||||
print("Error occur during loading checkpoint, please check.")
|
||||
|
||||
self.sampling_rate = 65
|
||||
|
||||
def get_embedding(self, sample_data, sampling_rate=65, device=torch.device('cpu')):
|
||||
# data: [bn, nvar, L]
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
sample_data = sample_data.astype(np.float32)
|
||||
|
||||
# resample
|
||||
if sampling_rate != self.sampling_rate:
|
||||
if sampling_rate > 256:
|
||||
resampler = T.Resample(sampling_rate, self.sampling_rate)
|
||||
|
||||
bn, nvar, L = sample_data.shape
|
||||
sample_data = resampler(sample_data.reshape(bn*nvar, L)) # [nvar*nvar, new_L]
|
||||
_, new_L = sample_data.shape
|
||||
sample_data = sample_data.reshape(bn, nvar, new_L) # [bn, nvar, new_L]
|
||||
|
||||
if torch.is_tensor(sample_data):
|
||||
sample_data = sample_data.numpy()
|
||||
|
||||
# calculate spectrogram
|
||||
spec = self.calc_cwt(sample_data, device=device).float() # [bn, nvar, 3, L, n_scales]
|
||||
# ====================================================================
|
||||
|
||||
# forward
|
||||
# out, hiddens = self.backbone.get_signal_embedding(spec.to(device), hidden_out=True, device=device) # bn, nvar, P, E
|
||||
# hidden: list([bn, nvar, P, E])
|
||||
|
||||
out = self.backbone.get_signal_embedding(spec.to(device), hidden_out=False, device=device) # bn, nvar, P, E
|
||||
|
||||
# keep all representations
|
||||
signal_embeddings = out # bn, nvar, P, E
|
||||
|
||||
# potential aggregation process
|
||||
# out = torch.mean(out[:, :, :, :], dim=2) # bn, nvar, E (take mean)
|
||||
# out = out[:, :, 0, :] # bn, nvar, E (take CLS)
|
||||
|
||||
# signal_embeddings = torch.mean(out, dim=0) # average over sensor channels
|
||||
# signal_embeddings = out.flatten() # concat all sensor channels
|
||||
|
||||
return signal_embeddings # raw: bn, nvar, P, E
|
||||
|
||||
def calc_cwt(self, x, device=torch.device('cpu')):
|
||||
# x: [bn, nvar, L]
|
||||
# return: # bn, nvar, 3, L, n_scales
|
||||
bn, nvar, L = x.shape
|
||||
|
||||
if self.optimized_cwt: # use the version implemented with pytorch
|
||||
if not torch.is_tensor(x):
|
||||
x = torch.from_numpy(x).to(device)
|
||||
# calculate cwt
|
||||
cwt_res = cwt_wrap(x.view(bn*nvar, L), 0.1, 64) # bn*nvar, 3, L, n_scales
|
||||
_, n_, new_L, n_scale = cwt_res.shape
|
||||
cwt_res = cwt_res.view(bn, nvar, n_, new_L, n_scale) # bn, nvar, 3, L, n_scales
|
||||
else: # vanilla CWT
|
||||
cwt_res = torch.stack([spec_cwt(sample) for sample in x]) # bn, nvar, 3, L, n_scales
|
||||
return cwt_res
|
||||
|
||||
def forward(self, x):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
device = torch.device('cpu')
|
||||
|
||||
# init model
|
||||
model = NormWearModel(weight_path='NormWear/modules/model_ckpts/NormWear_Large_checkpoint-10.pth', optimized_cwt=True).to(device)
|
||||
|
||||
# test I/O
|
||||
x = torch.rand(1, 8, 32).to(device) # 2 samples, 3 sensor, sequence length of 8
|
||||
y = model.get_embedding(x, sampling_rate=65, device=device) # bn, nvar, P, E
|
||||
|
||||
# log
|
||||
print("Input shape:", x.shape)
|
||||
print("Output shape:", y.shape)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,239 @@
|
||||
#head.py
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
import torch.nn.functional as F
|
||||
class SigmoidRange(nn.Module):
|
||||
def __init__(self, low, high):
|
||||
super().__init__()
|
||||
self.low, self.high = low, high
|
||||
# self.low, self.high = ranges
|
||||
def forward(self, x):
|
||||
# return sigmoid_range(x, self.low, self.high)
|
||||
return torch.sigmoid(x) * (self.high - self.low) + self.low
|
||||
|
||||
class RegressionHead(nn.Module):
|
||||
def __init__(self, n_vars, d_model, output_dim, head_dropout=0.1, y_range=None):
|
||||
super().__init__()
|
||||
self.y_range = y_range
|
||||
self.flatten = nn.Flatten(start_dim=1)
|
||||
self.dropout = nn.Dropout(head_dropout)
|
||||
self.linear = nn.Linear(n_vars*d_model, output_dim)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: [bs x nvars x num_patch x d_model]
|
||||
output: [bs x output_dim]
|
||||
"""
|
||||
x = x[:,:,0,:] # only consider the cls_token, x: bs x nvars x d_model
|
||||
x = self.flatten(x) # x: bs x nvars * d_model
|
||||
x = self.dropout(x) # 128 x 3072
|
||||
y = self.linear(x) # y: bs x output_dim
|
||||
if self.y_range: y = SigmoidRange(*self.y_range)(y)
|
||||
return y.squeeze()
|
||||
|
||||
|
||||
class ClassificationHead(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes, head_dropout=0.1):
|
||||
super().__init__()
|
||||
self.flatten = nn.Flatten(start_dim=1)
|
||||
self.dropout = nn.Dropout(head_dropout)
|
||||
self.linear = nn.Linear(n_vars*d_model, n_classes)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: [bs x nvars x num_patch x d_model]
|
||||
output: [bs x n_classes]
|
||||
"""
|
||||
x = x[:,:,0,:] # only consider the cls_token, x: bs x nvars x d_model
|
||||
x = self.flatten(x) # x: bs x nvars * d_model
|
||||
x = self.dropout(x)
|
||||
y = self.linear(x) # y: bs x n_classes
|
||||
|
||||
return y
|
||||
class MLPClassificationHead(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3):
|
||||
super().__init__()
|
||||
self.flatten = nn.Flatten(start_dim=1)
|
||||
|
||||
input_dim = n_vars * d_model
|
||||
hidden_dim = input_dim // hidden_dim_multiplier # 或者一个固定的值,例如 512, 1024
|
||||
|
||||
self.fc_stack = nn.Sequential(
|
||||
nn.Linear(input_dim, hidden_dim),
|
||||
nn.BatchNorm1d(hidden_dim), # 可选,但常用于MLP
|
||||
nn.ReLU(), # 或者 nn.GELU()
|
||||
nn.Dropout(head_dropout),
|
||||
nn.Linear(hidden_dim, n_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: [bs x nvars x num_patch x d_model]
|
||||
output: [bs x n_classes]
|
||||
"""
|
||||
x = x[:,:,0,:] # 仍然只考虑 cls_token
|
||||
x = self.flatten(x) # x: bs x nvars * d_model
|
||||
y = self.fc_stack(x)
|
||||
return y
|
||||
class MLPClassificationHeadWithMeanPatchPooling(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3):
|
||||
super().__init__()
|
||||
self.flatten_vars = nn.Flatten(start_dim=1) # 用于最后拼接不同变量的池化特征
|
||||
|
||||
# 输入到 MLP 的维度是 n_vars * d_model,因为每个变量的补丁池化后得到一个 d_model 维向量
|
||||
input_dim_to_mlp = n_vars * d_model
|
||||
hidden_dim = input_dim_to_mlp // hidden_dim_multiplier
|
||||
|
||||
self.fc_stack = nn.Sequential(
|
||||
nn.Linear(input_dim_to_mlp, hidden_dim),
|
||||
nn.BatchNorm1d(hidden_dim),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(head_dropout),
|
||||
nn.Linear(hidden_dim, n_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: [bs x nvars x num_patch x d_model]
|
||||
output: [bs x n_classes]
|
||||
"""
|
||||
# 1. 对每个变量的 num_patch 维度进行平均池化
|
||||
# x 的形状是 [bs, n_vars, num_patch, d_model]
|
||||
# 我们想在 dim=2 (num_patch 维度) 上进行平均池化
|
||||
pooled_patch_features_per_var = torch.mean(x, dim=2) # 结果形状: [bs, n_vars, d_model]
|
||||
|
||||
# 2. 展平/拼接不同变量的池化特征
|
||||
# pooled_patch_features_per_var 已经是 [bs, n_vars, d_model]
|
||||
# flatten_vars 会将其变为 [bs, n_vars * d_model]
|
||||
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
|
||||
|
||||
# 3. 通过 MLP 分类器
|
||||
y = self.fc_stack(flattened_aggregated_features)
|
||||
return y
|
||||
class AttentionPatchPooling(nn.Module):
|
||||
def __init__(self, d_model, num_heads=4):
|
||||
super().__init__()
|
||||
# 使用一个简单的线性层作为查询,或者一个可学习的参数
|
||||
self.query = nn.Parameter(torch.randn(1, d_model))
|
||||
# 或者更复杂的,例如一个小型MLP来生成查询
|
||||
# self.attention = nn.MultiheadAttention(d_model, num_heads, batch_first=True)
|
||||
# MultiheadAttention 可能对于单个变量内的补丁池化来说过于复杂,
|
||||
# 可以用更简单的点积注意力或加性注意力。
|
||||
|
||||
# 简化的加性注意力或缩放点积注意力
|
||||
self.W_k = nn.Linear(d_model, d_model, bias=False)
|
||||
self.W_q = nn.Linear(d_model, d_model, bias=False) # 如果查询是动态生成的
|
||||
self.W_v = nn.Linear(d_model, d_model, bias=False)
|
||||
self.temperature = np.sqrt(d_model)
|
||||
|
||||
def forward(self, patches_per_var):
|
||||
# patches_per_var: [bs, num_patch, d_model]
|
||||
bs, num_p, d = patches_per_var.shape
|
||||
|
||||
q = self.query.unsqueeze(0).expand(bs, -1, -1) # [bs, 1, d_model]
|
||||
# 或者 q = self.W_q(some_context_vector)
|
||||
|
||||
k = self.W_k(patches_per_var) # [bs, num_patch, d_model]
|
||||
v = self.W_v(patches_per_var) # [bs, num_patch, d_model]
|
||||
|
||||
attn_scores = torch.bmm(q, k.transpose(1, 2)) / self.temperature # [bs, 1, num_patch]
|
||||
attn_weights = F.softmax(attn_scores, dim=-1) # [bs, 1, num_patch]
|
||||
|
||||
context_vector = torch.bmm(attn_weights, v).squeeze(1) # [bs, d_model]
|
||||
return context_vector
|
||||
|
||||
class MLPClassificationHeadWithAttentionPatchPooling(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3, num_attn_heads_patch=1):
|
||||
super().__init__()
|
||||
self.n_vars = n_vars
|
||||
self.patch_poolers = nn.ModuleList(
|
||||
[AttentionPatchPooling(d_model, num_heads=num_attn_heads_patch) for _ in range(n_vars)]
|
||||
)
|
||||
self.flatten_vars = nn.Flatten(start_dim=1)
|
||||
|
||||
input_dim_to_mlp = n_vars * d_model
|
||||
hidden_dim = input_dim_to_mlp // hidden_dim_multiplier
|
||||
|
||||
self.fc_stack = nn.Sequential(
|
||||
nn.Linear(input_dim_to_mlp, hidden_dim),
|
||||
nn.BatchNorm1d(hidden_dim),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(head_dropout),
|
||||
nn.Linear(hidden_dim, n_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
# x: [bs, n_vars, num_patch, d_model]
|
||||
bs = x.size(0)
|
||||
pooled_features_list = []
|
||||
for i in range(self.n_vars):
|
||||
var_patches = x[:, i, :, :] # [bs, num_patch, d_model]
|
||||
pooled_features_list.append(self.patch_poolers[i](var_patches))
|
||||
|
||||
concatenated_features = torch.stack(pooled_features_list, dim=1) # [bs, n_vars, d_model]
|
||||
flattened_aggregated_features = self.flatten_vars(concatenated_features) # [bs, n_vars * d_model]
|
||||
|
||||
y = self.fc_stack(flattened_aggregated_features)
|
||||
return y
|
||||
|
||||
class DeeperMLPClassificationHeadWithMeanPatchPooling(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes,
|
||||
hidden_dims=[512, 256], # 定义多个隐藏层维度
|
||||
head_dropout=0.3, use_batchnorm=True):
|
||||
super().__init__()
|
||||
self.flatten_vars = nn.Flatten(start_dim=1)
|
||||
|
||||
input_dim_to_mlp = n_vars * d_model
|
||||
|
||||
layers = []
|
||||
current_dim = input_dim_to_mlp
|
||||
for h_dim in hidden_dims:
|
||||
layers.append(nn.Linear(current_dim, h_dim))
|
||||
if use_batchnorm:
|
||||
layers.append(nn.BatchNorm1d(h_dim))
|
||||
layers.append(nn.ReLU()) # 或者 nn.GELU()
|
||||
layers.append(nn.Dropout(head_dropout))
|
||||
current_dim = h_dim
|
||||
|
||||
layers.append(nn.Linear(current_dim, n_classes)) # 最后的输出层
|
||||
|
||||
self.fc_stack = nn.Sequential(*layers)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: [bs, n_vars, num_patch, d_model]
|
||||
output: [bs, n_classes]
|
||||
"""
|
||||
pooled_patch_features_per_var = torch.mean(x, dim=2)
|
||||
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
|
||||
y = self.fc_stack(flattened_aggregated_features)
|
||||
return y
|
||||
class MLPClassificationHeadWithMeanPatchPoolingAdjustable(nn.Module):
|
||||
def __init__(self, n_vars, d_model, n_classes,
|
||||
hidden_dim=768, # 直接指定隐藏层维度
|
||||
head_dropout=0.3 # 直接指定 Dropout 率
|
||||
):
|
||||
super().__init__()
|
||||
self.flatten_vars = nn.Flatten(start_dim=1)
|
||||
|
||||
input_dim_to_mlp = n_vars * d_model
|
||||
|
||||
# 确保 hidden_dim 是一个合理的值,例如,如果太小可能没有意义
|
||||
if hidden_dim <= 0:
|
||||
print(f"Warning: hidden_dim ({hidden_dim}) is not positive. Setting to a default value (e.g., 128 or input_dim_to_mlp // 4).")
|
||||
hidden_dim = max(128, input_dim_to_mlp // 4) # 示例默认值
|
||||
|
||||
self.fc_stack = nn.Sequential(
|
||||
nn.Linear(input_dim_to_mlp, hidden_dim),
|
||||
nn.BatchNorm1d(hidden_dim), # 考虑是否保留 BatchNorm
|
||||
nn.ReLU(),
|
||||
nn.Dropout(head_dropout),
|
||||
nn.Linear(hidden_dim, n_classes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
pooled_patch_features_per_var = torch.mean(x, dim=2)
|
||||
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
|
||||
y = self.fc_stack(flattened_aggregated_features)
|
||||
return y
|
||||
@@ -0,0 +1,21 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
import math
|
||||
|
||||
def adjust_learning_rate(optimizer, epoch, args):
|
||||
"""Decay the learning rate with half-cycle cosine after warmup"""
|
||||
if epoch < args.warmup_epochs:
|
||||
lr = args.lr * epoch / args.warmup_epochs
|
||||
else:
|
||||
lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \
|
||||
(1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))
|
||||
for param_group in optimizer.param_groups:
|
||||
if "lr_scale" in param_group:
|
||||
param_group["lr"] = lr * param_group["lr_scale"]
|
||||
else:
|
||||
param_group["lr"] = lr
|
||||
return lr
|
||||
@@ -0,0 +1,392 @@
|
||||
# normwear.py
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from timm.models.vision_transformer import Block
|
||||
|
||||
# Assuming pos_embed and patch_embed are in the same directory or accessible
|
||||
from .pos_embed import get_2d_sincos_pos_embed_flexible, get_1d_sincos_pos_embed_from_grid
|
||||
from .patch_embed import PatchEmbed_new, PatchEmbed_ts
|
||||
import torch.nn.functional as F
|
||||
|
||||
class Spatial_recon(nn.Module):
|
||||
def __init__(self, nvar=4, embed_dim=512, inter_dim=256):
|
||||
super(Spatial_recon, self).__init__()
|
||||
self.norm = nn.BatchNorm1d(nvar * embed_dim)
|
||||
self.conv1 = nn.Conv1d(in_channels=nvar * embed_dim, out_channels=inter_dim, kernel_size=1)
|
||||
self.conv2 = nn.Conv1d(in_channels=inter_dim, out_channels=nvar, kernel_size=1)
|
||||
self.gelu = nn.GELU()
|
||||
self.nvar = nvar
|
||||
def forward(self, x):
|
||||
_, E, L = x.shape
|
||||
x = torch.reshape(x,(-1,self.nvar*E,L))
|
||||
x = self.norm(x)
|
||||
x = self.conv1(x)
|
||||
x = self.gelu(x)
|
||||
x = self.conv2(x)
|
||||
return x
|
||||
|
||||
class EncoderLayer(nn.Module):
|
||||
def __init__(self,embed_dim = 768,
|
||||
norm_layer = nn.LayerNorm,
|
||||
num_heads=12,
|
||||
nvar = 4,
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
drop=0.1,
|
||||
fuse_frequency=2,
|
||||
curr_layer = 0,
|
||||
no_fusion=False,
|
||||
mean_fuse=False,):
|
||||
super().__init__()
|
||||
self.no_fusion = no_fusion
|
||||
self.mean_fuse = mean_fuse
|
||||
self.curr_layer = curr_layer
|
||||
self.fuse_frequency = fuse_frequency
|
||||
self.nvar = nvar
|
||||
self.variate_encoder = Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer)
|
||||
if self.curr_layer % self.fuse_frequency == 0:
|
||||
self.cls_fusion = Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias)
|
||||
|
||||
def forward(self,x):
|
||||
_, N, E = x.shape
|
||||
x_out = self.variate_encoder(x)
|
||||
if self.curr_layer % self.fuse_frequency == 0 and not self.no_fusion:
|
||||
x_out = torch.reshape(x_out, (-1,self.nvar, N, E))
|
||||
patch_tokens = x_out[:,:,1:,:]
|
||||
if self.mean_fuse:
|
||||
cls = x_out.mean(dim=2)
|
||||
else:
|
||||
cls = x_out[:,:,0,:]
|
||||
cls = self.cls_fusion(cls).unsqueeze(2)
|
||||
x_out = torch.cat((cls,patch_tokens),dim=2)
|
||||
bs, n_vars, N, E = x_out.shape
|
||||
x_out = torch.reshape(x_out,(bs*n_vars,N,E))
|
||||
return x_out
|
||||
|
||||
class NormWear(nn.Module):
|
||||
def __init__(self, img_size=(387,65), patch_size=(9,5), in_chans=3,
|
||||
target_len = 388,nvar=4,
|
||||
embed_dim=768, decoder_embed_dim=512,
|
||||
depth=12, num_heads=12,decoder_depth=2,
|
||||
mlp_ratio=4., norm_layer=nn.LayerNorm,
|
||||
fuse_freq=2,is_pretrain=True,
|
||||
mask_t_prob=0.6, mask_f_prob=0.5,
|
||||
mask_prob=0.8,mask_scheme='random', use_cwt=True,
|
||||
attn_score=False,
|
||||
comb_freq=False,
|
||||
no_fusion=False,
|
||||
mean_fuse=False,):
|
||||
super().__init__()
|
||||
self.attn_score = attn_score
|
||||
self.comb_freq = comb_freq
|
||||
if self.attn_score:
|
||||
self.attn_score_lst = []
|
||||
if use_cwt:
|
||||
self.patch_embed = PatchEmbed_new(img_size, patch_size, in_chans, embed_dim,stride=patch_size)
|
||||
else:
|
||||
self.patch_embed = PatchEmbed_ts(img_size[0],patch_size[0],embed_dim,stride=patch_size[0])
|
||||
num_patches = self.patch_embed.num_patches
|
||||
self.mask_t_prob = mask_t_prob
|
||||
self.mask_f_prob = mask_f_prob
|
||||
self.mask_scheme = mask_scheme
|
||||
self.use_cwt = use_cwt
|
||||
self.nvar = nvar
|
||||
self.embed_dim = embed_dim # Expose embed_dim
|
||||
if mask_scheme == 'random':
|
||||
self.mask_prob = mask_prob
|
||||
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
||||
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim), requires_grad=False)
|
||||
self.encoder_blocks = nn.ModuleList([
|
||||
EncoderLayer(embed_dim=embed_dim, norm_layer=norm_layer, num_heads=num_heads, mlp_ratio=mlp_ratio,
|
||||
drop=0.1, nvar=nvar, fuse_frequency=fuse_freq, curr_layer=i,
|
||||
no_fusion=no_fusion, mean_fuse=mean_fuse)
|
||||
for i in range(depth)])
|
||||
self.norm = norm_layer(embed_dim)
|
||||
self.encoder_depth = depth
|
||||
if is_pretrain:
|
||||
self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)
|
||||
self.target_len = target_len
|
||||
self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim))
|
||||
self.decoder_pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, decoder_embed_dim), requires_grad=False)
|
||||
self.decoder_blocks = nn.ModuleList([
|
||||
Block(dim=decoder_embed_dim,num_heads=8, mlp_ratio=mlp_ratio,norm_layer=norm_layer)
|
||||
for i in range(decoder_depth)])
|
||||
self.temporal_recon = nn.Linear(num_patches + 1,target_len)
|
||||
self.spatial_recon = Spatial_recon(nvar=nvar,embed_dim=decoder_embed_dim,inter_dim=embed_dim//2)
|
||||
self.decoder_norm = norm_layer(decoder_embed_dim)
|
||||
self.cosim = nn.CosineSimilarity(dim=-1, eps=1e-6)
|
||||
self.initialize_weights()
|
||||
|
||||
def initialize_weights(self):
|
||||
if self.use_cwt:
|
||||
pos_embed = get_2d_sincos_pos_embed_flexible(self.pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
|
||||
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
||||
if hasattr(self, 'decoder_pos_embed'):
|
||||
decoder_pos_embed = get_2d_sincos_pos_embed_flexible(self.decoder_pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
|
||||
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
||||
else:
|
||||
pos_embed = get_1d_sincos_pos_embed_from_grid(self.pos_embed.shape[-1],np.arange(self.pos_embed.shape[-2],dtype=np.float32))
|
||||
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
||||
if hasattr(self, 'decoder_pos_embed'):
|
||||
decoder_pos_embed = get_1d_sincos_pos_embed_from_grid(self.decoder_pos_embed.shape[-1],np.arange(self.decoder_pos_embed.shape[-2],dtype=np.float32))
|
||||
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
|
||||
torch.nn.init.normal_(self.cls_token, std=.02)
|
||||
if hasattr(self, 'mask_token'):
|
||||
torch.nn.init.normal_(self.mask_token, std=.02)
|
||||
self.apply(self._init_weights)
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, nn.Linear):
|
||||
torch.nn.init.xavier_uniform_(m.weight)
|
||||
if isinstance(m, nn.Linear) and m.bias is not None:
|
||||
nn.init.constant_(m.bias, 0)
|
||||
elif isinstance(m, nn.LayerNorm):
|
||||
nn.init.constant_(m.bias, 0)
|
||||
nn.init.constant_(m.weight, 1.0)
|
||||
|
||||
def pos_adjust(self, new_img_size, device=torch.device('cpu')):
|
||||
orig_size = self.patch_embed.patch_hw
|
||||
_, _, h, w = self.patch_embed.get_output_shape(new_img_size, device=device)
|
||||
new_size = (h, w)
|
||||
pos_embed_checkpoint = self.pos_embed
|
||||
embedding_size = pos_embed_checkpoint.shape[-1]
|
||||
num_extra_tokens = 1
|
||||
if orig_size != new_size:
|
||||
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
||||
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
||||
pos_tokens = pos_tokens.reshape(-1, orig_size[0], orig_size[1], embedding_size).permute(0, 3, 1, 2)
|
||||
pos_tokens = torch.nn.functional.interpolate(
|
||||
pos_tokens, size=(new_size[0], new_size[1]), mode='bicubic', align_corners=False)
|
||||
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
||||
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
||||
return new_pos_embed
|
||||
return self.pos_embed
|
||||
|
||||
def combine_freq_patch(self, x):
|
||||
N, nvar, L_plus_1, E = x.shape
|
||||
clss = x[:, :, :1, :]
|
||||
patch_tokens = x[:, :, 1:, :]
|
||||
L = patch_tokens.shape[2]
|
||||
F = self.patch_embed.patch_hw[1]
|
||||
T = L // F
|
||||
patch_tokens = patch_tokens.view(N, nvar, T, F, E)
|
||||
patch_tokens = torch.sum(patch_tokens, dim=3)
|
||||
return torch.cat((clss, patch_tokens), dim=2)
|
||||
|
||||
# @torch.no_grad() # 暂时在 no_grad 下运行以隔离问题
|
||||
def get_signal_embedding(self, x, hidden_out=False, device=torch.device('cpu')):
|
||||
"""
|
||||
Extracts signal embeddings from the backbone.
|
||||
This version includes extensive debugging checks to trace NaN/Inf issues.
|
||||
"""
|
||||
# --- 0. 初始输入检查 ---
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print("!!! FATAL: NaN/Inf found in the raw input tensor 'x' passed to get_signal_embedding !!!")
|
||||
# 在这里可以打印更多关于 x 的信息
|
||||
print(f"Input shape: {x.shape}")
|
||||
# 为了防止程序崩溃,可以尝试清理,但这表明上游数据处理有问题
|
||||
x = torch.nan_to_num(x, nan=0.0, posinf=0.0, neginf=0.0)
|
||||
|
||||
N, nvar, ch, L, F_ = x.shape
|
||||
|
||||
# --- 1. 检查 patch_embed 模块的权重 ---
|
||||
proj_weight = self.patch_embed.proj.weight
|
||||
if not torch.all(torch.isfinite(proj_weight)):
|
||||
print("!!! FATAL: NaN/Inf found in patch_embed layer weights !!! This is likely due to unstable training (e.g., high learning rate).")
|
||||
# 打印权重统计信息以帮助诊断
|
||||
print(f"Weight stats: min={proj_weight.min().item()}, max={proj_weight.max().item()}, mean={proj_weight.mean().item()}, std={proj_weight.std().item()}")
|
||||
# 在这里退出可能是最好的选择,因为模型权重已经损坏
|
||||
raise RuntimeError("Corrupted weights in patch_embed layer.")
|
||||
|
||||
# --- 2. 执行 patch_embed ---
|
||||
x_reshaped = torch.reshape(x, (N*nvar, ch, L, F_))
|
||||
x = self.patch_embed(x_reshaped) # x shape: [N*nvar, P, E]
|
||||
|
||||
# --- 3. 检查 patch_embed 之后的输出 ---
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print("!!! FATAL: NaN/Inf generated immediately after patch_embed layer !!!")
|
||||
# 这通常意味着输入值乘以权重后发生了溢出(在 float16 中尤其常见)
|
||||
print(f"Input to patch_embed had shape: {x_reshaped.shape}")
|
||||
print(f"Input stats: min={x_reshaped.min().item()}, max={x_reshaped.max().item()}, mean={x_reshaped.mean().item()}")
|
||||
raise RuntimeError("NaN/Inf generated by patch_embed layer.")
|
||||
|
||||
# --- 4. 检查并应用位置编码 ---
|
||||
pos_embed = self.pos_adjust((L, F_), device=device)
|
||||
if not torch.all(torch.isfinite(pos_embed)):
|
||||
print("!!! FATAL: NaN/Inf found in position embeddings !!!")
|
||||
raise RuntimeError("Corrupted position embeddings.")
|
||||
|
||||
x = x + pos_embed[:, 1:, :]
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print("!!! FATAL: NaN/Inf generated after adding position embeddings !!!")
|
||||
raise RuntimeError("NaN/Inf after adding position embeddings.")
|
||||
|
||||
# --- 5. 检查并添加CLS token ---
|
||||
cls_token = self.cls_token + pos_embed[:, :1, :]
|
||||
if not torch.all(torch.isfinite(cls_token)):
|
||||
print("!!! FATAL: NaN/Inf found in CLS token !!!")
|
||||
raise RuntimeError("Corrupted CLS token.")
|
||||
|
||||
cls_tokens = cls_token.expand(x.shape[0], -1, -1)
|
||||
x = torch.cat((cls_tokens, x), dim=1)
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print("!!! FATAL: NaN/Inf generated after concatenating CLS token !!!")
|
||||
raise RuntimeError("NaN/Inf after concatenating CLS token.")
|
||||
|
||||
# --- 6. 逐层检查 Transformer Encoder ---
|
||||
hiddens = list()
|
||||
for i, blk in enumerate(self.encoder_blocks):
|
||||
blk.nvar = nvar
|
||||
x = blk(x)
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print(f"!!! FATAL: NaN/Inf generated by Encoder block {i} !!!")
|
||||
# 这通常指向自注意力或MLP块中的数值不稳定
|
||||
raise RuntimeError(f"NaN/Inf from Encoder block {i}.")
|
||||
|
||||
if hidden_out:
|
||||
BN, P, E = x.shape
|
||||
curr_hidden = torch.reshape(x,(BN//nvar, nvar, P, E))
|
||||
if self.comb_freq:
|
||||
curr_hidden = self.combine_freq_patch(curr_hidden)
|
||||
hiddens.append(curr_hidden)
|
||||
|
||||
# --- 7. 检查最后的 LayerNorm ---
|
||||
x = self.norm(x)
|
||||
if not torch.all(torch.isfinite(x)):
|
||||
print("!!! FATAL: NaN/Inf generated by the final LayerNorm !!!")
|
||||
raise RuntimeError("NaN/Inf from final LayerNorm.")
|
||||
|
||||
# --- 8. 最后的塑形和返回 ---
|
||||
BN, P, E = x.shape
|
||||
x = torch.reshape(x,(BN//nvar, nvar, P, E))
|
||||
|
||||
if self.comb_freq:
|
||||
x = self.combine_freq_patch(x)
|
||||
|
||||
if hidden_out:
|
||||
return x, hiddens
|
||||
return x
|
||||
|
||||
# --- MoCo CLASS WITH DEBUGGING ASSERTIONS ---
|
||||
class MoCo(nn.Module):
|
||||
def __init__(self, base_encoder_class, dim=128, K=65536, m=0.999, T=0.07, mlp=True, **kwargs):
|
||||
super(MoCo, self).__init__()
|
||||
self.K = K
|
||||
self.m = m
|
||||
self.T = T
|
||||
self.encoder_q = base_encoder_class(is_pretrain=False, **kwargs)
|
||||
self.encoder_k = base_encoder_class(is_pretrain=False, **kwargs)
|
||||
encoder_dim = self.encoder_q.embed_dim
|
||||
if mlp:
|
||||
self.projector_q = nn.Sequential(nn.Linear(encoder_dim, encoder_dim), nn.ReLU(), nn.Linear(encoder_dim, dim))
|
||||
self.projector_k = nn.Sequential(nn.Linear(encoder_dim, encoder_dim), nn.ReLU(), nn.Linear(encoder_dim, dim))
|
||||
else:
|
||||
self.projector_q = nn.Identity()
|
||||
self.projector_k = nn.Identity()
|
||||
for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()):
|
||||
param_k.data.copy_(param_q.data)
|
||||
param_k.requires_grad = False
|
||||
for param_q, param_k in zip(self.projector_q.parameters(), self.projector_k.parameters()):
|
||||
param_k.data.copy_(param_q.data)
|
||||
param_k.requires_grad = False
|
||||
self.register_buffer("queue", torch.randn(dim, K))
|
||||
self.queue = nn.functional.normalize(self.queue, dim=0,eps=1e-2)
|
||||
self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long))
|
||||
|
||||
@torch.no_grad()
|
||||
def _momentum_update_key_encoder(self):
|
||||
for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()):
|
||||
param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)
|
||||
for param_q, param_k in zip(self.projector_q.parameters(), self.projector_k.parameters()):
|
||||
param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)
|
||||
|
||||
@torch.no_grad()
|
||||
def _dequeue_and_enqueue(self, keys):
|
||||
# gather keys before updating queue
|
||||
keys = concat_all_gather(keys)
|
||||
|
||||
batch_size = keys.shape[0]
|
||||
ptr = int(self.queue_ptr)
|
||||
|
||||
# --- ROBUST QUEUE UPDATE LOGIC ---
|
||||
# This logic handles cases where batch_size is not a divisor of K,
|
||||
# and correctly wraps around the queue pointer.
|
||||
|
||||
# 1. Determine the indices to replace in the queue
|
||||
# If ptr + batch_size exceeds the queue size, we need to wrap around.
|
||||
if ptr + batch_size > self.K:
|
||||
# Part 1: Fill from ptr to the end of the queue
|
||||
part1_len = self.K - ptr
|
||||
self.queue[:, ptr:] = keys[:part1_len].T
|
||||
|
||||
# Part 2: Fill from the beginning of the queue
|
||||
part2_len = batch_size - part1_len
|
||||
self.queue[:, :part2_len] = keys[part1_len:].T
|
||||
|
||||
# Update the pointer
|
||||
ptr = part2_len
|
||||
else:
|
||||
# The common case: no wrap-around needed
|
||||
self.queue[:, ptr:ptr + batch_size] = keys.T
|
||||
|
||||
# Update the pointer
|
||||
ptr = (ptr + batch_size) % self.K # Use modulo for safety, will be 0 if ptr + batch_size == K
|
||||
|
||||
self.queue_ptr[0] = ptr
|
||||
def forward(self, im_q, im_k):
|
||||
# 1. Compute query features
|
||||
q_feat = self.encoder_q.get_signal_embedding(im_q, device=im_q.device)
|
||||
q_cls = q_feat[:, :, 0, :]
|
||||
q_cls = torch.mean(q_cls, dim=1)
|
||||
q = self.projector_q(q_cls)
|
||||
q = nn.functional.normalize(q, dim=1, p=2, eps=1e-12) # Add eps for stability
|
||||
|
||||
assert torch.all(torch.isfinite(q)), "NaN/Inf in query features 'q' after normalization"
|
||||
|
||||
# 2. Compute key features
|
||||
with torch.no_grad():
|
||||
self._momentum_update_key_encoder()
|
||||
k_feat = self.encoder_k.get_signal_embedding(im_k, device=im_k.device)
|
||||
k_cls = k_feat[:, :, 0, :]
|
||||
k_cls = torch.mean(k_cls, dim=1)
|
||||
k = self.projector_k(k_cls)
|
||||
k = nn.functional.normalize(k, dim=1, p=2, eps=1e-12) # Add eps for stability
|
||||
|
||||
assert torch.all(torch.isfinite(k)), "NaN/Inf in key features 'k' after normalization"
|
||||
|
||||
# 3. Compute logits
|
||||
l_pos = torch.einsum('nc,nc->n', [q, k]).unsqueeze(-1)
|
||||
|
||||
assert torch.all(torch.isfinite(self.queue)), "NaN/Inf found in the negative queue"
|
||||
|
||||
l_neg = torch.einsum('nc,ck->nk', [q, self.queue.clone().detach()])
|
||||
|
||||
assert torch.all(torch.isfinite(l_pos)), "NaN/Inf in positive logits"
|
||||
assert torch.all(torch.isfinite(l_neg)), "NaN/Inf in negative logits"
|
||||
|
||||
logits = torch.cat([l_pos, l_neg], dim=1)
|
||||
logits /= self.T
|
||||
|
||||
assert torch.all(torch.isfinite(logits)), "NaN/Inf in final logits after temperature scaling"
|
||||
|
||||
# 4. Loss calculation
|
||||
labels = torch.zeros(logits.shape[0], dtype=torch.long).to(logits.device)
|
||||
loss = F.cross_entropy(logits, labels)
|
||||
|
||||
# 5. Dequeue and enqueue (only if loss is finite)
|
||||
if torch.isfinite(loss):
|
||||
self._dequeue_and_enqueue(k)
|
||||
|
||||
return loss, q, k
|
||||
|
||||
@torch.no_grad()
|
||||
def concat_all_gather(tensor):
|
||||
if not torch.distributed.is_available() or not torch.distributed.is_initialized():
|
||||
return tensor
|
||||
|
||||
tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())]
|
||||
torch.distributed.all_gather(tensors_gather, tensor, async_op=False)
|
||||
output = torch.cat(tensors_gather, dim=0)
|
||||
return output
|
||||
@@ -0,0 +1,135 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from .pos_embed import tAPE
|
||||
from torch.cuda.amp import autocast
|
||||
from timm.models.layers import to_2tuple
|
||||
|
||||
class PatchEmbed_new(nn.Module):
|
||||
""" Flexible Image to Patch Embedding
|
||||
"""
|
||||
def __init__(self, img_size=224,
|
||||
patch_size=16,
|
||||
in_chans=3,
|
||||
embed_dim=768,
|
||||
stride=16,
|
||||
dropout=0.1, # position_embed params
|
||||
scale_factor=1.0,
|
||||
use_tAPE=False):
|
||||
super().__init__()
|
||||
|
||||
'''
|
||||
For pretrain:
|
||||
we fixed img_size to be (387,65)
|
||||
thereby using patch_size (9,5)
|
||||
yielding 43 * 13 = 559 patches
|
||||
'''
|
||||
|
||||
'''
|
||||
for downstream task,
|
||||
resize
|
||||
'''
|
||||
|
||||
img_size = to_2tuple(img_size)
|
||||
patch_size = to_2tuple(patch_size)
|
||||
stride = to_2tuple(stride)
|
||||
|
||||
self.use_tAPE = use_tAPE
|
||||
self.img_size = img_size
|
||||
self.patch_size = patch_size
|
||||
|
||||
|
||||
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
|
||||
_, _, h, w = self.get_output_shape(img_size) # n, emb_dim, h, w
|
||||
self.patch_hw = (h, w)
|
||||
|
||||
self.num_patches = h*w
|
||||
if use_tAPE:
|
||||
self.time_pos_embed = tAPE(d_model=embed_dim, max_len=h,
|
||||
dropout=dropout,scale_factor=scale_factor)
|
||||
|
||||
def get_output_shape(self, img_size, device=torch.device('cpu')):
|
||||
# todo: don't be lazy..
|
||||
return self.proj(torch.randn(1,3,img_size[0],img_size[1]).to(device)).shape
|
||||
|
||||
def forward(self, x):
|
||||
B, C, H, W = x.shape
|
||||
|
||||
# --- [修复] 强制在 float32 下执行卷积 ---
|
||||
# 即使外部的 autocast 上下文是 float16,
|
||||
# 这个内部的上下文也会覆盖它,强制 self.proj 在 float32 下计算。
|
||||
with autocast(enabled=True, dtype=torch.float32):
|
||||
x = self.proj(x.float()) # 确保输入也是 float32
|
||||
# --- [修复结束] ---
|
||||
|
||||
if self.use_tAPE:
|
||||
x = self.time_pos_embed(x)
|
||||
x = x.flatten(2)
|
||||
x = x.transpose(1, 2)
|
||||
return x
|
||||
|
||||
|
||||
|
||||
|
||||
class PatchEmbed_ts(nn.Module):
|
||||
""" Flexible Image to Patch Embedding
|
||||
"""
|
||||
def __init__(self, ts_len=387,
|
||||
patch_size=9,
|
||||
embed_dim=768,
|
||||
stride=9,
|
||||
dropout=0.1, # position_embed params
|
||||
scale_factor=1.0,):
|
||||
super().__init__()
|
||||
|
||||
'''
|
||||
For pretrain:
|
||||
we fix length and nvar -> bs*nvar x L = bs *4 x 388
|
||||
'''
|
||||
|
||||
self.ts_len = ts_len
|
||||
self.patch_size = patch_size
|
||||
|
||||
|
||||
self.proj = conv1d_layer = nn.Conv1d(in_channels=1,out_channels=embed_dim,kernel_size=patch_size,stride=patch_size)
|
||||
|
||||
|
||||
bs, E, P = self.get_output_shape(ts_len) # n, emb_dim, P
|
||||
|
||||
self.patch_hw = patch_size
|
||||
self.num_patches = P
|
||||
|
||||
def get_output_shape(self, ts_len):
|
||||
# todo: don't be lazy..
|
||||
return self.proj(torch.randn(1,1,ts_len)).shape # bs, num_parches, L
|
||||
|
||||
def forward(self, x):
|
||||
bs, L = x.shape
|
||||
x = x.unsqueeze(1) # bs, 1, L
|
||||
|
||||
x = self.proj(x) # bs,E,L
|
||||
x = x.permute(0, 2, 1) # bs, L, E
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# patch_emb = PatchEmbed_new(img_size=(387,65), patch_size=(9,5), in_chans=3, embed_dim=64, stride=(9,5))
|
||||
# input = torch.rand(8,3,387,65)
|
||||
# output = patch_emb(input)
|
||||
# print(output.shape) # (8,559,64)
|
||||
|
||||
# patch_emb = PatchEmbed3D_new(video_size=(6,224,224), patch_size=(2,16,16), in_chans=3, embed_dim=768, stride=(2,16,16))
|
||||
# input = torch.rand(8,3,6,224,224)
|
||||
# output = patch_emb(input)
|
||||
#print(output.shape) # (8,64)
|
||||
|
||||
patch_emb = PatchEmbed_ts(ts_len=387,patch_size=9,stride=9)
|
||||
input = torch.randn(6,387)
|
||||
output = patch_emb(input)
|
||||
print(output.shape)
|
||||
print(patch_emb.patch_size)
|
||||
@@ -0,0 +1,112 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
|
||||
# fix time position embedding
|
||||
class tAPE(nn.Module):
|
||||
def __init__(self, d_model, dropout=0.1, max_len=43, scale_factor=1.0):
|
||||
super(tAPE, self).__init__()
|
||||
'''Modifying original tAPE
|
||||
adding time position embedding to 2d patches before flatten to 1d token
|
||||
Add along H by broadcasting W
|
||||
'''
|
||||
self.dropout = nn.Dropout(p=dropout)
|
||||
pe = torch.zeros(max_len, d_model) # positional encoding
|
||||
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
||||
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
||||
|
||||
pe[:, 0::2] = torch.sin((position * div_term)*(d_model/max_len))
|
||||
pe[:, 1::2] = torch.cos((position * div_term)*(d_model/max_len))
|
||||
|
||||
pe = scale_factor * pe.unsqueeze(0).unsqueeze(-1).permute(0, 2, 1, 3) # pe: L,E -> 1,E,1,L
|
||||
self.register_buffer('pe', pe) # this stores the variable in the state_dict (used for non-trainable variables)
|
||||
|
||||
def forward(self, x):
|
||||
"""Inputs of forward function
|
||||
Args:
|
||||
x: the sequence fed to the positional encoder model (required).
|
||||
Shape:
|
||||
x: [batch size*nvars, embed_dim, time length, frequency length]
|
||||
output: [batch size*nvars, embed_dim, time length, frequency length]
|
||||
"""
|
||||
|
||||
x = x + self.pe[:, :, :x.size(2), :]
|
||||
return self.dropout(x)
|
||||
|
||||
|
||||
# fix position embedding
|
||||
def get_2d_sincos_pos_embed_flexible(embed_dim, grid_size, cls_token=False):
|
||||
"""
|
||||
grid_size: int of the grid height and width
|
||||
return:
|
||||
pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
||||
"""
|
||||
grid_h = np.arange(grid_size[0], dtype=np.float32)
|
||||
grid_w = np.arange(grid_size[1], dtype=np.float32)
|
||||
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
||||
grid = np.stack(grid, axis=0)
|
||||
|
||||
grid = grid.reshape([2, 1, grid_size[0], grid_size[1]])
|
||||
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
||||
if cls_token:
|
||||
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
||||
return pos_embed
|
||||
|
||||
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
||||
assert embed_dim % 2 == 0
|
||||
|
||||
# use half of dimensions to encode grid_h
|
||||
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
||||
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
||||
|
||||
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
||||
return emb
|
||||
|
||||
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
||||
"""
|
||||
embed_dim: output dimension for each position
|
||||
pos: a list of positions to be encoded: size (M,)
|
||||
out: (M, D)
|
||||
"""
|
||||
assert embed_dim % 2 == 0
|
||||
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
||||
omega /= embed_dim / 2.
|
||||
omega = 1. / 10000**omega # (D/2,)
|
||||
|
||||
pos = pos.reshape(-1) # (M,)
|
||||
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
||||
|
||||
emb_sin = np.sin(out) # (M, D/2)
|
||||
emb_cos = np.cos(out) # (M, D/2)
|
||||
|
||||
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
||||
return emb
|
||||
|
||||
def interpolate_pos_embed(model, checkpoint_model,orig_size=(43,13),new_size=(43,13)):
|
||||
'''
|
||||
Input: model: the class is definging for downstream
|
||||
checkpoint_model: pre-train weight
|
||||
orig_size = (old_num_time_patches,old_num_freq_patches) = (43,13)
|
||||
'''
|
||||
|
||||
if 'pos_embed' in checkpoint_model:
|
||||
pos_embed_checkpoint = checkpoint_model['pos_embed'] # 1 x 560 x 768 (1 x num_patches x E)
|
||||
embedding_size = pos_embed_checkpoint.shape[-1] # 768
|
||||
|
||||
# number of special tokens (e.g. in this case num_extra_tokens = 1 for the cls token)
|
||||
num_patches = model.patch_embed.num_patches
|
||||
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
|
||||
|
||||
if orig_size != new_size:
|
||||
print("Position interpolate from %dx%d to %dx%d" % (orig_size[0], orig_size[1], new_size[0], new_size[1]))
|
||||
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
||||
# only the position tokens are interpolated
|
||||
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] # old positions
|
||||
pos_tokens = pos_tokens.reshape(-1, orig_size[0], orig_size[1], embedding_size).permute(0, 3, 1, 2)
|
||||
pos_tokens = torch.nn.functional.interpolate(
|
||||
pos_tokens, size=(new_size[0], new_size[1]), mode='bicubic', align_corners=False)
|
||||
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
||||
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
||||
checkpoint_model['pos_embed'] = new_pos_embed
|
||||
Binary file not shown.
@@ -0,0 +1,259 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
# --------------------------------------------------------
|
||||
# References:
|
||||
# DeiT: https://github.com/facebookresearch/deit
|
||||
# BEiT: https://github.com/microsoft/unilm/tree/master/beit
|
||||
# --------------------------------------------------------
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import numpy as np
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
import torch
|
||||
import torch.backends.cudnn as cudnn
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from .pretrain_pipeline.misc import get_next_run_number
|
||||
import timm.optim.optim_factory as optim_factory
|
||||
|
||||
from .pretrain_pipeline import misc
|
||||
from .pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
||||
|
||||
from .modules.normwear import *
|
||||
|
||||
from .pretrain_pipeline.engine_pretrain import train_one_epoch
|
||||
from .pretrain_pipeline.dataset import PretrainDataset,collate_fn,DataLoader
|
||||
|
||||
def get_args_parser():
|
||||
parser = argparse.ArgumentParser('MAE pre-training', add_help=False)
|
||||
parser.add_argument('--batch_size', default=4, type=int,
|
||||
help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
|
||||
parser.add_argument('--epochs', default=400, type=int)
|
||||
parser.add_argument('--accum_iter', default=1, type=int,
|
||||
help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)')
|
||||
parser.add_argument('--remark', default='model_mae',
|
||||
help='model_remark')
|
||||
parser.add_argument('--save_every_epoch', default=20, type=int,
|
||||
help='default: save every 20 epoches')
|
||||
|
||||
# Model parameters
|
||||
parser.add_argument('--model', default='mae_vit_base_patch16', type=str, metavar='MODEL',
|
||||
help='Name of model to train')
|
||||
|
||||
parser.add_argument('--img_size', default=(387, 65), nargs=2, type=int, help='images input size')
|
||||
parser.add_argument('--patch_size', type=int, default=(9,5), nargs=2,help='Patch size')
|
||||
parser.add_argument('--in_chans', type=int, default=3, help='Number of input channels')#修改为1用来测试
|
||||
parser.add_argument('--target_len', type=int, default=388, help='Target length')
|
||||
parser.add_argument('--nvar', type=int, default=4, help='Number of variables')
|
||||
parser.add_argument('--embed_dim', type=int, default=768, help='Embedding dimension')
|
||||
parser.add_argument('--decoder_embed_dim', type=int, default=512, help='Decoder embedding dimension')
|
||||
parser.add_argument('--depth', type=int, default=12, help='Depth of the transformer')
|
||||
parser.add_argument('--num_heads', type=int, default=12, help='Number of heads in the multi-head attention')
|
||||
parser.add_argument('--decoder_depth', type=int, default=2, help='Depth of the decoder')
|
||||
parser.add_argument('--mlp_ratio', type=float, default=4.0, help='MLP ratio')
|
||||
parser.add_argument('--fuse_freq', type=int, default=2, help='Frequency of fusing')
|
||||
parser.add_argument('--is_pretrain', type=bool, default=True, help='Pretrain flag')
|
||||
parser.add_argument('--mask_t_prob', type=float, default=0.6, help='Masking probability for time')
|
||||
parser.add_argument('--mask_f_prob', type=float, default=0.5, help='Masking probability for frequency')
|
||||
parser.add_argument('--mask_prob', type=float, default=0.8, help='Overall masking probability')
|
||||
parser.add_argument('--mask_scheme', type=str, default='random', help='Masking scheme')
|
||||
parser.add_argument('--use_cwt',type=bool,default=True,help='use cwt as input or ts')
|
||||
parser.add_argument('--use_meanpooling',type=int,default=0,help='use meanpooling for fusion')
|
||||
|
||||
|
||||
|
||||
# Optimizer parameters
|
||||
parser.add_argument('--weight_decay', type=float, default=0.05,
|
||||
help='weight decay (default: 0.05)')
|
||||
|
||||
parser.add_argument('--lr', type=float, default=None, metavar='LR',
|
||||
help='learning rate (absolute lr)')
|
||||
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR',
|
||||
help='base learning rate: absolute_lr = base_lr * total_batch_size / 256')
|
||||
parser.add_argument('--min_lr', type=float, default=0., metavar='LR',
|
||||
help='lower lr bound for cyclic schedulers that hit 0')
|
||||
|
||||
parser.add_argument('--warmup_epochs', type=int, default=10, metavar='N',
|
||||
help='epochs to warmup LR')
|
||||
|
||||
|
||||
# Dataset parameters
|
||||
parser.add_argument('--data_path', default='data/pretrain', type=str,
|
||||
help='dataset path')
|
||||
parser.add_argument('--output_dir', default="../data/results", type=str)
|
||||
parser.add_argument('--log_dir', default='../data/results/log',
|
||||
help='path where to tensorboard log')
|
||||
parser.add_argument('--device', default='cuda',
|
||||
help='device to use for training / testing')
|
||||
parser.add_argument('--seed', default=42, type=int)
|
||||
parser.add_argument('--resume', default='',
|
||||
help='resume from checkpoint')
|
||||
parser.add_argument('--is_test', default=0, type=int) # 0 for False, 1 for True
|
||||
|
||||
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
|
||||
help='start epoch')
|
||||
parser.add_argument('--num_workers', default=0, type=int)
|
||||
parser.add_argument('--pin_mem', action='store_true',
|
||||
help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
|
||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
||||
parser.set_defaults(pin_mem=True)
|
||||
|
||||
# distributed training parameters
|
||||
parser.add_argument('--world_size', default=1, type=int,
|
||||
help='number of distributed processes')
|
||||
parser.add_argument('--local_rank', default=-1, type=int)
|
||||
parser.add_argument('--dist_on_itp', action='store_true')
|
||||
parser.add_argument('--dist_url', default='env://',
|
||||
help='url used to set up distributed training')
|
||||
return parser
|
||||
|
||||
|
||||
def main(args):
|
||||
misc.init_distributed_mode(args)
|
||||
print('======================= starting pretrain =======================')
|
||||
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
|
||||
print("{}".format(args).replace(', ', ',\n'))
|
||||
|
||||
device = torch.device("cpu")#修改为cpu 运行
|
||||
|
||||
# fix the seed for reproducibility
|
||||
seed = args.seed + misc.get_rank()
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
|
||||
cudnn.benchmark = True
|
||||
|
||||
dataset_train = PretrainDataset(
|
||||
data_dir=args.data_path,
|
||||
dataset_names=[
|
||||
# "auditory",
|
||||
# "cf",
|
||||
"dalia"
|
||||
# "maus",
|
||||
# "mendeley",
|
||||
# "phyatt",
|
||||
],
|
||||
is_test=args.is_test,)
|
||||
|
||||
|
||||
if True: # args.distributed:
|
||||
num_tasks = misc.get_world_size()
|
||||
global_rank = misc.get_rank()
|
||||
sampler_train = torch.utils.data.DistributedSampler(
|
||||
dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
|
||||
)
|
||||
print("Sampler_train = %s" % str(sampler_train))
|
||||
else:
|
||||
sampler_train = torch.utils.data.RandomSampler(dataset_train)
|
||||
|
||||
if global_rank == 0 and args.log_dir is not None:
|
||||
log_dir = os.path.join(args.log_dir, args.remark)
|
||||
os.makedirs(log_dir,exist_ok=True)
|
||||
run_number = get_next_run_number(log_dir)
|
||||
log_run_dir = os.path.join(log_dir, f'run_{run_number}')
|
||||
os.makedirs(log_run_dir, exist_ok=True)
|
||||
log_writer = SummaryWriter(log_dir=log_run_dir)
|
||||
else:
|
||||
log_writer = None
|
||||
|
||||
|
||||
data_loader_train = DataLoader(dataset_train, batch_size=args.batch_size,
|
||||
collate_fn=lambda x: collate_fn(x, pad_nvar=args.nvar),
|
||||
sampler=sampler_train,drop_last=True,
|
||||
num_workers=args.num_workers,pin_memory=True)
|
||||
print("Number of Samples:", len(dataset_train))
|
||||
|
||||
# define the model
|
||||
model = NormWear(
|
||||
img_size=args.img_size,
|
||||
patch_size=args.patch_size,
|
||||
in_chans=args.in_chans,
|
||||
target_len=args.target_len,
|
||||
nvar=args.nvar,
|
||||
embed_dim=args.embed_dim,
|
||||
decoder_embed_dim=args.decoder_embed_dim,
|
||||
depth=args.depth,
|
||||
num_heads=args.num_heads,
|
||||
decoder_depth=args.decoder_depth,
|
||||
mlp_ratio=args.mlp_ratio,
|
||||
fuse_freq=args.fuse_freq,
|
||||
is_pretrain=args.is_pretrain,
|
||||
mask_t_prob=args.mask_t_prob,
|
||||
mask_f_prob=args.mask_f_prob,
|
||||
mask_prob=args.mask_prob,
|
||||
mask_scheme=args.mask_scheme,
|
||||
use_cwt = args.use_cwt,
|
||||
# use_meanpooling=args.use_meanpooling
|
||||
)
|
||||
|
||||
model.to(device)
|
||||
|
||||
model_without_ddp = model
|
||||
print("Model = %s" % str(model_without_ddp))
|
||||
|
||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
||||
|
||||
if args.lr is None: # only base_lr is specified
|
||||
args.lr = args.blr * eff_batch_size / 256
|
||||
|
||||
print("base lr: %.2e" % (args.lr * 256 / eff_batch_size))
|
||||
print("actual lr: %.2e" % args.lr)
|
||||
|
||||
print("accumulate grad iterations: %d" % args.accum_iter)
|
||||
print("effective batch size: %d" % eff_batch_size)
|
||||
|
||||
if args.distributed:
|
||||
print('use distributed!!')
|
||||
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
|
||||
model_without_ddp = model.module
|
||||
|
||||
# following timm: set wd as 0 for bias and norm layers
|
||||
|
||||
param_groups = optim_factory.param_groups_weight_decay(model_without_ddp, args.weight_decay)
|
||||
optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95))
|
||||
print(optimizer)
|
||||
loss_scaler = NativeScaler()
|
||||
|
||||
misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
|
||||
|
||||
print(f"Start training for {args.epochs} epochs")
|
||||
start_time = time.time()
|
||||
for epoch in range(args.start_epoch, args.epochs):
|
||||
if args.distributed:
|
||||
data_loader_train.sampler.set_epoch(epoch)
|
||||
train_stats = train_one_epoch(
|
||||
model, data_loader_train,
|
||||
optimizer, device, epoch, loss_scaler,
|
||||
log_writer=log_writer,
|
||||
args=args
|
||||
)
|
||||
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
|
||||
misc.save_model(
|
||||
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
|
||||
loss_scaler=loss_scaler, epoch=epoch)
|
||||
|
||||
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
|
||||
'epoch': epoch,}
|
||||
|
||||
if args.output_dir and misc.is_main_process():
|
||||
if log_writer is not None:
|
||||
log_writer.flush()
|
||||
with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(log_stats) + "\n")
|
||||
|
||||
total_time = time.time() - start_time
|
||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||
print('Training time {}'.format(total_time_str))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
if args.output_dir:
|
||||
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
main(args)
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,664 @@
|
||||
# dataset.py
|
||||
|
||||
import pickle
|
||||
import os
|
||||
from torch.utils.data import Dataset
|
||||
import random
|
||||
from tqdm import tqdm
|
||||
import torch
|
||||
from torch.utils.data import DataLoader
|
||||
from torch.utils.data._utils.collate import default_collate
|
||||
import torch.nn.functional as F
|
||||
import json
|
||||
import numpy as np
|
||||
from torchvision import transforms
|
||||
class LinearProbDataset(Dataset):
|
||||
def __init__(self,fnames,task):
|
||||
|
||||
#self.dataset_path = os.path.join(data_dir,dataset_name,'samples')
|
||||
self.fnames = fnames
|
||||
self.max_L = 387 # fix length
|
||||
self.task = task
|
||||
|
||||
def __len__(self):
|
||||
return len(self.fnames)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
f_path = self.fnames[idx]
|
||||
|
||||
with open(f_path, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
#x = torch.from_numpy(data_dict['cwt']).permute(0, 3, 1, 2) # n_var, 3, L, 65
|
||||
x = torch.from_numpy(data_dict['cwt']) # n_var, 3, L, 65
|
||||
'''
|
||||
在使用cwt_wrap函数时已经进行了变换
|
||||
'''
|
||||
|
||||
if torch.isnan(x).any():
|
||||
return None # Ignore the sample with NaN values
|
||||
|
||||
n_var, n_channels, L, H = x.size()
|
||||
padded_inputs = torch.zeros((n_var, n_channels, self.max_L, H))
|
||||
|
||||
if L < self.max_L:
|
||||
padded_inputs[:, :, -L:, :] = x
|
||||
else:
|
||||
padded_inputs = x[:, :, -self.max_L:, :]
|
||||
|
||||
label = data_dict['label']
|
||||
|
||||
if isinstance(label, dict):
|
||||
values = [label[key] for key in label.keys()]
|
||||
label = values
|
||||
|
||||
if self.task == "reg":
|
||||
label = torch.tensor(label).float()
|
||||
else:
|
||||
label = torch.tensor(label).long()
|
||||
|
||||
return {
|
||||
'input':padded_inputs,
|
||||
'label':label,
|
||||
}
|
||||
|
||||
def linprob_collate_fn(batch):
|
||||
batch = [b for b in batch if b is not None]
|
||||
return default_collate(batch)
|
||||
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
########################################################################################################################################################
|
||||
class PretrainDataset(Dataset):
|
||||
"""
|
||||
[最终修复版] 一个支持滑动窗口、缓存机制,并允许手动指定缓存文件名的鲁棒预训练数据集。
|
||||
|
||||
- 解决了因Python哈希随机化导致缓存失效的问题。
|
||||
- 推荐使用 `cache_name` 参数来精确控制要加载的缓存文件。
|
||||
"""
|
||||
def __init__(self, data_dir, dataset_names, is_test=0,
|
||||
window_size=387,
|
||||
stride=100,
|
||||
img_size=(387, 65),
|
||||
cache_name: str = None): # [新增] 手动指定缓存文件名的参数
|
||||
|
||||
self.window_size = window_size
|
||||
self.stride = stride
|
||||
|
||||
# --- [修改] 缓存逻辑 ---
|
||||
# 1. 如果手动指定了缓存名,则直接使用它,这是最优先、最稳定的方式。
|
||||
if cache_name:
|
||||
# 确保它是一个 .pkl 文件
|
||||
if not cache_name.endswith('.pkl'):
|
||||
cache_name += '.pkl'
|
||||
cache_path = os.path.join(data_dir, cache_name)
|
||||
print(f"Attempting to load from manually specified cache: {cache_path}")
|
||||
else:
|
||||
# 2. 如果没有手动指定,则使用稳定的方法生成文件名 (不再使用不稳定的 hash)
|
||||
# 将数据集名称排序并用'-'连接,这比哈希更稳定
|
||||
dataset_str = "-".join(sorted(dataset_names))
|
||||
cache_filename = f"pretrain_windows_ds_{dataset_str}_ws{window_size}_s{stride}.pkl"
|
||||
cache_path = os.path.join(data_dir, cache_filename)
|
||||
|
||||
# 3. 检查缓存是否存在 (测试模式下总会重新计算,不使用缓存)
|
||||
if os.path.exists(cache_path) and not is_test:
|
||||
print(f"Loading pre-computed windows from cache: {cache_path}")
|
||||
with open(cache_path, 'rb') as f:
|
||||
self.windows = pickle.load(f)
|
||||
else:
|
||||
# 4. 如果缓存不存在,则执行耗时的计算过程
|
||||
if is_test:
|
||||
print("Running in test mode, bypassing cache...")
|
||||
else:
|
||||
print(f"No cache found at '{cache_path}'. Preprocessing dataset (this will happen only once for this configuration)...")
|
||||
|
||||
fnames = [
|
||||
os.path.join(data_dir, dataset_name, fn)
|
||||
for dataset_name in dataset_names
|
||||
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
||||
if fn[0] != "."
|
||||
]
|
||||
if is_test == 1:
|
||||
fnames = fnames[:20]
|
||||
|
||||
self.windows = []
|
||||
for fname in tqdm(fnames, desc="Calculating windows"):
|
||||
try:
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
_, L = torch.from_numpy(data_dict['data']).float().shape
|
||||
|
||||
if L < self.window_size:
|
||||
continue
|
||||
|
||||
num_windows = (L - self.window_size) // self.stride + 1
|
||||
for i in range(num_windows):
|
||||
self.windows.append((fname, i * self.stride))
|
||||
except Exception as e:
|
||||
# print(f"Warning: Could not process file {fname}. Error: {e}")
|
||||
continue
|
||||
|
||||
# 5. 如果不是测试模式,将计算结果保存到缓存文件
|
||||
if not is_test:
|
||||
print(f"Saving computed windows to cache for future use: {cache_path}")
|
||||
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
|
||||
with open(cache_path, 'wb') as f:
|
||||
pickle.dump(self.windows, f)
|
||||
|
||||
print(f"Dataset initialized with {len(self.windows)} windows.")
|
||||
|
||||
# --- CWT 和数据增强部分保持不变 ---
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
self.transform = transforms.Compose([
|
||||
transforms.RandomResizedCrop(size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
||||
transforms.RandomApply([
|
||||
transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)
|
||||
], p=0.8),
|
||||
transforms.RandomGrayscale(p=0.2),
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
return len(self.windows)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
fname, start_idx = self.windows[idx]
|
||||
|
||||
with open(fname, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
full_signal = torch.from_numpy(data_dict['data']).float()
|
||||
processed_signal = full_signal[:, start_idx : start_idx + self.window_size]
|
||||
|
||||
if not torch.all(torch.isfinite(processed_signal)):
|
||||
processed_signal = torch.nan_to_num(processed_signal, nan=0.0, posinf=0.0, neginf=0.0)
|
||||
|
||||
mean = torch.mean(processed_signal, dim=1, keepdim=True)
|
||||
std = torch.std(processed_signal, dim=1, keepdim=True)
|
||||
processed_signal = (processed_signal - mean) / (std + 1e-8)
|
||||
|
||||
cwt_images = cwt_wrap(processed_signal, self.cwt_scales)
|
||||
|
||||
if not torch.all(torch.isfinite(cwt_images)):
|
||||
return None
|
||||
|
||||
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
||||
x_q_aug = self.transform(cwt_images_permuted)
|
||||
x_k_aug = self.transform(cwt_images_permuted)
|
||||
x_q = x_q_aug.permute(0, 1, 3, 2)
|
||||
x_k = x_k_aug.permute(0, 1, 3, 2)
|
||||
|
||||
if not torch.all(torch.isfinite(x_q)) or not torch.all(torch.isfinite(x_k)):
|
||||
return None
|
||||
|
||||
return {'input_q': x_q, 'input_k': x_k}
|
||||
|
||||
except Exception as e:
|
||||
# print(f"Error processing window at index {idx}. Error: {e}. Skipping.")
|
||||
return None
|
||||
|
||||
def ricker_wavelet(points, scale):
|
||||
"""Generate the Ricker (Mexican hat) wavelet for a given scale."""
|
||||
A = 2 / (torch.sqrt(3 * scale) * (np.pi**0.25))
|
||||
wsq = scale**2
|
||||
device = scale.device if isinstance(scale, torch.Tensor) else 'cpu'
|
||||
vec = torch.arange(0, points, device=device) - (points - 1.0) / 2
|
||||
xsq = vec**2
|
||||
mod = (1 - xsq / wsq)
|
||||
gauss = torch.exp(-xsq / (2 * wsq))
|
||||
return A * mod * gauss
|
||||
|
||||
def cwt_ricker(x, scales, wavelet_len):
|
||||
"""
|
||||
Compute the CWT using the Ricker wavelet.
|
||||
Args:
|
||||
x (torch.Tensor): Input time-series of shape (batch, sequence_length).
|
||||
scales (torch.Tensor): 1D Tensor of scales to use.
|
||||
wavelet_len (int): Length of the wavelet kernel.
|
||||
"""
|
||||
batch_size, sequence_length = x.shape
|
||||
x = x.unsqueeze(1) # -> (batch, 1, sequence_length)
|
||||
|
||||
num_scales = scales.shape[0]
|
||||
scales = scales.to(x.device)
|
||||
|
||||
effective_wavelet_len = min(wavelet_len, sequence_length)
|
||||
wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
||||
wavelets = wavelets.view(num_scales, 1, -1) # -> (num_scales, 1, wavelet_len)
|
||||
|
||||
cwt_output = F.conv1d(x, wavelets, padding='same')
|
||||
return cwt_output # -> (batch, num_scales, sequence_length)
|
||||
|
||||
def cwt_wrap(x, scales):
|
||||
"""
|
||||
Wrapper for CWT computation.
|
||||
Args:
|
||||
x (torch.Tensor): Input signal of shape (n_var, L).
|
||||
scales (torch.Tensor): 1D Tensor of scales to use for CWT.
|
||||
Returns:
|
||||
torch.Tensor: CWT result of shape (n_var, 3, L, num_scales).
|
||||
"""
|
||||
n_var, L = x.shape
|
||||
|
||||
# 1. Calculate derivatives
|
||||
d1 = x[:, 1:] - x[:, :-1]
|
||||
d2 = d1[:, 1:] - d1[:, :-1]
|
||||
|
||||
# 2. Align signals by padding them to the same length L
|
||||
original_x = x
|
||||
d1_padded = F.pad(d1, (1, 0), 'replicate')
|
||||
d2_padded = F.pad(d2, (2, 0), 'replicate')
|
||||
|
||||
# 3. Stack the aligned signals
|
||||
stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
|
||||
|
||||
n_var, n_channels, L_stacked = stacked_x.shape
|
||||
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
||||
|
||||
# 4. Compute CWT
|
||||
wavelet_len = 257 # A fixed reasonable length
|
||||
cwt_res = cwt_ricker(flat_x, scales, wavelet_len) # -> (n_var * 3, num_scales, L)
|
||||
|
||||
_, n_scales, _ = cwt_res.shape
|
||||
|
||||
# 5. Reshape to final format
|
||||
final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
||||
|
||||
return final_cwt
|
||||
|
||||
# --- The collate_fn (Keep this as it is, it's robust) ---
|
||||
# In dataset.py
|
||||
|
||||
def collate_fn(batch, pad_nvar=4):
|
||||
# --- NEW ROBUST LOGIC FOR DISTRIBUTED TRAINING ---
|
||||
|
||||
# 1. Find the first valid item in the batch
|
||||
first_valid_item = None
|
||||
for item in batch:
|
||||
if item is not None:
|
||||
first_valid_item = item
|
||||
break
|
||||
|
||||
# If the entire batch is None (highly unlikely, but safe to handle)
|
||||
if first_valid_item is None:
|
||||
return None
|
||||
|
||||
# 2. Replace all None items with a copy of the first valid item
|
||||
# This ensures all items in the batch are valid tensors.
|
||||
processed_batch = []
|
||||
for item in batch:
|
||||
if item is not None:
|
||||
processed_batch.append(item)
|
||||
else:
|
||||
# Use deepcopy to avoid modifying the same tensor instance if it's augmented later
|
||||
import copy
|
||||
processed_batch.append(copy.deepcopy(first_valid_item))
|
||||
|
||||
# Now, `processed_batch` is guaranteed to have `batch_size` valid items.
|
||||
# The rest of the function can proceed as before.
|
||||
batch = processed_batch
|
||||
|
||||
batch_size = len(batch)
|
||||
_, n_channels, L, H = batch[0]['input_q'].shape
|
||||
|
||||
padded_inputs_q = torch.zeros((batch_size, pad_nvar, n_channels, L, H))
|
||||
padded_inputs_k = torch.zeros((batch_size, pad_nvar, n_channels, L, H))
|
||||
|
||||
for i, item in enumerate(batch):
|
||||
for key, padded_tensor in [('input_q', padded_inputs_q), ('input_k', padded_inputs_k)]:
|
||||
n_var = item[key].size(0)
|
||||
|
||||
current_input = item[key]
|
||||
if n_var > pad_nvar:
|
||||
indices = random.sample(range(n_var), pad_nvar)
|
||||
current_input = current_input[indices]
|
||||
n_var = pad_nvar
|
||||
|
||||
padded_tensor[i, :n_var] = current_input
|
||||
|
||||
if n_var > 0 and n_var < pad_nvar:
|
||||
for j in range(n_var, pad_nvar):
|
||||
padded_tensor[i, j] = padded_tensor[i, n_var - 1]
|
||||
|
||||
return {'input_q': padded_inputs_q, 'input_k': padded_inputs_k}
|
||||
# class PretrainDataset(Dataset):
|
||||
# def __init__(self, data_dir, dataset_names, is_test=0, max_L=387, img_size=(387, 65)):
|
||||
# self.fnames = [
|
||||
# os.path.join(data_dir, dataset_name, fn)
|
||||
# for dataset_name in dataset_names
|
||||
# for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
|
||||
# if fn[0] != "."
|
||||
# ]
|
||||
# if is_test == 1:
|
||||
# self.fnames = self.fnames[:1]
|
||||
|
||||
# self.max_L = max_L
|
||||
|
||||
# # --- CWT Parameters ---
|
||||
# # Define scales for CWT. This will determine the height (65) of the CWT image.
|
||||
# # We create this tensor once during initialization.
|
||||
# self.cwt_scales = torch.arange(1, img_size[1] + 1) # Generates scales from 1 to 65
|
||||
|
||||
# # --- Data Augmentation Pipeline for CWT images ---
|
||||
# # The input to this transform should be a tensor of shape (C, H, W)
|
||||
# self.transform = transforms.Compose([
|
||||
# transforms.RandomResizedCrop(size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
|
||||
# transforms.RandomApply([
|
||||
# transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)
|
||||
# ], p=0.8),
|
||||
# transforms.RandomGrayscale(p=0.2),
|
||||
# ])
|
||||
|
||||
# def __len__(self):
|
||||
# return len(self.fnames)
|
||||
|
||||
# def __getitem__(self, idx):
|
||||
# # 1. Load RAW 1D signal from disk
|
||||
# with open(self.fnames[idx], 'rb') as f:
|
||||
# data_dict = pickle.load(f)
|
||||
|
||||
# raw_signal = torch.from_numpy(data_dict['data']).float()
|
||||
|
||||
# if torch.isnan(raw_signal).any():
|
||||
# return None
|
||||
|
||||
# # 2. Pad or truncate the raw signal to max_L
|
||||
# n_var, L = raw_signal.shape
|
||||
# if L < self.max_L:
|
||||
# padding = torch.zeros((n_var, self.max_L - L))
|
||||
# processed_signal = torch.cat([padding, raw_signal], dim=1)
|
||||
# else:
|
||||
# processed_signal = raw_signal[:, -self.max_L:]
|
||||
|
||||
# # 3. REAL-TIME CWT Computation
|
||||
# # The pre-computed self.cwt_scales tensor is passed directly.
|
||||
# cwt_images = cwt_wrap(processed_signal, self.cwt_scales)
|
||||
|
||||
# # 4. Apply Augmentations to CWT images
|
||||
# cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
|
||||
|
||||
# x_q_aug = self.transform(cwt_images_permuted)
|
||||
# x_k_aug = self.transform(cwt_images_permuted)
|
||||
|
||||
# x_q = x_q_aug.permute(0, 1, 3, 2)
|
||||
# x_k = x_k_aug.permute(0, 1, 3, 2)
|
||||
|
||||
# return {'input_q': x_q, 'input_k': x_k}
|
||||
|
||||
# # --- collate_fn remains the same ---
|
||||
# def collate_fn(batch, pad_nvar=4):
|
||||
# batch = [item for item in batch if item is not None]
|
||||
# if len(batch) == 0:
|
||||
# return None
|
||||
|
||||
# batch_size = len(batch)
|
||||
# n_var_item, n_channels, L, H = batch[0]['input_q'].shape
|
||||
|
||||
# padded_inputs_q = torch.zeros((batch_size, pad_nvar, n_channels, L, H))
|
||||
# padded_inputs_k = torch.zeros((batch_size, pad_nvar, n_channels, L, H))
|
||||
|
||||
# for i, item in enumerate(batch):
|
||||
# for key, padded_tensor in [('input_q', padded_inputs_q), ('input_k', padded_inputs_k)]:
|
||||
# n_var = item[key].size(0)
|
||||
|
||||
# current_input = item[key]
|
||||
# if n_var > pad_nvar:
|
||||
# indices = random.sample(range(n_var), pad_nvar)
|
||||
# current_input = current_input[indices]
|
||||
# n_var = pad_nvar
|
||||
|
||||
# padded_tensor[i, :n_var] = current_input
|
||||
|
||||
# if n_var > 0 and n_var < pad_nvar:
|
||||
# for j in range(n_var, pad_nvar):
|
||||
# padded_tensor[i, j] = padded_tensor[i, n_var - 1]
|
||||
|
||||
# return {'input_q': padded_inputs_q, 'input_k': padded_inputs_k}
|
||||
# def collate_fn(batch, pad_nvar=4):
|
||||
# # Filter out None values from the batch
|
||||
# batch = [item for item in batch if item is not None]
|
||||
|
||||
# if len(batch) == 0:
|
||||
# return None # Return None to be handled in the training loop
|
||||
|
||||
# # Find the maximum sequence length L in the batch
|
||||
# max_L = 387
|
||||
|
||||
# batch_size = len(batch)
|
||||
# input_dim_1 = batch[0]['input_q'].size(1) # Channel count
|
||||
# input_dim_4 = batch[0]['input_q'].size(3) # Wavelet scale count
|
||||
|
||||
# # Initialize padded tensors for query and key inputs
|
||||
# padded_inputs_q = torch.zeros((batch_size, pad_nvar, input_dim_1, max_L, input_dim_4))
|
||||
# padded_inputs_k = torch.zeros((batch_size, pad_nvar, input_dim_1, max_L, input_dim_4))
|
||||
|
||||
# for i, item in enumerate(batch):
|
||||
# # Process both query and key inputs
|
||||
# for key, padded_tensor in [('input_q', padded_inputs_q), ('input_k', padded_inputs_k)]:
|
||||
# n_var = item[key].size(0)
|
||||
# L = item[key].size(2)
|
||||
|
||||
# current_input = item[key]
|
||||
# # If the number of variables is greater than pad_nvar, randomly sample pad_nvar variables
|
||||
# if n_var > pad_nvar:
|
||||
# indices = random.sample(range(n_var), pad_nvar)
|
||||
# current_input = current_input[indices]
|
||||
# n_var = pad_nvar
|
||||
|
||||
# # Pad the inputs
|
||||
# padded_tensor[i, :n_var, :, -L:, :] = current_input # Pad to the right
|
||||
|
||||
# # Copy last valid sequence to pad remaining variables up to pad_nvar
|
||||
# if n_var > 0:
|
||||
# for j in range(n_var, pad_nvar):
|
||||
# padded_tensor[i, j] = padded_tensor[i, n_var - 1]
|
||||
|
||||
# return {'input_q': padded_inputs_q, 'input_k': padded_inputs_k}
|
||||
|
||||
|
||||
# ##############CWT Helper function########################################################################################################
|
||||
# def ricker_wavelet(points, scale):
|
||||
# """Generate the Ricker (Mexican hat) wavelet for a given scale."""
|
||||
# A = 2 / (torch.sqrt(3 * scale) * (np.pi**0.25))
|
||||
# wsq = scale**2
|
||||
# # Ensure vec is created on the same device as scale if scale is a tensor
|
||||
# device = scale.device if isinstance(scale, torch.Tensor) else 'cpu'
|
||||
# vec = torch.arange(0, points, device=device) - (points - 1.0) / 2
|
||||
# xsq = vec**2
|
||||
# mod = (1 - xsq / wsq)
|
||||
# gauss = torch.exp(-xsq / (2 * wsq))
|
||||
# return A * mod * gauss
|
||||
|
||||
# def cwt_ricker(x, scales, wavelet_len):
|
||||
# """
|
||||
# Compute the CWT using the Ricker wavelet.
|
||||
# Args:
|
||||
# x (torch.Tensor): Input time-series of shape (batch, sequence_length).
|
||||
# scales (torch.Tensor): 1D Tensor of scales to use.
|
||||
# wavelet_len (int): Length of the wavelet kernel.
|
||||
# """
|
||||
# # x shape: (batch, sequence_length)
|
||||
# batch_size, sequence_length = x.shape
|
||||
# x = x.unsqueeze(1) # -> (batch, 1, sequence_length)
|
||||
|
||||
# num_scales = scales.shape[0]
|
||||
|
||||
# # Move scales to the correct device
|
||||
# scales = scales.to(x.device)
|
||||
|
||||
# # Prepare wavelets for convolution
|
||||
# # Ensure wavelet length is not greater than signal length
|
||||
# effective_wavelet_len = min(wavelet_len, sequence_length)
|
||||
# wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
|
||||
# wavelets = wavelets.view(num_scales, 1, -1) # -> (num_scales, 1, wavelet_len)
|
||||
|
||||
# # Perform convolution
|
||||
# cwt_output = F.conv1d(x, wavelets, padding='same')
|
||||
# return cwt_output # -> (batch, num_scales, sequence_length)
|
||||
|
||||
# def cwt_wrap(x, scales):
|
||||
# """
|
||||
# Wrapper for CWT computation.
|
||||
# Args:
|
||||
# x (torch.Tensor): Input signal of shape (n_var, L).
|
||||
# scales (torch.Tensor): 1D Tensor of scales to use for CWT.
|
||||
# Returns:
|
||||
# torch.Tensor: CWT result of shape (n_var, 3, L, num_scales).
|
||||
# """
|
||||
# n_var, L = x.shape
|
||||
|
||||
# # 1. Calculate derivatives
|
||||
# # d1 will have length L-1
|
||||
# d1 = x[:, 1:] - x[:, :-1]
|
||||
# # d2 will have length L-2
|
||||
# d2 = d1[:, 1:] - d1[:, :-1]
|
||||
|
||||
# # 2. Align signals by padding them to the same length L
|
||||
# # We pad at the beginning (left side) to make up for the lost points from differentiation.
|
||||
# # This is a common practice, assuming the signal starts from a steady state.
|
||||
|
||||
# # original_x is already (n_var, L), no padding needed.
|
||||
# original_x = x
|
||||
|
||||
# # Pad d1 with one value at the beginning to match length L
|
||||
# d1_padded = F.pad(d1, (1, 0), 'replicate') # 'replicate' pads with the first value
|
||||
|
||||
# # Pad d2 with two values at the beginning to match length L
|
||||
# d2_padded = F.pad(d2, (2, 0), 'replicate')
|
||||
|
||||
# # Check shapes before stacking
|
||||
# # assert original_x.shape == d1_padded.shape == d2_padded.shape
|
||||
|
||||
# # 3. Stack the aligned signals
|
||||
# stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
|
||||
|
||||
# n_var, n_channels, L_stacked = stacked_x.shape
|
||||
|
||||
# # Reshape for batch CWT computation
|
||||
# flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
|
||||
|
||||
# # 4. Compute CWT
|
||||
# wavelet_len = 257 # A fixed reasonable length
|
||||
# cwt_res = cwt_ricker(flat_x, scales, wavelet_len) # -> (n_var * 3, num_scales, L)
|
||||
|
||||
# _, n_scales, _ = cwt_res.shape
|
||||
|
||||
# # 5. Reshape to final format
|
||||
# final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
|
||||
|
||||
# return final_cwt
|
||||
|
||||
#################################################################################
|
||||
class dataset_class(Dataset):
|
||||
"""
|
||||
A robust Dataset class for fine-tuning tasks.
|
||||
- Handles explicit label mapping for binary classification (e.g., healthy vs. unhealthy).
|
||||
- Includes session_id and sample_id in the output for detailed evaluation.
|
||||
- Applies 1D time-series augmentations during training.
|
||||
- Performs real-time CWT calculation if specified.
|
||||
- Includes robust padding and error handling.
|
||||
"""
|
||||
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65)):
|
||||
super(dataset_class, self).__init__()
|
||||
self.data_dir = data_dir
|
||||
self.is_train = is_train
|
||||
|
||||
# 1. 加载数据集划分
|
||||
with open(os.path.join(self.data_dir, 'train_test_split.json'), 'r') as file:
|
||||
split = json.load(file)
|
||||
self.file_list = split['train'] if self.is_train else split['test']
|
||||
|
||||
# 2. 明确定义标签映射
|
||||
# 0: 健康 (Negative class)
|
||||
# 1: 有病 (Positive class)
|
||||
self.label_map = {
|
||||
1: 0, # 原始标签1是'健康',映射为索引0
|
||||
2: 1, # 原始标签2是'有病',映射为索引1
|
||||
}
|
||||
if is_train:
|
||||
print(f"Using predefined label map for fine-tuning: {self.label_map}")
|
||||
|
||||
self.max_len = max_len
|
||||
self.use_spec = use_spec
|
||||
|
||||
# 3. 初始化 CWT scales
|
||||
if not isinstance(img_size, tuple) or len(img_size) != 2:
|
||||
img_size = (max_len - 2, 65)
|
||||
self.cwt_scales = torch.arange(1, img_size[1] + 1)
|
||||
|
||||
# 4. 初始化数据增强
|
||||
self.augmentations = augmentations if self.is_train else None
|
||||
|
||||
def __getitem__(self, idx):
|
||||
try:
|
||||
curr_fn = self.file_list[idx]
|
||||
with open(os.path.join(self.data_dir, 'sample_for_downstream', curr_fn), 'rb') as file:
|
||||
data = pickle.load(file)
|
||||
|
||||
# --- [修复] 提取ID信息 ---
|
||||
if 'uid' in data:
|
||||
sample_id = str(data['uid'])
|
||||
else:
|
||||
sample_id = os.path.splitext(curr_fn)[0]
|
||||
|
||||
parts = sample_id.split('_')
|
||||
if len(parts) >= 2:
|
||||
session_id = f"{parts[0]}_{parts[1]}"
|
||||
else:
|
||||
session_id = parts[0]
|
||||
# --- [修复结束] ---
|
||||
|
||||
# 加载并清理1D信号
|
||||
tss = torch.from_numpy(data['data']).float()
|
||||
tss = torch.nan_to_num(tss, 0.0)
|
||||
|
||||
# 加载并使用预定义的映射转换标签
|
||||
original_label = data['label'][0]['class']
|
||||
if original_label not in self.label_map:
|
||||
return None
|
||||
mapped_label = self.label_map[original_label]
|
||||
label = torch.tensor(mapped_label, dtype=torch.long)
|
||||
|
||||
# [训练时] 应用1D数据增强
|
||||
if self.augmentations:
|
||||
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
tss = tss + torch.randn_like(tss) * self.augmentations['noise_std']
|
||||
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
|
||||
scale = torch.rand(1).item() * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
|
||||
tss = tss * scale
|
||||
|
||||
# 序列长度处理 (填充或裁剪)
|
||||
current_L = tss.shape[1]
|
||||
if current_L > self.max_len:
|
||||
tss = tss[:, -self.max_len:]
|
||||
elif current_L < self.max_len:
|
||||
pad_size = self.max_len - current_L
|
||||
pad_values = tss[:, 0:1].expand(-1, pad_size)
|
||||
tss = torch.cat((pad_values, tss), dim=1)
|
||||
|
||||
# --- [修复] 构建包含所有需要信息的返回字典 ---
|
||||
output_dict = {
|
||||
'label': label,
|
||||
'session_id': session_id,
|
||||
'sample_id': sample_id
|
||||
}
|
||||
|
||||
if self.use_spec:
|
||||
cwt = cwt_wrap(tss, scales=self.cwt_scales)
|
||||
if not torch.all(torch.isfinite(cwt)):
|
||||
return None
|
||||
output_dict['input'] = cwt
|
||||
else:
|
||||
output_dict['input'] = tss
|
||||
|
||||
return output_dict
|
||||
# --- [修复结束] ---
|
||||
|
||||
except Exception as e:
|
||||
# print(f"Error processing sample at index {idx} (file: {self.file_list[idx]}): {e}. Skipping.")
|
||||
return None
|
||||
|
||||
def __len__(self):
|
||||
return len(self.file_list)
|
||||
@@ -0,0 +1,110 @@
|
||||
# engine_pretrain.py
|
||||
|
||||
import math
|
||||
import sys
|
||||
from typing import Iterable, Optional
|
||||
import torch
|
||||
from torch.cuda.amp import autocast
|
||||
|
||||
# 确保 misc 模块可以被找到
|
||||
try:
|
||||
from . import misc
|
||||
except ImportError:
|
||||
import misc
|
||||
|
||||
# [修改] 函数签名增加了 dtype 参数,并为 loss_scaler 提供了更准确的类型提示 (Optional)
|
||||
def train_one_epoch(model: torch.nn.Module,
|
||||
data_loader: Iterable,
|
||||
optimizer: torch.optim.Optimizer,
|
||||
device: torch.device,
|
||||
epoch: int,
|
||||
loss_scaler: Optional[torch.cuda.amp.GradScaler],
|
||||
log_writer=None,
|
||||
args=None,
|
||||
dtype: torch.dtype = torch.float16):
|
||||
model.train(True)
|
||||
metric_logger = misc.MetricLogger(delimiter=" ")
|
||||
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
|
||||
metric_logger.add_meter('grad_norm', misc.SmoothedValue(window_size=1, fmt='{value:.2f}'))
|
||||
header = 'Epoch: [{}]'.format(epoch)
|
||||
print_freq = 20
|
||||
|
||||
accum_iter = args.accum_iter
|
||||
optimizer.zero_grad()
|
||||
|
||||
if log_writer is not None and misc.is_main_process():
|
||||
print('log_dir: {}'.format(log_writer.log_dir))
|
||||
|
||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||
if (data_iter_step) % accum_iter == 0:
|
||||
misc.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
|
||||
|
||||
if batch is None:
|
||||
# 在分布式训练中,一个进程的batch为None,其他进程可能不为None,最好继续以避免卡死
|
||||
# print(f"Skipping iteration {data_iter_step} on rank {misc.get_rank()} due to empty batch.")
|
||||
continue
|
||||
|
||||
samples_q = batch['input_q'].to(device, non_blocking=True)
|
||||
samples_k = batch['input_k'].to(device, non_blocking=True)
|
||||
|
||||
# [修改] 使用传入的 dtype,并启用 autocast
|
||||
with autocast( dtype=dtype):
|
||||
loss, _, _ = model(im_q=samples_q, im_k=samples_k)
|
||||
|
||||
loss_value = loss.item()
|
||||
|
||||
if not math.isfinite(loss_value):
|
||||
print(f"Loss is {loss_value} on rank {misc.get_rank()}, skipping update.")
|
||||
optimizer.zero_grad()
|
||||
continue
|
||||
|
||||
loss = loss / accum_iter
|
||||
|
||||
# --- [修改] 核心逻辑:根据 loss_scaler 是否存在来决定如何反向传播 ---
|
||||
if loss_scaler is not None:
|
||||
# 这是 FP16 的路径,使用 GradScaler
|
||||
loss_scaler.scale(loss).backward()
|
||||
else:
|
||||
# 这是 BF16 或 FP32 的路径,直接反向传播
|
||||
loss.backward()
|
||||
|
||||
if (data_iter_step + 1) % accum_iter == 0:
|
||||
# --- [修改] 核心逻辑:根据 loss_scaler 是否存在来决定如何更新优化器 ---
|
||||
if loss_scaler is not None:
|
||||
# FP16 路径:unscale -> clip -> step -> update
|
||||
loss_scaler.unscale_(optimizer)
|
||||
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=3.0)
|
||||
loss_scaler.step(optimizer)
|
||||
loss_scaler.update()
|
||||
else:
|
||||
# BF16 / FP32 路径:clip -> step
|
||||
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=3.0)
|
||||
optimizer.step()
|
||||
|
||||
optimizer.zero_grad()
|
||||
|
||||
# 同步 grad_norm 以便在所有进程上记录相似的值
|
||||
grad_norm_tensor = torch.tensor(grad_norm.item(), device=device)
|
||||
torch.distributed.all_reduce(grad_norm_tensor)
|
||||
grad_norm_avg = grad_norm_tensor.item() / misc.get_world_size()
|
||||
metric_logger.update(grad_norm=grad_norm_avg)
|
||||
|
||||
torch.cuda.synchronize()
|
||||
|
||||
metric_logger.update(loss=loss_value)
|
||||
lr = optimizer.param_groups[0]["lr"]
|
||||
metric_logger.update(lr=lr)
|
||||
|
||||
loss_value_reduce = misc.all_reduce_mean(loss_value)
|
||||
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
|
||||
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
|
||||
log_writer.add_scalar('train_loss', loss_value_reduce, epoch_1000x)
|
||||
log_writer.add_scalar('lr', lr, epoch_1000x)
|
||||
if 'grad_norm' in metric_logger.meters:
|
||||
grad_norm_value = metric_logger.meters['grad_norm'].value
|
||||
log_writer.add_scalar('grad_norm', grad_norm_value, epoch_1000x)
|
||||
|
||||
# 收集所有进程的统计数据
|
||||
metric_logger.synchronize_between_processes()
|
||||
print("Averaged stats:", metric_logger)
|
||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||
@@ -0,0 +1,396 @@
|
||||
# misc/__init__.py
|
||||
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
# --------------------------------------------------------
|
||||
# References:
|
||||
# DeiT: https://github.com/facebookresearch/deit
|
||||
# BEiT: https://github.com/microsoft/unilm/tree/master/beit
|
||||
# --------------------------------------------------------
|
||||
|
||||
import builtins
|
||||
import datetime
|
||||
import os
|
||||
import time
|
||||
import math
|
||||
from collections import defaultdict, deque
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import inf
|
||||
|
||||
|
||||
class SmoothedValue(object):
|
||||
"""Track a series of values and provide access to smoothed values over a
|
||||
window or the global series average.
|
||||
"""
|
||||
|
||||
def __init__(self, window_size=20, fmt=None):
|
||||
if fmt is None:
|
||||
fmt = "{median:.4f} ({global_avg:.4f})"
|
||||
self.deque = deque(maxlen=window_size)
|
||||
self.total = 0.0
|
||||
self.count = 0
|
||||
self.fmt = fmt
|
||||
|
||||
def update(self, value, n=1):
|
||||
self.deque.append(value)
|
||||
self.count += n
|
||||
self.total += value * n
|
||||
|
||||
def synchronize_between_processes(self):
|
||||
"""
|
||||
Warning: does not synchronize the deque!
|
||||
"""
|
||||
if not is_dist_avail_and_initialized():
|
||||
return
|
||||
t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
|
||||
dist.barrier()
|
||||
dist.all_reduce(t)
|
||||
t = t.tolist()
|
||||
self.count = int(t[0])
|
||||
self.total = t[1]
|
||||
|
||||
@property
|
||||
def median(self):
|
||||
d = torch.tensor(list(self.deque))
|
||||
return d.median().item()
|
||||
|
||||
@property
|
||||
def avg(self):
|
||||
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
||||
return d.mean().item()
|
||||
|
||||
@property
|
||||
def global_avg(self):
|
||||
# Handle division by zero if no updates were made
|
||||
if self.count == 0:
|
||||
return 0.0
|
||||
return self.total / self.count
|
||||
|
||||
@property
|
||||
def max(self):
|
||||
return max(self.deque)
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
return self.deque[-1]
|
||||
|
||||
def __str__(self):
|
||||
return self.fmt.format(
|
||||
median=self.median,
|
||||
avg=self.avg,
|
||||
global_avg=self.global_avg,
|
||||
max=self.max,
|
||||
value=self.value)
|
||||
|
||||
|
||||
class MetricLogger(object):
|
||||
def __init__(self, delimiter="\t"):
|
||||
self.meters = defaultdict(SmoothedValue)
|
||||
self.delimiter = delimiter
|
||||
|
||||
def update(self, **kwargs):
|
||||
for k, v in kwargs.items():
|
||||
if v is None:
|
||||
continue
|
||||
if isinstance(v, torch.Tensor):
|
||||
v = v.item()
|
||||
assert isinstance(v, (float, int))
|
||||
self.meters[k].update(v)
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr in self.meters:
|
||||
return self.meters[attr]
|
||||
if attr in self.__dict__:
|
||||
return self.__dict__[attr]
|
||||
raise AttributeError("'{}' object has no attribute '{}'".format(
|
||||
type(self).__name__, attr))
|
||||
|
||||
def __str__(self):
|
||||
loss_str = []
|
||||
for name, meter in self.meters.items():
|
||||
loss_str.append(
|
||||
"{}: {}".format(name, str(meter))
|
||||
)
|
||||
return self.delimiter.join(loss_str)
|
||||
|
||||
def synchronize_between_processes(self):
|
||||
for meter in self.meters.values():
|
||||
meter.synchronize_between_processes()
|
||||
|
||||
def add_meter(self, name, meter):
|
||||
self.meters[name] = meter
|
||||
|
||||
def log_every(self, iterable, print_freq, header=None):
|
||||
i = 0
|
||||
if not header:
|
||||
header = ''
|
||||
start_time = time.time()
|
||||
end = time.time()
|
||||
iter_time = SmoothedValue(fmt='{avg:.4f}')
|
||||
data_time = SmoothedValue(fmt='{avg:.4f}')
|
||||
space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
|
||||
log_msg = [
|
||||
header,
|
||||
'[{0' + space_fmt + '}/{1}]',
|
||||
'eta: {eta}',
|
||||
'{meters}',
|
||||
'time: {time}',
|
||||
'data: {data}'
|
||||
]
|
||||
if torch.cuda.is_available():
|
||||
log_msg.append('max mem: {memory:.0f}')
|
||||
log_msg = self.delimiter.join(log_msg)
|
||||
MB = 1024.0 * 1024.0
|
||||
for obj in iterable:
|
||||
data_time.update(time.time() - end)
|
||||
yield obj
|
||||
iter_time.update(time.time() - end)
|
||||
if i % print_freq == 0 or i == len(iterable) - 1:
|
||||
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
||||
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
||||
if torch.cuda.is_available():
|
||||
print(log_msg.format(
|
||||
i, len(iterable), eta=eta_string,
|
||||
meters=str(self),
|
||||
time=str(iter_time), data=str(data_time),
|
||||
memory=torch.cuda.max_memory_allocated() / MB))
|
||||
else:
|
||||
print(log_msg.format(
|
||||
i, len(iterable), eta=eta_string,
|
||||
meters=str(self),
|
||||
time=str(iter_time), data=str(data_time)))
|
||||
i += 1
|
||||
end = time.time()
|
||||
total_time = time.time() - start_time
|
||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||
print('{} Total time: {} ({:.4f} s / it)'.format(
|
||||
header, total_time_str, total_time / len(iterable)))
|
||||
|
||||
|
||||
def setup_for_distributed(is_master):
|
||||
"""
|
||||
This function disables printing when not in master process
|
||||
"""
|
||||
builtin_print = builtins.print
|
||||
|
||||
def print(*args, **kwargs):
|
||||
force = kwargs.pop('force', False)
|
||||
force = force or (get_world_size() > 8)
|
||||
if is_master or force:
|
||||
now = datetime.datetime.now().time()
|
||||
builtin_print('[{}] '.format(now), end='') # print with time stamp
|
||||
builtin_print(*args, **kwargs)
|
||||
|
||||
builtins.print = print
|
||||
|
||||
|
||||
def is_dist_avail_and_initialized():
|
||||
if not dist.is_available():
|
||||
return False
|
||||
if not dist.is_initialized():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def get_world_size():
|
||||
if not is_dist_avail_and_initialized():
|
||||
return 1
|
||||
return dist.get_world_size()
|
||||
|
||||
|
||||
def get_rank():
|
||||
if not is_dist_avail_and_initialized():
|
||||
return 0
|
||||
return dist.get_rank()
|
||||
|
||||
|
||||
def is_main_process():
|
||||
return get_rank() == 0
|
||||
|
||||
|
||||
def save_on_master(*args, **kwargs):
|
||||
if is_main_process():
|
||||
torch.save(*args, **kwargs)
|
||||
|
||||
|
||||
def init_distributed_mode(args):
|
||||
if args.dist_on_itp:
|
||||
args.rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
|
||||
args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
|
||||
args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
|
||||
args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'])
|
||||
os.environ['LOCAL_RANK'] = str(args.gpu)
|
||||
os.environ['RANK'] = str(args.rank)
|
||||
os.environ['WORLD_SIZE'] = str(args.world_size)
|
||||
elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
|
||||
args.rank = int(os.environ["RANK"])
|
||||
args.world_size = int(os.environ['WORLD_SIZE'])
|
||||
args.gpu = int(os.environ['LOCAL_RANK'])
|
||||
elif 'SLURM_PROCID' in os.environ:
|
||||
args.rank = int(os.environ['SLURM_PROCID'])
|
||||
args.gpu = args.rank % torch.cuda.device_count()
|
||||
else:
|
||||
print('Not using distributed mode')
|
||||
setup_for_distributed(is_master=True)
|
||||
args.distributed = False
|
||||
return
|
||||
|
||||
args.distributed = True
|
||||
|
||||
torch.cuda.set_device(args.gpu)
|
||||
args.dist_backend = 'nccl'
|
||||
print('| distributed init (rank {}): {}, gpu {}'.format(
|
||||
args.rank, args.dist_url, args.gpu), flush=True)
|
||||
torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
|
||||
world_size=args.world_size, rank=args.rank)
|
||||
torch.distributed.barrier()
|
||||
setup_for_distributed(args.rank == 0)
|
||||
|
||||
|
||||
class NativeScalerWithGradNormCount:
|
||||
state_dict_key = "amp_scaler"
|
||||
|
||||
def __init__(self):
|
||||
self._scaler = torch.cuda.amp.GradScaler()
|
||||
|
||||
def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
|
||||
self._scaler.scale(loss).backward(create_graph=create_graph)
|
||||
if update_grad:
|
||||
if clip_grad is not None:
|
||||
assert parameters is not None
|
||||
self._scaler.unscale_(optimizer)
|
||||
norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
|
||||
else:
|
||||
self._scaler.unscale_(optimizer)
|
||||
norm = get_grad_norm_(parameters)
|
||||
self._scaler.step(optimizer)
|
||||
self._scaler.update()
|
||||
else:
|
||||
norm = None
|
||||
return norm
|
||||
|
||||
def state_dict(self):
|
||||
return self._scaler.state_dict()
|
||||
|
||||
def load_state_dict(self, state_dict):
|
||||
self._scaler.load_state_dict(state_dict)
|
||||
|
||||
|
||||
def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor:
|
||||
if isinstance(parameters, torch.Tensor):
|
||||
parameters = [parameters]
|
||||
parameters = [p for p in parameters if p.grad is not None]
|
||||
norm_type = float(norm_type)
|
||||
if len(parameters) == 0:
|
||||
return torch.tensor(0.)
|
||||
device = parameters[0].grad.device
|
||||
if norm_type == inf:
|
||||
total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters)
|
||||
else:
|
||||
total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type)
|
||||
return total_norm
|
||||
|
||||
|
||||
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler):
|
||||
"""
|
||||
Saves the model checkpoint using a standard PyTorch approach.
|
||||
This version is compatible with any torch.nn.Module and handles
|
||||
the presence or absence of a loss_scaler.
|
||||
"""
|
||||
output_dir = Path(args.output_dir)
|
||||
# Ensure the output directory exists
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
epoch_name = str(epoch)
|
||||
|
||||
# Define the checkpoint path
|
||||
checkpoint_path = output_dir / (f'{args.remark}_checkpoint-{epoch_name}.pth')
|
||||
|
||||
print(f"Saving checkpoint to {checkpoint_path}")
|
||||
|
||||
# Always save the model and optimizer state dicts
|
||||
to_save = {
|
||||
'model': model_without_ddp.state_dict(),
|
||||
'optimizer': optimizer.state_dict(),
|
||||
'epoch': epoch,
|
||||
'args': args,
|
||||
}
|
||||
|
||||
# Conditionally add the loss_scaler state dict if it exists (i.e., if AMP is enabled)
|
||||
if loss_scaler is not None:
|
||||
to_save['scaler'] = loss_scaler.state_dict()
|
||||
|
||||
# Use the save_on_master utility to save the checkpoint, ensuring it only happens on the main process
|
||||
save_on_master(to_save, checkpoint_path)
|
||||
|
||||
|
||||
def load_model(args, model_without_ddp, optimizer, loss_scaler):
|
||||
if args.resume:
|
||||
if args.resume.startswith('https'):
|
||||
checkpoint = torch.hub.load_state_dict_from_url(
|
||||
args.resume, map_location='cpu', check_hash=True)
|
||||
else:
|
||||
checkpoint = torch.load(args.resume, map_location='cpu')
|
||||
model_without_ddp.load_state_dict(checkpoint['model'])
|
||||
print("Resume checkpoint %s" % args.resume)
|
||||
if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
|
||||
optimizer.load_state_dict(checkpoint['optimizer'])
|
||||
args.start_epoch = checkpoint['epoch'] + 1
|
||||
# Conditionally load scaler state if it exists in the checkpoint and loss_scaler is being used
|
||||
if 'scaler' in checkpoint and loss_scaler is not None:
|
||||
loss_scaler.load_state_dict(checkpoint['scaler'])
|
||||
print("With optim & sched!")
|
||||
|
||||
|
||||
def all_reduce_mean(x):
|
||||
world_size = get_world_size()
|
||||
if world_size > 1:
|
||||
x_reduce = torch.tensor(x).cuda()
|
||||
dist.all_reduce(x_reduce)
|
||||
x_reduce /= world_size
|
||||
return x_reduce.item()
|
||||
else:
|
||||
return x
|
||||
|
||||
|
||||
def get_next_run_number(log_dir):
|
||||
if not os.path.exists(log_dir):
|
||||
return 1
|
||||
existing_runs = [d for d in os.listdir(log_dir) if os.path.isdir(os.path.join(log_dir, d))]
|
||||
if not existing_runs:
|
||||
return 1
|
||||
else:
|
||||
run_numbers = []
|
||||
for run in existing_runs:
|
||||
try:
|
||||
run_numbers.append(int(run.split('_')[-1]))
|
||||
except ValueError:
|
||||
continue # Ignore directories that don't end in a number
|
||||
if not run_numbers:
|
||||
return 1
|
||||
return max(run_numbers) + 1
|
||||
|
||||
def freeze_model(model):
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
return model
|
||||
|
||||
def adjust_learning_rate(optimizer, epoch, args):
|
||||
"""Decay the learning rate with half-cycle cosine after warmup"""
|
||||
if epoch < args.warmup_epochs:
|
||||
lr = args.lr * epoch / args.warmup_epochs
|
||||
else:
|
||||
lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \
|
||||
(1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))
|
||||
for param_group in optimizer.param_groups:
|
||||
if "lr_scale" in param_group:
|
||||
param_group["lr"] = lr * param_group["lr_scale"]
|
||||
else:
|
||||
param_group["lr"] = lr
|
||||
return lr
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,249 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
# --------------------------------------------------------
|
||||
# References:
|
||||
# DeiT: https://github.com/facebookresearch/deit
|
||||
# BEiT: https://github.com/microsoft/unilm/tree/master/beit
|
||||
# --------------------------------------------------------
|
||||
import os
|
||||
import math
|
||||
import random
|
||||
import pickle
|
||||
import numpy as np
|
||||
from typing import Iterable
|
||||
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
|
||||
from ..pretrain_pipeline import misc
|
||||
|
||||
# ===== LOAD DATA =======================================================
|
||||
def read_pickle(file_path):
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
return pickle.load(f)
|
||||
except (EOFError, pickle.UnpicklingError) as e:
|
||||
print(f"Error reading file: {file_path}")
|
||||
print(f"Error details: {str(e)}")
|
||||
print(f"File size: {os.path.getsize(file_path)} bytes")
|
||||
return None
|
||||
|
||||
class ZerShotDataset(Dataset):
|
||||
def __init__(self, args, nvar=4):
|
||||
self.img_dir = args.data_path
|
||||
self.nvar = nvar
|
||||
|
||||
def __len__(self): # 195910 if data not in pod, else 144715
|
||||
return 195910 #len(os.listdir(self.img_dir))
|
||||
|
||||
def __getitem__(self, idx):
|
||||
# check data condition
|
||||
data_in_pod = os.path.isfile("../data_in_pod.pkl")
|
||||
|
||||
# fetch file path
|
||||
img_path = os.path.join(self.img_dir,f'{idx}.pkl')
|
||||
if data_in_pod:
|
||||
img_path = img_path.replace("../", "") # switch the root data path to the one in pod
|
||||
else:
|
||||
os.makedirs(self.img_dir.replace("../", ""), exist_ok=True)
|
||||
|
||||
# read data
|
||||
if not os.path.isfile(img_path):
|
||||
return None
|
||||
data_dict = read_pickle(img_path)
|
||||
|
||||
if data_dict.get('label') is None:
|
||||
return None
|
||||
|
||||
# if data_dict is None:
|
||||
# return None
|
||||
# # Skip this item and get the next one
|
||||
# print(f"Skipping item {idx} due to pickle error")
|
||||
# return self.__getitem__((idx + 1) % len(self))
|
||||
|
||||
# # if use spectrum
|
||||
# x = torch.from_numpy(data_dict['spec'])
|
||||
# # shape adjust
|
||||
# ch_idx, F_idx, L_idx = 0, 0, 0
|
||||
# for s_i in range(1, 4):
|
||||
# if x.shape[s_i] == 3:
|
||||
# ch_idx = s_i
|
||||
# elif x.shape[s_i] == 65:
|
||||
# F_idx = s_i
|
||||
# else:
|
||||
# L_idx = s_i
|
||||
# x = torch.permute(x, (0, ch_idx, L_idx, F_idx)) # nvar, 3, L, F
|
||||
|
||||
if torch.is_tensor(data_dict['tss']):
|
||||
x = data_dict['tss'] # nvar, L
|
||||
else:
|
||||
x = torch.from_numpy(data_dict['tss']) # nvar, L
|
||||
x = torch.stack([ts for ts in x if (torch.isnan(ts).sum() / x.shape[1]) < 0.4])
|
||||
|
||||
# ========== for saving to pod ========================================
|
||||
if not data_in_pod:
|
||||
# write
|
||||
with open(img_path.replace("../", ""), 'wb') as f:
|
||||
#print("Check filepath before write to avoid overwrite:", img_path.replace("../", ""))
|
||||
saved_dict = {
|
||||
'tss': data_dict['tss'],
|
||||
'label': data_dict['label']
|
||||
}
|
||||
pickle.dump(saved_dict, f)
|
||||
# ======================================================================
|
||||
|
||||
# sample one task
|
||||
task_key = np.random.choice([k for k in data_dict['label'].keys()], 1)[0]
|
||||
|
||||
# packaging for return
|
||||
return_pack = {
|
||||
# 'spec': x,
|
||||
'tss': x.float(),
|
||||
'task': task_key, # str
|
||||
'label': str(data_dict['label'][task_key]) # str
|
||||
}
|
||||
|
||||
return return_pack
|
||||
|
||||
def collate_fn(batch, pad_nvar=4):
|
||||
# Filter out None values from the batch
|
||||
batch = [item for item in batch if item is not None]
|
||||
|
||||
if len(batch) == 0:
|
||||
# return {'spec': torch.empty(0), 'task': torch.empty(0), 'label': torch.empty(0)}
|
||||
return {'tss': torch.empty(0), 'task': torch.empty(0), 'label': torch.empty(0)}
|
||||
|
||||
# Collect strings into a list
|
||||
task = [item['task'] for item in batch]
|
||||
label = [item['label'] for item in batch]
|
||||
|
||||
# Find the maximum sequence length L in the batch
|
||||
# max_L = 387 # +2 if it is tss
|
||||
max_L = 389
|
||||
|
||||
batch_size = len(batch)
|
||||
# input_dim_1 = batch[0]['spec'].size(1)
|
||||
# input_dim_4 = batch[0]['spec'].size(3)
|
||||
|
||||
# Initialize padded tensors for inputs and targets
|
||||
# padded_inputs = torch.zeros((batch_size, pad_nvar, input_dim_1, max_L, input_dim_4))
|
||||
padded_inputs = torch.zeros((batch_size, pad_nvar, max_L))
|
||||
|
||||
for i, item in enumerate(batch):
|
||||
# print('item[input] shape: ',item['input'].shape)
|
||||
# exit()
|
||||
|
||||
# n_var = item['spec'].size(0)
|
||||
# L = item['spec'].size(2)
|
||||
|
||||
# if use tss
|
||||
n_var = item['tss'].size(0)
|
||||
L = item['tss'].size(1)
|
||||
|
||||
# If the number of variables is greater than pad_nvar, randomly sample pad_nvar variables
|
||||
if n_var > pad_nvar:
|
||||
indices = random.sample(range(n_var), pad_nvar)
|
||||
# item['spec'] = item['spec'][indices]
|
||||
item['tss'] = item['tss'][indices]
|
||||
n_var = pad_nvar
|
||||
|
||||
|
||||
# Pad the inputs and targets
|
||||
# padded_inputs[i, :n_var, :, :L, :] = item['spec']
|
||||
padded_inputs[i, :n_var, :L] = item['tss']
|
||||
|
||||
# Copy last valid sequence to pad remaining variables up to pad_nvar
|
||||
for j in range(n_var, pad_nvar):
|
||||
padded_inputs[i, j] = padded_inputs[i, n_var - 1]
|
||||
|
||||
|
||||
# return {'spec': padded_inputs, 'task': item['task'], 'label': item['label']}
|
||||
return {'tss': padded_inputs, 'task': task, 'label': label}
|
||||
|
||||
# ===== TRAIN HELPER FUNCTION =======================================================
|
||||
def train_one_epoch(model: torch.nn.Module,
|
||||
data_loader: Iterable, optimizer: torch.optim.Optimizer,
|
||||
device: torch.device, epoch: int, loss_scaler,
|
||||
log_writer=None,
|
||||
args=None):
|
||||
model.train(True)
|
||||
metric_logger = misc.MetricLogger(delimiter=" ")
|
||||
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
|
||||
header = 'Epoch: [{}]'.format(epoch)
|
||||
print_freq = 20
|
||||
|
||||
accum_iter = args.accum_iter
|
||||
|
||||
optimizer.zero_grad()
|
||||
|
||||
if log_writer is not None:
|
||||
print('log_dir: {}'.format(log_writer.log_dir))
|
||||
|
||||
# TODO: loading samples
|
||||
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
|
||||
# batch = [b for b in batch if b is not None]
|
||||
# samples = batch['spec'].to(args.device)
|
||||
|
||||
# edge case: skip if have less than 2 samples in the batch (unluckly sampled too many samples with no ground truth available)
|
||||
if len(batch['tss']) < 2:
|
||||
continue
|
||||
|
||||
samples = batch['tss'].to(args.device)
|
||||
|
||||
# we use a per iteration (instead of per epoch) lr scheduler
|
||||
if data_iter_step % accum_iter == 0:
|
||||
misc.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
|
||||
|
||||
samples = samples.to(device, non_blocking=True)
|
||||
|
||||
with torch.cuda.amp.autocast():
|
||||
# input is x, task, label
|
||||
loss = model(samples, batch['task'], label=batch['label'])
|
||||
|
||||
loss_value = loss.item()
|
||||
|
||||
if not math.isfinite(loss_value):
|
||||
print("Loss is {}, stopping training".format(loss_value))
|
||||
print('samples', torch.mean(samples))
|
||||
|
||||
# for param in model.parameters():
|
||||
# if param.grad is not None:
|
||||
# param.grad.detach_()
|
||||
# param.grad.zero_()
|
||||
|
||||
# Replace the non-finite loss with zero to avoid issues in backward pass
|
||||
# loss = torch.tensor(1.0, requires_grad=True).to(loss.device)
|
||||
|
||||
loss /= accum_iter
|
||||
loss_scaler(loss, optimizer, parameters=model.parameters(),clip_grad=args.clip_grad,
|
||||
update_grad=(data_iter_step + 1) % accum_iter == 0)
|
||||
if (data_iter_step + 1) % accum_iter == 0:
|
||||
optimizer.zero_grad()
|
||||
|
||||
torch.cuda.synchronize()
|
||||
|
||||
# free memory
|
||||
del samples
|
||||
|
||||
metric_logger.update(loss=loss_value)
|
||||
|
||||
lr = optimizer.param_groups[0]["lr"]
|
||||
metric_logger.update(lr=lr)
|
||||
|
||||
loss_value_reduce = misc.all_reduce_mean(loss_value)
|
||||
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
|
||||
""" We use epoch_1000x as the x-axis in tensorboard.
|
||||
This calibrates different curves when batch size changes.
|
||||
"""
|
||||
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
|
||||
log_writer.add_scalar('train_loss', loss_value_reduce, epoch_1000x)
|
||||
log_writer.add_scalar('lr', lr, epoch_1000x)
|
||||
|
||||
|
||||
# gather the stats from all processes
|
||||
metric_logger.synchronize_between_processes()
|
||||
print("Averaged stats:", metric_logger)
|
||||
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
||||
@@ -0,0 +1,241 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
# --------------------------------------------------------
|
||||
# References:
|
||||
# DeiT: https://github.com/facebookresearch/deit
|
||||
# BEiT: https://github.com/microsoft/unilm/tree/master/beit
|
||||
# --------------------------------------------------------
|
||||
|
||||
# basic module
|
||||
import argparse
|
||||
import datetime
|
||||
import pickle
|
||||
import json
|
||||
import numpy as np
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# torch related modules
|
||||
import torch
|
||||
import torch.backends.cudnn as cudnn
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
from ..pretrain_pipeline.misc import get_next_run_number
|
||||
|
||||
import timm.optim.optim_factory as optim_factory
|
||||
import torch.nn as nn
|
||||
from ..pretrain_pipeline import misc
|
||||
from ..pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
# model and data specific module
|
||||
from .engine_zeroshot import train_one_epoch, collate_fn, ZerShotDataset
|
||||
from .msitf_fusion import *
|
||||
|
||||
def get_args_parser():
|
||||
parser = argparse.ArgumentParser('MAE pre-training for zero-shot', add_help=False)
|
||||
parser.add_argument('--batch_size', default=64, type=int,
|
||||
help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
|
||||
parser.add_argument('--epochs', default=100, type=int)
|
||||
parser.add_argument('--accum_iter', default=1, type=int,
|
||||
help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)')
|
||||
parser.add_argument('--remark', default='model_mae',
|
||||
help='model_remark')
|
||||
parser.add_argument('--save_every_epoch', default=2, type=int,
|
||||
help='default: save every 10 epoches')
|
||||
|
||||
# Model parameters
|
||||
parser.add_argument('--nvar', type=int, default=4)
|
||||
parser.add_argument('--embed_dim', type=int, default=768)
|
||||
parser.add_argument('--norm_pix_loss', type=bool, default=False)
|
||||
|
||||
|
||||
# Optimizer parameters
|
||||
parser.add_argument('--weight_decay', type=float, default=1e-4,
|
||||
help='weight decay (default: 0.05)')
|
||||
|
||||
parser.add_argument('--lr', type=float, default=None, metavar='LR',
|
||||
help='learning rate (absolute lr)')
|
||||
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR',
|
||||
help='base learning rate: absolute_lr = base_lr * total_batch_size / 256')
|
||||
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR',
|
||||
help='lower lr bound for cyclic schedulers that hit 0')
|
||||
parser.add_argument('--warmup_epochs', type=int, default=0, metavar='N',
|
||||
help='epochs to warmup LR')
|
||||
parser.add_argument('--clip_grad', type=float, default=None,
|
||||
help='max norm of gradient')
|
||||
|
||||
|
||||
# Dataset parameters
|
||||
parser.add_argument('--data_path', default='../data/wearable_zeroshot_pretrain', type=str,
|
||||
help='dataset path')
|
||||
parser.add_argument('--output_dir', default="../data/audio_results", type=str)
|
||||
parser.add_argument('--log_dir', default='../data/audio_results/log',
|
||||
help='path where to tensorboard log')
|
||||
parser.add_argument('--device', default='cuda',
|
||||
help='device to use for training / testing')
|
||||
parser.add_argument('--seed', default=42, type=int)
|
||||
parser.add_argument('--resume', default='',
|
||||
help='resume from checkpoint')
|
||||
# parser.add_argument('--resume', default='../../data/audio_results/audio_only_normwear/audio_only_normwear_checkpoint-10.pth',
|
||||
# help='resume from checkpoint')
|
||||
|
||||
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
|
||||
help='start epoch')
|
||||
parser.add_argument('--num_workers', default=4, type=int)
|
||||
parser.add_argument('--pin_mem', action='store_true',
|
||||
help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
|
||||
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
|
||||
parser.set_defaults(pin_mem=True)
|
||||
|
||||
# distributed training parameters
|
||||
parser.add_argument('--world_size', default=1, type=int,
|
||||
help='number of distributed processes')
|
||||
parser.add_argument('--local_rank', default=-1, type=int)
|
||||
parser.add_argument('--dist_on_itp', action='store_true')
|
||||
parser.add_argument('--dist_url', default='env://',
|
||||
help='url used to set up distributed training')
|
||||
return parser
|
||||
|
||||
|
||||
def main(args):
|
||||
misc.init_distributed_mode(args)
|
||||
print('======================= starting pretrain =======================')
|
||||
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
|
||||
print("{}".format(args).replace(', ', ',\n'))
|
||||
|
||||
device = torch.device(args.device)
|
||||
|
||||
# fix the seed for reproducibility
|
||||
seed = args.seed + misc.get_rank()
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
|
||||
cudnn.benchmark = True
|
||||
|
||||
# TODO: add dataset_train
|
||||
dataset_train = ZerShotDataset(args)
|
||||
|
||||
if True: # args.distributed:
|
||||
num_tasks = misc.get_world_size()
|
||||
global_rank = misc.get_rank()
|
||||
sampler_train = torch.utils.data.DistributedSampler(
|
||||
dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
|
||||
)
|
||||
print("Sampler_train = %s" % str(sampler_train))
|
||||
else:
|
||||
sampler_train = torch.utils.data.RandomSampler(dataset_train)
|
||||
|
||||
if global_rank == 0 and args.log_dir is not None:
|
||||
log_dir = os.path.join(args.log_dir, args.remark)
|
||||
os.makedirs(log_dir,exist_ok=True)
|
||||
run_number = get_next_run_number(log_dir, resume=args.resume)
|
||||
log_run_dir = os.path.join(log_dir, f'run_{run_number}')
|
||||
os.makedirs(log_run_dir, exist_ok=True)
|
||||
log_writer = SummaryWriter(log_dir=log_run_dir)
|
||||
else:
|
||||
log_writer = None
|
||||
|
||||
|
||||
data_loader_train = DataLoader(dataset_train, batch_size=args.batch_size,
|
||||
collate_fn=lambda x: collate_fn(x, pad_nvar=args.nvar),
|
||||
sampler=sampler_train,drop_last=False,
|
||||
num_workers=args.num_workers,pin_memory=True)
|
||||
print("Number of Samples:", len(dataset_train))
|
||||
|
||||
# define the model
|
||||
print("Loading model...")
|
||||
model = NormWearZeroShot()
|
||||
|
||||
model.to(device)
|
||||
|
||||
model_without_ddp = model
|
||||
#print("Model = %s" % str(model_without_ddp))
|
||||
|
||||
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
|
||||
|
||||
if args.lr is None: # only base_lr is specified
|
||||
args.lr = args.blr * eff_batch_size / 256
|
||||
|
||||
print("base lr: %.2e" % (args.lr * 256 / eff_batch_size))
|
||||
print("actual lr: %.2e" % args.lr)
|
||||
|
||||
print("accumulate grad iterations: %d" % args.accum_iter)
|
||||
print("effective batch size: %d" % eff_batch_size)
|
||||
|
||||
if args.distributed:
|
||||
print('use distributed!!')
|
||||
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
|
||||
model_without_ddp = model.module
|
||||
|
||||
# following timm: set wd as 0 for bias and norm layers
|
||||
|
||||
param_groups = optim_factory.param_groups_weight_decay(model_without_ddp, args.weight_decay)
|
||||
optimizer = torch.optim.AdamW(param_groups, lr=args.lr, betas=(0.9, 0.95),amsgrad=True)
|
||||
# optimizer = torch.optim.SGD(param_groups, lr=args.lr,momentum=0.9,nesterov=True)
|
||||
#print(optimizer)
|
||||
loss_scaler = NativeScaler()
|
||||
|
||||
misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
|
||||
####### Check model has grad ########
|
||||
# for name, param in model.named_parameters():
|
||||
# if not param.requires_grad:
|
||||
# print(f"Warning: Parameter {name} has requires_grad=False")
|
||||
# print("###############Finish checking grad################")
|
||||
########################################
|
||||
print(model.module.aggregator)
|
||||
|
||||
print(f"Start training for {args.epochs} epochs")
|
||||
start_time = time.time()
|
||||
for epoch in range(args.start_epoch, args.epochs):
|
||||
if args.distributed:
|
||||
data_loader_train.sampler.set_epoch(epoch)
|
||||
train_stats = train_one_epoch(
|
||||
model, data_loader_train,
|
||||
optimizer, device, epoch, loss_scaler,
|
||||
log_writer=log_writer,
|
||||
args=args
|
||||
)
|
||||
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
|
||||
misc.save_model(
|
||||
args=args, model=model.module.aggregator, model_without_ddp=model_without_ddp.aggregator,
|
||||
optimizer=optimizer,
|
||||
loss_scaler=loss_scaler, epoch=epoch,
|
||||
model_only=True)
|
||||
|
||||
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
|
||||
'epoch': epoch,}
|
||||
|
||||
if args.output_dir and misc.is_main_process():
|
||||
if log_writer is not None:
|
||||
log_writer.flush()
|
||||
with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(log_stats) + "\n")
|
||||
|
||||
# flag for whehther 1st epoch in this pod
|
||||
data_in_pod = os.path.isfile("../data_in_pod.pkl")
|
||||
if not data_in_pod:
|
||||
with open("../data_in_pod.pkl", 'wb') as f:
|
||||
pickle.dump("", f)
|
||||
|
||||
total_time = time.time() - start_time
|
||||
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
||||
print('Training time {}'.format(total_time_str))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = get_args_parser()
|
||||
args = args.parse_args()
|
||||
if args.output_dir:
|
||||
args.output_dir = os.path.join(args.output_dir, args.remark)
|
||||
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
main(args)
|
||||
|
||||
# python3 -m src.zero_shot.main_zeroshot --remark zs_test --batch_size 4
|
||||
# python3 -m src.zero_shot.main_zeroshot --remark zs_test --resume ../data/audio_results/normwear_audio/normwear_audio_checkpoint-20.pth
|
||||
|
||||
# main new
|
||||
# torchrun --nproc_per_node=4 -m src.zero_shot.main_zeroshot --remark normwear_msitf_clean --blr 1e-3 --weight_decay 1e-4 --epochs 50 --clip_grad 1.0 --save_every_epoch 5 --batch_size 64 --accum_iter 1
|
||||
@@ -0,0 +1,341 @@
|
||||
import os
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.functional as F
|
||||
from transformers import AutoTokenizer, AutoModelForCausalLM
|
||||
|
||||
from ..main_model import *
|
||||
from .sentence_template import *
|
||||
|
||||
# Basic Module
|
||||
def freeze_model(model):
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
return model
|
||||
|
||||
def unfreeze_model(model):
|
||||
for param in model.parameters():
|
||||
param.requires_grad = True
|
||||
return model
|
||||
|
||||
class CheckShape(nn.Module):
|
||||
def __init__(self, remark, key=None):
|
||||
super().__init__()
|
||||
self.remark = remark
|
||||
self.key = key
|
||||
def forward(self, x, **kwargs):
|
||||
if self.remark is not None:
|
||||
print(self.remark, x.shape)
|
||||
|
||||
out = x
|
||||
if self.key is not None:
|
||||
out = self.key(x)
|
||||
return out
|
||||
|
||||
class VAE_Latent(nn.Module):
|
||||
def __init__(self, emb_size, out_size):
|
||||
super().__init__()
|
||||
|
||||
self.mu = nn.Linear(emb_size, out_size)
|
||||
self.var = nn.Sequential(
|
||||
nn.Linear(emb_size, out_size),
|
||||
nn.Softplus()
|
||||
)
|
||||
|
||||
def forward(self, x, latent_only=True):
|
||||
# generate mean and variance
|
||||
mu, var = self.mu(x), self.var(x)
|
||||
|
||||
# reparametrization trick
|
||||
if self.training:
|
||||
eps = torch.randn_like(var)
|
||||
z = mu + var*eps
|
||||
else:
|
||||
z = mu
|
||||
|
||||
# output
|
||||
if latent_only:
|
||||
return z
|
||||
return z, mu, var
|
||||
|
||||
class FeedForward(nn.Module):
|
||||
def __init__(self, emb_size, hidden_size, dropout=0.1, add_norm=True, vae_out=True):
|
||||
super().__init__()
|
||||
self.add_norm = add_norm
|
||||
|
||||
last_out = nn.Linear if not vae_out else VAE_Latent
|
||||
|
||||
self.fc_liner = nn.Sequential(
|
||||
nn.Linear(emb_size, hidden_size),
|
||||
nn.GELU(),
|
||||
# nn.Dropout(p=dropout),
|
||||
# nn.Linear(hidden_size, emb_size),
|
||||
last_out(hidden_size, emb_size),
|
||||
nn.Dropout(p=dropout),
|
||||
)
|
||||
|
||||
self.LayerNorm = nn.LayerNorm(emb_size, eps=1e-6)
|
||||
|
||||
def forward(self, x):
|
||||
out = self.fc_liner(self.LayerNorm(x))
|
||||
if self.add_norm:
|
||||
return x + out
|
||||
return out
|
||||
|
||||
# Aggregation Module
|
||||
class MSiTFAggregation(nn.Module):
|
||||
def __init__(self, num_neurons=768, query_size=384, fuse_method='msitf', dropout=0.1, vae_out=True):
|
||||
super().__init__()
|
||||
self.fuse_method = fuse_method # mean, last, msitf
|
||||
|
||||
if fuse_method == 'msitf':
|
||||
# self.v = nn.Linear(num_neurons, query_size)
|
||||
|
||||
# importance, learn-to-drop
|
||||
self.cd = nn.Sequential(
|
||||
nn.Linear(num_neurons, 2),
|
||||
nn.Sigmoid()
|
||||
)
|
||||
self.t_bound = 5e-1
|
||||
|
||||
# relevance
|
||||
self.k = nn.Linear(num_neurons, query_size)
|
||||
self.v = nn.Linear(num_neurons, query_size)
|
||||
self.q = nn.Linear(query_size, query_size)
|
||||
|
||||
# recency
|
||||
self.decay_r = 0.997
|
||||
|
||||
# output fc
|
||||
self.out_fc = FeedForward(query_size, query_size*4, dropout=dropout, vae_out=vae_out)
|
||||
|
||||
def forward(self, x, query, mask=None, calc_recency=True, return_scores=False, device=torch.device('cpu'), rel_only=False, use_query=True):
|
||||
# x: (N, nvar, L, E)
|
||||
# query: N, nvar, E
|
||||
if self.fuse_method == 'mean':
|
||||
return torch.mean(x, dim=1)
|
||||
elif self.fuse_method == 'last':
|
||||
return x[:, :, -1]
|
||||
|
||||
# if not use query for aggregation (mean pool by default)
|
||||
if not use_query:
|
||||
return self.out_fc(self.v(x).mean(dim=1).mean(dim=1))
|
||||
|
||||
# memory stream based fusion
|
||||
N, nvar, L, E = x.shape
|
||||
# recency
|
||||
if calc_recency:
|
||||
recency = torch.tensor([self.decay_r ** p for p in range(L)], requires_grad=False).float().to(device) # .bfloat16() or .float()
|
||||
recency = torch.stack([recency for _ in range(nvar)]).flatten()
|
||||
recency = torch.flip(recency, [0]).view(1, -1) # 1, L
|
||||
x = x.reshape(N, nvar*L, E)
|
||||
|
||||
# relevance
|
||||
# query: N, E_q
|
||||
# query = query.unsqueeze(1) # N, 1, E_q
|
||||
q = self.q(query)
|
||||
k = self.k(x)
|
||||
v = self.v(x)
|
||||
# print(q.shape, k.shape)
|
||||
den = torch.norm(q, dim=-1)*torch.norm(k, dim=-1) # N, L
|
||||
attn = torch.sum(k*q, dim=-1) / den # N, L
|
||||
relevance = torch.softmax(attn, dim=-1)# N, L
|
||||
|
||||
# importance
|
||||
if not rel_only:
|
||||
prob = self.cd(x) # N, L, 2
|
||||
log_prob = torch.log(prob)
|
||||
if self.training:
|
||||
eps = -torch.log(-torch.log(torch.rand(prob.shape))).float().to(device) # gumbel distribution
|
||||
else:
|
||||
eps = torch.tensor(0.577).float().to(device) # empirical mean of gumbel distribution
|
||||
log_prob = (log_prob + eps) / self.t_bound # N, L, 2
|
||||
prob_matrix = torch.exp(log_prob) / torch.exp(log_prob).sum(dim=-1, keepdim=True) # N, L, 2
|
||||
# mask = 0.5 < prob_matrix
|
||||
# prob_matrix = prob_matrix * mask # N, L, 2
|
||||
importance = prob_matrix[:, :, 1] # N, L
|
||||
|
||||
# integrate scores, normalize, and weighted sum
|
||||
retrieval = relevance+(0.5*importance) # N, L
|
||||
if calc_recency:
|
||||
retrieval = retrieval + (0.2*recency)
|
||||
else:
|
||||
retrieval = relevance
|
||||
|
||||
# softmax
|
||||
retrieval = torch.softmax(retrieval, dim=-1) # N, L
|
||||
# retrieval = retrieval / torch.sum(retrieval, dim=1, keepdim=True) # N, L
|
||||
final_out = torch.sum(v*retrieval.unsqueeze(-1), dim=1) # N, E_q
|
||||
|
||||
final_out = self.out_fc(final_out)
|
||||
|
||||
# return
|
||||
if return_scores:
|
||||
return v, recency, relevance, importance
|
||||
return final_out
|
||||
|
||||
# main module
|
||||
def mean_pooling(model_output, attention_mask):
|
||||
token_embeddings = model_output.hidden_states[-1] #First element of model_output contains all token embeddings
|
||||
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
||||
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
||||
|
||||
def txt_encode(task=None, label=None, model=None, task_type=None):
|
||||
sentences = list()
|
||||
if len(task) == 1 and label is not None: # label sentence only (for gt encode only)
|
||||
# answers
|
||||
for l in label:
|
||||
if task_type == 'reg':
|
||||
sentences.append(np.random.choice(sentence_template[task[0]]['answer_template'], 1)[0].format(l))
|
||||
else:
|
||||
sentences.append(sentence_template[task[0]]['answer_template'][l])
|
||||
elif label is None and len(task) == 1: # query sentence only (for inference forward only)
|
||||
# questions
|
||||
for key in task:
|
||||
sentences.append(np.random.choice(sentence_template[key]['question_template'], 1)[0])
|
||||
|
||||
# if above 2 case meet (for pretrain)
|
||||
if len(sentences) > 0:
|
||||
# text encoding
|
||||
return model.txt_encode(sentences)
|
||||
|
||||
# else, both task and label have things
|
||||
questions, answers = list(), list()
|
||||
for t_i in range(len(task)):
|
||||
questions.append(np.random.choice(sentence_template[task[t_i]]['question_template'], 1)[0])
|
||||
answers.append(np.random.choice(sentence_template[task[t_i]]['answer_template'], 1)[0].format(label[t_i]))
|
||||
|
||||
# text encoding
|
||||
embeds = model.txt_encode(questions+answers) # N, 2048
|
||||
|
||||
return embeds[:len(questions), :], embeds[len(questions):, :] # question, answer
|
||||
|
||||
class NormWearZeroShot(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
msitf_ckpt="",
|
||||
weight_path="",
|
||||
use_query=True, # True
|
||||
rel_only=False # False
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.use_query = use_query
|
||||
self.rel_only = rel_only
|
||||
|
||||
# text encoder
|
||||
self.tokenizer = AutoTokenizer.from_pretrained("muzammil-eds/tinyllama-2.5T-Clinical-v2")
|
||||
self.nlp_model = freeze_model(AutoModelForCausalLM.from_pretrained("muzammil-eds/tinyllama-2.5T-Clinical-v2"))
|
||||
self.query_size = 2048
|
||||
|
||||
# sensor encoder
|
||||
self.sensor_model = freeze_model(NormWearModel(weight_path=weight_path))
|
||||
self.aggregator = MSiTFAggregation(num_neurons=768, query_size=self.query_size, vae_out=True)
|
||||
|
||||
# load pretrained weight
|
||||
if len(msitf_ckpt) > 0:
|
||||
try:
|
||||
stat_dict = torch.load(msitf_ckpt, map_location=torch.device('cpu'))
|
||||
|
||||
# # comment this out if the error on model save is fixed
|
||||
# stat_dict = torch.load(msitf_ckpt, map_location=torch.device('cpu'))['model']
|
||||
# current_state_dict_keys = self.aggregator.state_dict().keys()
|
||||
# filtered_state_dict = {k.replace("aggregator.", ""): v for k, v in stat_dict.items() if k.replace("aggregator.", "") in current_state_dict_keys}
|
||||
filtered_state_dict = stat_dict
|
||||
|
||||
# load
|
||||
self.aggregator.load_state_dict(filtered_state_dict)
|
||||
print("MSiTF Checkpoint is successfully loaded!")
|
||||
except:
|
||||
print("Error occur during loading checkpoint, please check.")
|
||||
|
||||
# loss
|
||||
loss_l1 = nn.L1Loss()
|
||||
# loss_l1 = nn.MSELoss()
|
||||
loss_cos = nn.CosineEmbeddingLoss()
|
||||
self.lambda_temp = nn.Parameter(torch.ones(1)*42, requires_grad=True)
|
||||
def ctr_loss(x, y):
|
||||
# x, y: bn, E
|
||||
dot_prod = torch.exp(torch.matmul(x, y.T)) ** (1/self.lambda_temp) # bn, bn
|
||||
loss = F.softmax(dot_prod, dim=1) # bn, bn
|
||||
loss = torch.log(torch.diagonal(loss) / loss.sum(dim=1)) # bn
|
||||
return -loss.mean()
|
||||
|
||||
# aggregate loss
|
||||
self.loss_f = lambda x, y: torch.sum(torch.nan_to_num(torch.stack([
|
||||
2*loss_l1(x, y),
|
||||
loss_cos(x, y, torch.ones(len(y)).to(x.device)),
|
||||
# ctr_loss(x, y)
|
||||
])))
|
||||
|
||||
def txt_encode(self, sentences):
|
||||
inputs = self.tokenizer(sentences, padding=True, return_tensors="pt").to(self.nlp_model.device)
|
||||
out = self.nlp_model(**inputs, output_hidden_states=True)
|
||||
return mean_pooling(out, inputs.attention_mask) # N, 2048
|
||||
|
||||
def signal_encode(self, x, query, sampling_rate=65):
|
||||
# x: [bn, nvar, L]
|
||||
device = x.device
|
||||
|
||||
# sensor encoding
|
||||
sensor_out = self.sensor_model.get_embedding(x, sampling_rate=sampling_rate, device=device) # bn, nvar, P, E
|
||||
|
||||
if query.shape[0] == 1: # if single question for all samples in input batch
|
||||
query = query.expand(sensor_out.shape[0], query.shape[1]) # (bn, 2048)
|
||||
|
||||
# aggregate
|
||||
bn, nvar, P, E = sensor_out.shape
|
||||
|
||||
query = query.unsqueeze(1).expand(bn, nvar*P, query.shape[1]) # (bn, nvar, 2048)
|
||||
|
||||
# per channel aggregate
|
||||
ch_aggregate_out = self.aggregator(
|
||||
sensor_out,
|
||||
query,
|
||||
device=device,
|
||||
rel_only=self.rel_only,
|
||||
use_query=self.use_query
|
||||
) # bn*nvar, E
|
||||
|
||||
return ch_aggregate_out
|
||||
|
||||
def inference(self, signal_embed, option_embed):
|
||||
# Manhattan distance
|
||||
distances = torch.abs(signal_embed[:, None, :] - option_embed[None, :, :]).sum(dim=-1) # bn, num_choice
|
||||
|
||||
# # dot product
|
||||
# distances = 1 / torch.matmul(signal_embed, option_embed.T) # bn, num_choice
|
||||
|
||||
sims = distances
|
||||
sims = 1 - (sims / torch.sum(sims, dim=1, keepdim=True))
|
||||
sims = torch.nan_to_num(sims) + 1e-8 # bn, num_choice
|
||||
|
||||
y_preds = nn.functional.softmax(sims.float(), dim=1) # bn, num_choice
|
||||
return y_preds
|
||||
|
||||
def forward(self, x, task, label=None, sampling_rate=65):
|
||||
# x: [bn, nvar, L]
|
||||
# task, label: string for sentence template match
|
||||
# label: None if query only
|
||||
# x = torch.nan_to_num(x) # numerical stability
|
||||
|
||||
# text forward
|
||||
txt_embed_res = txt_encode(task=task, label=label, model=self) # (bn, E), (bn, E)
|
||||
|
||||
# unpack
|
||||
if type(txt_embed_res) == tuple:
|
||||
query, gt = txt_embed_res
|
||||
else:
|
||||
query = txt_embed_res
|
||||
|
||||
sensor_embed = self.signal_encode(x, query, sampling_rate=sampling_rate)
|
||||
|
||||
|
||||
if label is None:
|
||||
return sensor_embed
|
||||
|
||||
# calculate loss
|
||||
loss = self.loss_f(sensor_embed, gt)
|
||||
|
||||
return loss
|
||||
@@ -0,0 +1,452 @@
|
||||
sentence_template = {
|
||||
# == PRETRAIN ================================================
|
||||
'NASA_TLX': {
|
||||
'question_template': [
|
||||
'What is the NASA Task Load Index in Percentage?',
|
||||
'Can you provide the NASA TLX score as a percentage?',
|
||||
'What percentage does the NASA Task Load Index indicate?',
|
||||
'Please tell me the NASA Task Load Index in percentage terms.',
|
||||
'How much is the NASA TLX score expressed in percentage?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The NASA Task Load Index (NASA-TLX) was recorded at {}%.",
|
||||
"According to the NASA Task Load Index, the workload was {}%.",
|
||||
"A score of {}% was measured using NASA-TLX, a common workload assessment tool.",
|
||||
"Workload evaluation using NASA TLX resulted in a score of {}%.",
|
||||
"The workload score, based on NASA Task Load Index metrics, is {}%.",
|
||||
"NASA-TLX, which measures perceived workload across multiple factors, recorded a score of {}%.",
|
||||
"An assessment with the NASA Task Load Index showed a workload score of {}%.",
|
||||
"Using the NASA-TLX methodology, the workload was rated at {}%.",
|
||||
"NASA Task Load Index, a tool for measuring mental and physical workload, indicated {}%.",
|
||||
"The recorded workload score from NASA-TLX was {}%.",
|
||||
"Workload, assessed via NASA Task Load Index, was measured at {}%.",
|
||||
"NASA TLX provided a workload evaluation score of {}%.",
|
||||
"The mental and physical demands, as quantified by NASA-TLX, were {}%.",
|
||||
"Perceived workload, evaluated using NASA Task Load Index, came out at {}%.",
|
||||
"NASA-TLX, a multidimensional workload assessment, reported {}%.",
|
||||
"The score derived from NASA Task Load Index data is {}%.",
|
||||
"NASA TLX, which evaluates workload across effort, performance, and other factors, reported a score of {}%.",
|
||||
"Measured workload, based on NASA-TLX, was {}%.",
|
||||
"A workload rating of {}% was determined using NASA Task Load Index methods.",
|
||||
"NASA-TLX indicated that the overall workload level was {}%."
|
||||
]
|
||||
},
|
||||
'PSQI': {
|
||||
'question_template': [
|
||||
'What is the Pittsburgh Sleep Quality Index in Percentage?',
|
||||
'Can you give me the PSQI score as a percentage?',
|
||||
'What percentage is the Pittsburgh Sleep Quality Index?',
|
||||
'Please provide the PSQI as a percentage.',
|
||||
'How is the Pittsburgh Sleep Quality Index represented in percentage?'
|
||||
],
|
||||
'answer_template': [
|
||||
"The Pittsburgh Sleep Quality Index score is {}%.",
|
||||
"According to the PSQI, the score is {}%.",
|
||||
"The sleep quality score, measured by the PSQI, stands at {}%.",
|
||||
"The PSQI result indicates a score of {}%.",
|
||||
"Based on the PSQI, the sleep quality percentage is {}%.",
|
||||
"The sleep quality assessment (PSQI) shows a result of {}%.",
|
||||
"Measured by the PSQI, the sleep quality index is {}%.",
|
||||
"The overall sleep quality, as per the PSQI score, is {}%.",
|
||||
"The index for sleep quality, also known as the PSQI, is {}%.",
|
||||
"Sleep quality assessment using the PSQI resulted in a score of {}%.",
|
||||
"The sleep score (Pittsburgh Sleep Quality Index) is {}%.",
|
||||
"Sleep quality percentage, evaluated by PSQI, is {}%.",
|
||||
"The reported PSQI sleep quality score stands at {}%.",
|
||||
"Sleep quality as indicated by the PSQI is {}%.",
|
||||
"The calculated PSQI score for sleep quality is {}%.",
|
||||
"Sleep quality, based on the Pittsburgh Sleep Quality Index, is {}%.",
|
||||
"The sleep index percentage (PSQI) is {}%.",
|
||||
"The PSQI sleep quality evaluation gives a score of {}%.",
|
||||
"Based on the Pittsburgh Sleep Quality Index (PSQI), the score is {}%.",
|
||||
"Sleep quality evaluation resulted in a score of {}% using the PSQI."
|
||||
]
|
||||
},
|
||||
'Emotion': {
|
||||
'question_template': [
|
||||
'What is the current emotion?',
|
||||
'Can you identify the current emotion?',
|
||||
'What emotion is being expressed now?',
|
||||
'What is the emotion right now?',
|
||||
'Could you specify the current emotion?'
|
||||
],
|
||||
'answer_template': [
|
||||
"The emotion recognized is {}.",
|
||||
"This person exhibits {} as their emotion.",
|
||||
"The detected emotional state is {}.",
|
||||
"The emotion associated with this individual is {}.",
|
||||
"The current feeling identified is {}.",
|
||||
"The observed emotional condition is {}.",
|
||||
"This person's emotional experience is {}.",
|
||||
"The identified state of emotion is {}.",
|
||||
"The analysis suggests the emotion is {}.",
|
||||
"Based on observation, the emotion is {}.",
|
||||
"The subject's emotional tone appears to be {}.",
|
||||
"The prevailing mood detected is {}.",
|
||||
"The emotional response identified is {}.",
|
||||
"This individual seems to be experiencing {}.",
|
||||
"The apparent emotion is {}.",
|
||||
"The interpreted emotional state is {}.",
|
||||
"The primary feeling of this subject is {}.",
|
||||
"The sentiment detected reflects {}.",
|
||||
"This individual's emotional signature indicates {}.",
|
||||
"The psychological state recognized is {}. Emotion refers to a complex reaction involving physiological and psychological responses to significant stimuli."
|
||||
]
|
||||
},
|
||||
'Valence': {
|
||||
'question_template': [
|
||||
'What is the valence level in Percentage?',
|
||||
'Can you provide the valence level as a percentage?',
|
||||
'What percentage represents the valence level?',
|
||||
'Please tell me the valence level in percentage terms.',
|
||||
'How much is the valence level expressed in percentage?'
|
||||
],
|
||||
'answer_template': [
|
||||
'Valence level detected is {}%.',
|
||||
'The valence level is {}%.',
|
||||
'Valence is measured at {}%.',
|
||||
'Measured valence level is {}%.',
|
||||
'The detected emotional valence level is {}%.',
|
||||
'An emotional valence level of {}% has been identified.',
|
||||
'The current valence level reads {}%.',
|
||||
'The recorded valence level stands at {}%.',
|
||||
'Valence has been assessed at {}%.',
|
||||
'Valence detection shows a level of {}%.',
|
||||
'The identified valence percentage is {}%.',
|
||||
'A valence reading of {}% was obtained.',
|
||||
'The emotional tone is measured as {}% valence.',
|
||||
'Detection indicates a valence of {}%.',
|
||||
'The calculated valence level amounts to {}%.',
|
||||
'Assessment reveals a valence level of {}%.',
|
||||
'Valence, representing emotional positivity, is {}%.',
|
||||
'The positivity score, referred to as valence, is {}%.',
|
||||
'An analysis of emotional valence returned a value of {}%.',
|
||||
'The percentage for emotional valence detected is {}%.'
|
||||
]
|
||||
},
|
||||
'Arousal': {
|
||||
'question_template': [
|
||||
'What is the arousal level in Percentage?',
|
||||
'Can you give me the arousal level as a percentage?',
|
||||
'What percentage represents the arousal level?',
|
||||
'Please provide the arousal level in percentage.',
|
||||
'How much is the arousal level expressed in percentage?'
|
||||
],
|
||||
'answer_template': [
|
||||
"Arousal level detected is {}%.",
|
||||
"The arousal level has been recorded as {}%.",
|
||||
"The detected arousal level is {}%.",
|
||||
"Arousal has been measured at {}%.",
|
||||
"The measurement indicates an arousal level of {}%.",
|
||||
"The recorded value for arousal is {}%.",
|
||||
"Arousal has been quantified at {}%.",
|
||||
"The level of arousal has been determined to be {}%.",
|
||||
"According to the measurement, the arousal level is {}%.",
|
||||
"Based on the analysis, the arousal level is {}%.",
|
||||
"The system identifies an arousal level of {}%.",
|
||||
"Arousal is reported at {}%.",
|
||||
"Arousal has been assessed as {}%.",
|
||||
"Arousal intensity is evaluated at {}%.",
|
||||
"The arousal percentage recorded is {}%.",
|
||||
"The current arousal level stands at {}%.",
|
||||
"Measurements show an arousal level of {}%.",
|
||||
"Arousal, which reflects the state of alertness or physiological activation, is noted to be {}%.",
|
||||
"Physiological arousal, often associated with heightened awareness or stress, has been measured at {}%.",
|
||||
"The system's output indicates an arousal metric of {}%."
|
||||
]
|
||||
},
|
||||
'min_bp': {
|
||||
'question_template':[
|
||||
'What is the diastolic blood pressure?',
|
||||
'Can you provide the diastolic blood pressure reading?',
|
||||
'What is the current diastolic BP?',
|
||||
'Please tell me the diastolic blood pressure.',
|
||||
'What is the diastolic pressure value?'
|
||||
],
|
||||
'answer_template': [
|
||||
"The diastolic blood pressure was measured as {}.",
|
||||
"A diastolic pressure reading of {} was obtained.",
|
||||
"Recorded diastolic blood pressure value: {}.",
|
||||
"The recorded value for diastolic blood pressure is {}.",
|
||||
"Diastolic BP measurement: {}.",
|
||||
"A measurement of diastolic BP shows {}.",
|
||||
"The diastolic blood pressure was noted to be {}.",
|
||||
"The recorded diastolic value is {}.",
|
||||
"A diastolic blood pressure reading of {} was documented.",
|
||||
"The measured diastolic BP value is {}.",
|
||||
"Diastolic blood pressure is the pressure in arteries when the heart is at rest; it was recorded as {}.",
|
||||
"The lower number in a blood pressure reading, diastolic pressure, is {}.",
|
||||
"A diastolic pressure value of {} has been observed.",
|
||||
"Measured diastolic pressure, which represents the arterial pressure during cardiac relaxation, is {}.",
|
||||
"Diastolic blood pressure, reflecting the heart's resting state, is {}.",
|
||||
"The observed diastolic BP was {}.",
|
||||
"A BP reading indicated a diastolic value of {}.",
|
||||
"The pressure recorded during heart relaxation, known as diastolic BP, is {}.",
|
||||
"The diastolic component of blood pressure is {}.",
|
||||
"Blood pressure reading reveals the diastolic value to be {}."
|
||||
]
|
||||
},
|
||||
'max_bp': {
|
||||
'question_template': [
|
||||
'What is the systolic blood pressure?',
|
||||
'Can you provide the systolic blood pressure reading?',
|
||||
'What is the current systolic BP?',
|
||||
'Please tell me the systolic blood pressure.',
|
||||
'What is the systolic pressure value?'
|
||||
],
|
||||
'answer_template': [
|
||||
'The systolic blood pressure was recorded as {}.',
|
||||
'Systolic blood pressure measurement shows {}.',
|
||||
'A systolic blood pressure value of {} was observed.',
|
||||
'The recorded systolic pressure is {}.',
|
||||
'The systolic blood pressure was measured to be {}.',
|
||||
'A measurement of systolic blood pressure indicated a value of {}.',
|
||||
'The value for systolic BP is {}.',
|
||||
'Systolic blood pressure is noted to be {}.',
|
||||
'Systolic blood pressure readings indicate {}.',
|
||||
'The systolic reading is {}.',
|
||||
'BP, specifically systolic pressure, was recorded as {}.',
|
||||
'The top number in the blood pressure reading, known as systolic pressure, is {}.',
|
||||
'The systolic blood pressure, which represents the pressure in the arteries when the heart beats, is {}.',
|
||||
'The pressure exerted on artery walls during heart contraction, or systolic pressure, is {}.',
|
||||
'Blood pressure measurement reports a systolic value of {}.',
|
||||
'The systolic component of blood pressure is {}.',
|
||||
'Recorded systolic BP value: {}.',
|
||||
'The systolic BP reading obtained is {}.',
|
||||
'Systolic blood pressure, which measures the force when the heart pumps, is {}.',
|
||||
'The initial or higher value in a blood pressure reading, the systolic pressure, measures {}.'
|
||||
]
|
||||
},
|
||||
'activity': {
|
||||
'question_template': [
|
||||
'What is the current activity?',
|
||||
'Can you identify the current activity?',
|
||||
'What activity is happening right now?',
|
||||
'Please tell me what the current activity is.',
|
||||
'What is the activity being performed currently?'
|
||||
],
|
||||
'answer_template':[
|
||||
'This subject is presently {}.',
|
||||
'The individual is involved in {}.',
|
||||
'Currently, the subject is engaged in {}.',
|
||||
'This person is performing {} at the moment.',
|
||||
'The current task for the subject is {}.',
|
||||
'At present, the subject is engaged in {}.',
|
||||
'The subject is actively participating in {}.',
|
||||
'This individual is involved with {}.',
|
||||
'The subject is currently occupied with {}.',
|
||||
'The person is presently carrying out {}.',
|
||||
'Subject is currently focused on {}.',
|
||||
'The subject has taken up {} as their current task.',
|
||||
'The ongoing activity of the subject is {}.',
|
||||
'The subject is undertaking {} at the moment.',
|
||||
'Subject is actively working on {}.',
|
||||
'This individual’s present activity is {}.',
|
||||
'The individual is currently dedicated to {}.',
|
||||
'At this time, the subject is engaged in {}.',
|
||||
'The current focus of the subject is {}.',
|
||||
'This person is involved in {} right now.'
|
||||
]
|
||||
},
|
||||
# == DOWNSTREAM ====================================
|
||||
('wearable_downstream/PPG_HTN', 'PPG_HTN'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the stage of hypertension?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person has no hypertension.",
|
||||
"The person is having prehypertension.",
|
||||
"The person is at first stage hypertension.",
|
||||
"The person is at second stage hypertension.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/PPG_DM', 'PPG_DM'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the risk of having diabetes?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is at low risk of having diabetes.",
|
||||
"The person is at high risk of having diabetes.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/PPG_CVA', 'PPG_CVA'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the risk of having cerebral vascular accident?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is at low risk of having cerebral vascular accident.",
|
||||
"The person is at high risk of having cerebral vascular accident."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/PPG_CVD', 'PPG_CVD'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the risk of having cardiovascular disease?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is at low risk of having cardiovascular disease.",
|
||||
"The person is having cerebrovascular disease.",
|
||||
"The person is having insufficiency of cerebral blood supply."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/indian-fPCG', 'indian-fPCG'): {
|
||||
'type': 'reg',
|
||||
'question_template': [
|
||||
'What is the fetal heart rate?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The fetal heart rate is {} beats per minute, within the normal range of 110-160 bpm."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/ppg_hgb', 'ppg_hgb'): {
|
||||
'type': 'reg',
|
||||
'question_template': [
|
||||
'What is the estimated level of hemoglobin?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The level of hemoglobin level is {}."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/non_invasive_bp', 'non_invasive_bp'): {
|
||||
'type': 'reg',
|
||||
'question_template': [
|
||||
'What is the estimated levels of systolic and diastolic blood pressure?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The levels of systolic and diastolic blood pressure are {} respectively."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/drive_fatigue', 'drive_fatigue'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is the person in fatigue state or not?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is at normal state.",
|
||||
"The person is at fatigue state.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/ecg_heart_cat', 'ecg_heart_cat'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is the person having myocardial infarction?'
|
||||
],
|
||||
'answer_template':[
|
||||
"Yes, the person is having high risk of myocardial infarction.",
|
||||
"No, the person is having healthy heart beat."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/gameemo', 'gameemo'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the current emotion state?'
|
||||
],
|
||||
'answer_template':[
|
||||
"Low mood, low energy.",
|
||||
"Low mood, high energy.",
|
||||
"High mood, low energy.",
|
||||
"High mood, high energy."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/uci_har', 'uci_har'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the current activity?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is walking.",
|
||||
"The person is walking upstairs.",
|
||||
"The person is walking downstairs.",
|
||||
"The person is sitting.",
|
||||
"The person is standing.",
|
||||
"The person is laying."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/wesad', 'wesad'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is the person doing good?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person is doing so so",
|
||||
"The person is under stress.",
|
||||
"The person is having fun.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/emg-tfc', 'emg-tfc'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the state of the muscle?'
|
||||
],
|
||||
'answer_template':[
|
||||
"The person has healthy muscle.",
|
||||
"The person is suffering from neuropathy.",
|
||||
"The person is suffering from myopathy.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/ecg-tfc', 'ecg-tfc'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the state of cardiac arrhythmias?'
|
||||
],
|
||||
'answer_template':[
|
||||
"It is a normal sinus rhythm.",
|
||||
"It is atrial fibrillation.",
|
||||
"It is alternative rhythm.",
|
||||
"Unknown noisy rhythm."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/Epilepsy', 'A_Z_eye_open'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'What is the status of eyes?'
|
||||
],
|
||||
'answer_template':[
|
||||
"Eyes closed.",
|
||||
"Eyes open.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/Epilepsy', 'B_O_eye_close'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is the person\'s eyes close? '
|
||||
],
|
||||
'answer_template':[
|
||||
"No, the eyes are open.",
|
||||
"Yes, the eyes are closed.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/Epilepsy', 'C_N_health'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is this a healthy brain area?'
|
||||
],
|
||||
'answer_template':[
|
||||
"This might be tumor, or undergo seizure.",
|
||||
"This is a normal area."
|
||||
]
|
||||
},
|
||||
('wearable_downstream/Epilepsy', 'D_F_tumor'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is this an area with tumor?'
|
||||
],
|
||||
'answer_template':[
|
||||
"No, it is not a tumor area.",
|
||||
"Yes, it is an area with tumor.",
|
||||
]
|
||||
},
|
||||
('wearable_downstream/Epilepsy', 'E_S_seizure'): {
|
||||
'type': 'class',
|
||||
'question_template': [
|
||||
'Is the person experiencing seizure?'
|
||||
],
|
||||
'answer_template':[
|
||||
"No, the person is not experiencing seizure.",
|
||||
"Yes, the person is experiencing seizure.",
|
||||
]
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import os
|
||||
import gc
|
||||
import sys
|
||||
import json
|
||||
import pickle
|
||||
from tqdm import tqdm
|
||||
from sklearn.metrics import roc_auc_score
|
||||
|
||||
from .msitf_fusion import *
|
||||
from ..downstream_pipeline.task_specification import *
|
||||
|
||||
DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device("cpu")
|
||||
print("DEVICE:", DEVICE)
|
||||
|
||||
# ============= helper functions ================================================
|
||||
def load_model(model_name='normwear'):
|
||||
# all models should follows the function structure of AST_API
|
||||
if model_name == 'normwear':
|
||||
# model = NormWearZeroShot() # random init
|
||||
msitf_ckpt = "../data/audio_results/normwear_msitf_clean/normwear_msitf_clean_checkpoint-5.pth"
|
||||
# msitf_ckpt = "../data/audio_results/normwear_msitf_clean/normwear_msitf_clean_checkpoint-15.pth"
|
||||
model = NormWearZeroShot(msitf_ckpt=msitf_ckpt)
|
||||
# elif model_name == 'clap':
|
||||
# model = CLAP_API()
|
||||
else:
|
||||
print("Model not supported. ")
|
||||
exit()
|
||||
|
||||
# return
|
||||
model = model.to(DEVICE)
|
||||
model.eval()
|
||||
|
||||
# # check number of parameters
|
||||
# total_params = sum(p.numel() for p in model.parameters())
|
||||
# print(f"{model_name} Number of parameters: {total_params}")
|
||||
# exit()
|
||||
|
||||
return model
|
||||
|
||||
def zs_inference(
|
||||
ds_name="wearable_downstream/PPG_HTN",
|
||||
model_name='normwear-msitf',
|
||||
task_idx=0,
|
||||
root_prefix="../",
|
||||
batch_size=1024
|
||||
):
|
||||
|
||||
# construct model
|
||||
model = load_model(model_name=model_name)
|
||||
|
||||
split = json.load(open("../data/{}/train_test_split.json".format(ds_name)))
|
||||
|
||||
# get embedding for each sample
|
||||
tasks_type = dict()
|
||||
embeds_all, labels_all = list(), dict()
|
||||
curr_samples, batch_num = list(), 0
|
||||
for fn in tqdm(sorted(os.listdir('{}data/{}/sample_for_downstream'.format(root_prefix, ds_name)))):
|
||||
# edge case
|
||||
if fn[0] == '.' or fn not in split['test']:
|
||||
continue
|
||||
|
||||
# load sample
|
||||
# read data
|
||||
with open(os.path.join('{}data/{}/sample_for_downstream'.format(root_prefix, ds_name), fn), 'rb') as f:
|
||||
sample = pickle.load(f) # ['uid', 'data', 'label', 'sampling_rate']
|
||||
|
||||
# expand 1 dimension if only single dimension
|
||||
if len(sample['data'].shape) == 1:
|
||||
sample['data'] = np.expand_dims(sample['data'], axis=0) # nvar, L
|
||||
|
||||
# store for batch operation
|
||||
task_name = CLASS_NUM[ds_name]['names'][task_idx]
|
||||
if labels_all.get(task_name) is None:
|
||||
labels_all[task_name] = list()
|
||||
tasks_type[task_name] = [k for k in sample['label'][task_idx].keys()][0]
|
||||
labels_all[task_name].append(sample['label'][task_idx][tasks_type[task_name]])
|
||||
curr_samples.append(sample['data'])
|
||||
batch_num += 1
|
||||
if batch_num < batch_size:
|
||||
continue
|
||||
|
||||
# batch operation
|
||||
|
||||
# test clap pipeline
|
||||
with torch.no_grad():
|
||||
embeds_all += model(
|
||||
torch.from_numpy(np.stack(curr_samples)).float().to(DEVICE),
|
||||
[(ds_name, CLASS_NUM[ds_name]['names'][task_idx])],
|
||||
label=None
|
||||
).cpu().detach().numpy().tolist() # bn, E
|
||||
|
||||
# refresh vars
|
||||
curr_samples, batch_num = list(), 0
|
||||
|
||||
# calculate last batch
|
||||
if len(curr_samples) > 0:
|
||||
with torch.no_grad():
|
||||
embeds_all += model(
|
||||
torch.from_numpy(np.stack(curr_samples)).float().to(DEVICE),
|
||||
[(ds_name, CLASS_NUM[ds_name]['names'][task_idx])],
|
||||
label=None
|
||||
).cpu().detach().numpy().tolist() # bn, E
|
||||
|
||||
# calculate predictions
|
||||
embeds_all = torch.tensor(embeds_all).to(DEVICE) # N, E
|
||||
|
||||
for k in labels_all:
|
||||
# if has more than 1 dimensions
|
||||
if isinstance(labels_all[k][0], np.ndarray):
|
||||
if len(labels_all[k][0].shape) >= 1:
|
||||
labels_all[k] = [tuple(l) for l in labels_all[k]]
|
||||
else:
|
||||
labels_all[k] = [int(l) for l in labels_all[k]]
|
||||
|
||||
# get choices
|
||||
label_name_map = [l for l in set(labels_all[k])]
|
||||
|
||||
# text encoding
|
||||
choice_embeds = txt_encode(
|
||||
task=[(ds_name, CLASS_NUM[ds_name]['names'][task_idx])],
|
||||
label=label_name_map,
|
||||
model=model,
|
||||
task_type=tasks_type[k]
|
||||
) # num_label, E
|
||||
|
||||
# label map, y_true, distance, task_type
|
||||
scores = zs_evaluate(
|
||||
sensor_embeds=embeds_all, # tensor
|
||||
choice_embeds=choice_embeds, # tensor
|
||||
label_name_map=label_name_map, # dict
|
||||
task_type=tasks_type[k], # str
|
||||
y_trues=np.array(labels_all[k]) # np array
|
||||
)
|
||||
|
||||
print("Evaluation scores on {}:".format(ds_name, k))
|
||||
scores = [round(s*100, 3) for s in scores]
|
||||
print(scores)
|
||||
|
||||
def zs_evaluate(
|
||||
sensor_embeds=None,
|
||||
choice_embeds=None,
|
||||
label_name_map=None,
|
||||
task_type=None,
|
||||
y_trues=None
|
||||
):
|
||||
# L1 distance
|
||||
distances = torch.abs(sensor_embeds[:, None, :] - choice_embeds[None, :, :]).sum(dim=-1) # bn, num_choice
|
||||
# distances = 1 / torch.matmul(sensor_embeds, choice_embeds.T) # bn, num_choice
|
||||
# distances = distances + (0.5*dt_distances)
|
||||
|
||||
# # check
|
||||
# print(distances.shape)
|
||||
# exit()
|
||||
|
||||
if task_type == "reg":
|
||||
y_preds = np.array([label_name_map[idx] for idx in torch.argmin(distances, dim=1).cpu().numpy()]) # bn
|
||||
return [1 - np.mean(np.absolute(y_trues - y_preds) / y_trues)]
|
||||
else:
|
||||
sims = distances
|
||||
sims = 1 - (sims / torch.sum(sims, dim=1, keepdim=True))
|
||||
sims = torch.nan_to_num(sims) + 1e-8 # bn, num_choice
|
||||
|
||||
y_preds = nn.functional.softmax(sims.float(), dim=1).detach().cpu().numpy() # bn, num_choice
|
||||
|
||||
print("Classes in Test:", set(y_trues))
|
||||
if len(set(y_trues)) <= 2:
|
||||
return [roc_auc_score(y_trues, y_preds[:, 1])]
|
||||
else:
|
||||
# for i in range(len(y_trues)):
|
||||
# print(y_trues[i], np.argmax(y_preds[i]))
|
||||
# print(y_trues, y_preds)
|
||||
return [roc_auc_score(y_trues, y_preds, multi_class="ovo", average="macro")]
|
||||
|
||||
if __name__ == '__main__':
|
||||
# python3 -m src.zero_shot.zero_shot_inference clap
|
||||
# python3 -m src.zero_shot.zero_shot_inference normwear
|
||||
|
||||
# input model name
|
||||
model_name = sys.argv[1] # normwear
|
||||
|
||||
# gc.collect()
|
||||
# torch.cuda.empty_cache()
|
||||
|
||||
ds_names = [
|
||||
"wearable_downstream/PPG_HTN",
|
||||
"wearable_downstream/PPG_DM",
|
||||
"wearable_downstream/PPG_CVA",
|
||||
"wearable_downstream/PPG_CVD",
|
||||
"wearable_downstream/non_invasive_bp",
|
||||
"wearable_downstream/ppg_hgb",
|
||||
"wearable_downstream/indian-fPCG",
|
||||
"wearable_downstream/ecg_heart_cat", # **
|
||||
"wearable_downstream/drive_fatigue", # *
|
||||
"wearable_downstream/gameemo", # **
|
||||
"wearable_downstream/uci_har", # ***
|
||||
"wearable_downstream/wesad", # ***
|
||||
"wearable_downstream/emg-tfc",
|
||||
"wearable_downstream/Epilepsy",
|
||||
]
|
||||
for d_i in range(len(ds_names)):
|
||||
task_idx = 0
|
||||
if ds_names[d_i] == "wearable_downstream/Epilepsy":
|
||||
ds_names[d_i] = (ds_names[d_i], 0)
|
||||
for d_j in range(1, 5):
|
||||
ds_names.append(("wearable_downstream/Epilepsy", d_j))
|
||||
else:
|
||||
ds_names[d_i] = (ds_names[d_i], 0)
|
||||
|
||||
# launch zero shot evaluation
|
||||
for ds in ds_names:
|
||||
print(ds)
|
||||
ds_name, task_idx = ds
|
||||
|
||||
zs_inference(
|
||||
ds_name=ds_name,
|
||||
model_name=model_name,
|
||||
task_idx=task_idx,
|
||||
root_prefix="", # "../" if data not in pod, else ""
|
||||
batch_size=8
|
||||
)
|
||||
Binary file not shown.
@@ -0,0 +1,190 @@
|
||||
# check_pkl_files_and_delete.py
|
||||
import os
|
||||
import pickle
|
||||
import numpy as np
|
||||
from tqdm import tqdm
|
||||
|
||||
def check_pkl_file_integrity(filepath):
|
||||
"""
|
||||
Checks a single .pkl file for format and data integrity.
|
||||
|
||||
Args:
|
||||
filepath (str): Path to the .pkl file.
|
||||
|
||||
Returns:
|
||||
tuple: (list of errors, list of warnings, boolean indicating if 'data' has Inf)
|
||||
"""
|
||||
errors = []
|
||||
warnings = []
|
||||
data_has_inf = False # Flag to indicate if 'data' contains Inf values
|
||||
|
||||
try:
|
||||
with open(filepath, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
except Exception as e:
|
||||
errors.append(f"Failed to load pickle file: {e}")
|
||||
return errors, warnings, data_has_inf # Return False for data_has_inf on load failure
|
||||
|
||||
# 1. Check top-level keys
|
||||
expected_keys = {"uid", "data", "sampling_rate", "label"}
|
||||
actual_keys = set(data_dict.keys())
|
||||
if not expected_keys.issubset(actual_keys):
|
||||
missing = expected_keys - actual_keys
|
||||
extra = actual_keys - expected_keys
|
||||
if missing:
|
||||
errors.append(f"Missing top-level keys: {missing}")
|
||||
if extra:
|
||||
warnings.append(f"Unexpected top-level keys: {extra}")
|
||||
|
||||
# 2. Check 'uid'
|
||||
if "uid" in data_dict:
|
||||
if not isinstance(data_dict["uid"], str):
|
||||
errors.append(f"'uid' is not a string (type: {type(data_dict['uid'])}). Value: {data_dict['uid']}")
|
||||
# No 'else' needed here as missing key is caught above
|
||||
|
||||
# 3. Check 'data'
|
||||
if "data" in data_dict:
|
||||
sensor_data = data_dict["data"]
|
||||
if not isinstance(sensor_data, np.ndarray):
|
||||
errors.append(f"'data' is not a numpy.ndarray (type: {type(sensor_data)}).")
|
||||
else:
|
||||
if sensor_data.dtype != np.float16:
|
||||
warnings.append(f"'data' dtype is {sensor_data.dtype}, expected np.float16.")
|
||||
|
||||
if sensor_data.ndim != 2:
|
||||
errors.append(f"'data' has {sensor_data.ndim} dimensions, expected 2. Shape: {sensor_data.shape}")
|
||||
else:
|
||||
num_channels, sequence_length = sensor_data.shape
|
||||
if num_channels == 0: errors.append("'data' has 0 channels.")
|
||||
if sequence_length == 0: errors.append("'data' has 0 sequence length.")
|
||||
|
||||
if np.isnan(sensor_data).any():
|
||||
nan_count = np.isnan(sensor_data).sum()
|
||||
errors.append(f"'data' contains {nan_count} NaN values.")
|
||||
if np.isinf(sensor_data).any():
|
||||
inf_count = np.isinf(sensor_data).sum()
|
||||
errors.append(f"'data' contains {inf_count} Inf values.")
|
||||
data_has_inf = True # Set the flag
|
||||
# No 'else' needed here
|
||||
|
||||
# 4. Check 'sampling_rate'
|
||||
if "sampling_rate" in data_dict:
|
||||
sr = data_dict["sampling_rate"]
|
||||
if not isinstance(sr, (int, float)):
|
||||
errors.append(f"'sampling_rate' is not a number (type: {type(sr)}). Value: {sr}")
|
||||
elif sr <= 0:
|
||||
errors.append(f"'sampling_rate' is not positive. Value: {sr}")
|
||||
# No 'else' needed here
|
||||
|
||||
# 5. Check 'label'
|
||||
if "label" in data_dict:
|
||||
labels = data_dict["label"]
|
||||
if not isinstance(labels, list):
|
||||
errors.append(f"'label' is not a list (type: {type(labels)}).")
|
||||
else:
|
||||
if not labels: warnings.append("'label' list is empty.")
|
||||
for i, label_item in enumerate(labels):
|
||||
if not isinstance(label_item, dict):
|
||||
errors.append(f"Item {i} in 'label' list is not a dict (type: {type(label_item)}).")
|
||||
continue
|
||||
if len(label_item) != 1:
|
||||
errors.append(f"Item {i} in 'label' dict does not have exactly one key. Keys: {list(label_item.keys())}")
|
||||
continue
|
||||
|
||||
task_type, label_value = list(label_item.items())[0]
|
||||
if task_type not in ["class", "reg"]:
|
||||
errors.append(f"Item {i} in 'label' dict has invalid task type '{task_type}'.")
|
||||
|
||||
if task_type == "class" and not isinstance(label_value, (int, np.integer)):
|
||||
warnings.append(f"Label for 'class' task (item {i}) is not an integer. Value: {label_value}")
|
||||
elif task_type == "reg" and not isinstance(label_value, (int, float, np.number)):
|
||||
warnings.append(f"Label for 'reg' task (item {i}) is not a number. Value: {label_value}")
|
||||
|
||||
if label_value is None:
|
||||
errors.append(f"Label value for task '{task_type}' (item {i}) is None.")
|
||||
# No 'else' needed here
|
||||
|
||||
return errors, warnings, data_has_inf
|
||||
|
||||
def main():
|
||||
target_directory = input("Enter the directory containing .pkl files: ")
|
||||
|
||||
if not os.path.isdir(target_directory):
|
||||
print(f"Error: Directory '{target_directory}' not found.")
|
||||
return
|
||||
|
||||
# --- 新增:确认是否删除文件 ---
|
||||
confirm_delete = input("Do you want to DELETE files where 'data' contains Inf values? (yes/no): ").strip().lower()
|
||||
if confirm_delete == 'yes':
|
||||
print("\n!!! WARNING: Files with Inf values in 'data' will be PERMANENTLY DELETED. !!!")
|
||||
final_confirm = input("Are you absolutely sure? This cannot be undone. (yes/no): ").strip().lower()
|
||||
if final_confirm != 'yes':
|
||||
print("Deletion cancelled by user.")
|
||||
confirm_delete = 'no'
|
||||
else:
|
||||
print("Files will NOT be deleted.")
|
||||
# --- 结束新增 ---
|
||||
|
||||
print(f"\nScanning directory: {target_directory}")
|
||||
|
||||
pkl_files = [os.path.join(target_directory, f) for f in os.listdir(target_directory) if f.endswith(".pkl")]
|
||||
|
||||
if not pkl_files:
|
||||
print("No .pkl files found in the directory.")
|
||||
return
|
||||
|
||||
all_files_ok_initially = True # Tracks if any file had issues before potential deletion
|
||||
total_errors = 0
|
||||
total_warnings = 0
|
||||
files_deleted_count = 0
|
||||
deleted_files_log = []
|
||||
|
||||
for pkl_file_path in tqdm(pkl_files, desc="Checking files"):
|
||||
errors, warnings, data_has_inf = check_pkl_file_integrity(pkl_file_path)
|
||||
|
||||
if errors or warnings:
|
||||
all_files_ok_initially = False
|
||||
print(f"\n--- Issues found in: {os.path.basename(pkl_file_path)} ---")
|
||||
if errors:
|
||||
total_errors += len(errors)
|
||||
print(" Errors:")
|
||||
for err in errors:
|
||||
print(f" - {err}")
|
||||
if warnings:
|
||||
total_warnings += len(warnings)
|
||||
print(" Warnings:")
|
||||
for warn in warnings:
|
||||
print(f" - {warn}")
|
||||
|
||||
# --- 新增:删除逻辑 ---
|
||||
if data_has_inf and confirm_delete == 'yes':
|
||||
try:
|
||||
os.remove(pkl_file_path)
|
||||
print(f" DELETED file: {os.path.basename(pkl_file_path)} due to Inf values in 'data'.")
|
||||
files_deleted_count += 1
|
||||
deleted_files_log.append(os.path.basename(pkl_file_path))
|
||||
except OSError as e:
|
||||
print(f" ERROR: Could not delete file {os.path.basename(pkl_file_path)}: {e}")
|
||||
# --- 结束新增 ---
|
||||
|
||||
print("\n--- Scan Complete ---")
|
||||
if all_files_ok_initially and files_deleted_count == 0:
|
||||
print("All .pkl files seem to be in the correct format and have no NaN/Inf in 'data'.")
|
||||
else:
|
||||
print(f"Initial scan found {total_errors} error(s) and {total_warnings} warning(s).")
|
||||
|
||||
if files_deleted_count > 0:
|
||||
print(f"\nSuccessfully deleted {files_deleted_count} file(s) containing Inf values in 'data':")
|
||||
for fname in deleted_files_log:
|
||||
print(f" - {fname}")
|
||||
elif confirm_delete == 'yes':
|
||||
print("\nNo files were deleted (either no Inf values found or deletion was cancelled).")
|
||||
|
||||
if not all_files_ok_initially and files_deleted_count < total_errors and confirm_delete == 'yes': # Check if other errors remain
|
||||
print("\nNote: Some files with other errors (not Inf in data) might still exist.")
|
||||
elif not all_files_ok_initially and confirm_delete != 'yes':
|
||||
print("\nPlease review the messages above for files with issues.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
import os
|
||||
import pickle
|
||||
import numpy as np
|
||||
from tqdm import tqdm
|
||||
import sys
|
||||
import concurrent.futures
|
||||
import traceback
|
||||
from typing import Dict, List, Tuple, Any, Optional
|
||||
import collections
|
||||
|
||||
# --- 常量和配置 (无变化) ---
|
||||
FOLDER1_PATH = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/ecg_full'
|
||||
FOLDER2_PATH = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/ppg_full'
|
||||
COMMON_TIMESTAMPS_FILE = 'common1.txt'
|
||||
OUTPUT_BASE_NAME = 'combined_processed_data_2d'
|
||||
OUTPUT_FOLDER = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/full_data'
|
||||
TIMESTAMP_LIMIT: Optional[int] = None
|
||||
CHUNK_SIZE = 20
|
||||
# 保持较低的进程数以避免内存问题
|
||||
NUM_PROCESSES: Optional[int] = 2
|
||||
WORKER_CACHE_SIZE = 10
|
||||
|
||||
TIMESTAMP_KEY = 'timestamp'
|
||||
DATA_KEY = 'data'
|
||||
|
||||
# --- 全局变量 (无变化) ---
|
||||
worker_index1: Optional[Dict[Any, Tuple[str, int]]] = None
|
||||
worker_index2: Optional[Dict[Any, Tuple[str, int]]] = None
|
||||
_worker_file_cache: Optional[collections.OrderedDict[str, List[Dict[str, Any]]]] = None
|
||||
|
||||
# --- 索引构建、读取Timestamp、降采样、Worker初始化、缓存加载函数 (均无变化) ---
|
||||
def build_timestamp_index(folder_path: str, description: str) -> Dict[Any, Tuple[str, int]]:
|
||||
timestamp_index: Dict[Any, Tuple[str, int]] = {}
|
||||
if not os.path.isdir(folder_path):
|
||||
print(f"错误:索引构建失败,文件夹未找到或不是一个目录:{folder_path}", file=sys.stderr)
|
||||
return timestamp_index
|
||||
all_files = [f for f in os.listdir(folder_path) if f.endswith('.pkl')]
|
||||
print(f"开始构建索引 for {description}...")
|
||||
for filename in tqdm(all_files, desc=description, unit="file"):
|
||||
file_path = os.path.join(folder_path, filename)
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
data_list = pickle.load(f)
|
||||
if isinstance(data_list, list):
|
||||
for i, item in enumerate(data_list):
|
||||
if isinstance(item, dict) and TIMESTAMP_KEY in item:
|
||||
ts = item[TIMESTAMP_KEY]
|
||||
timestamp_index[ts] = (file_path, i)
|
||||
except Exception as e:
|
||||
print(f"索引构建处理文件 {file_path} 时发生错误:{e}", file=sys.stderr)
|
||||
return timestamp_index
|
||||
|
||||
def read_common_timestamps(file_path: str) -> List[Any]:
|
||||
common_timestamps: List[Any] = []
|
||||
if not os.path.exists(file_path):
|
||||
print(f"错误:未找到共有的 timestamp 文件:{file_path}", file=sys.stderr)
|
||||
return common_timestamps
|
||||
print(f"正在读取共有的 timestamp 文件:{file_path}")
|
||||
try:
|
||||
with open(file_path, 'r') as f:
|
||||
for line in tqdm(f, desc="读取 timestamp", unit="line"):
|
||||
ts_str = line.strip()
|
||||
if ts_str:
|
||||
common_timestamps.append(ts_str)
|
||||
except Exception as e:
|
||||
print(f"读取共有的 timestamp 文件时发生错误:{e}", file=sys.stderr)
|
||||
return common_timestamps
|
||||
|
||||
def downsample_multidim(data: np.ndarray, target_length: int, axis: int = 0) -> np.ndarray:
|
||||
current_length = data.shape[axis]
|
||||
if current_length == target_length:
|
||||
return data
|
||||
if target_length <= 0:
|
||||
return np.empty((*data.shape[:axis], 0, *data.shape[axis+1:]), dtype=data.dtype)
|
||||
indices = np.linspace(0, current_length - 1, target_length, dtype=int)
|
||||
return np.take(data, indices, axis=axis)
|
||||
|
||||
def worker_init(idx1: Dict[Any, Tuple[str, int]], idx2: Dict[Any, Tuple[str, int]]):
|
||||
global worker_index1, worker_index2, _worker_file_cache
|
||||
worker_index1 = idx1
|
||||
worker_index2 = idx2
|
||||
_worker_file_cache = collections.OrderedDict()
|
||||
|
||||
def load_data_from_file_cached(file_path: str) -> Optional[List[Dict[str, Any]]]:
|
||||
global _worker_file_cache, WORKER_CACHE_SIZE
|
||||
if _worker_file_cache is None: return None
|
||||
if file_path in _worker_file_cache:
|
||||
data_list = _worker_file_cache.pop(file_path)
|
||||
_worker_file_cache[file_path] = data_list
|
||||
return data_list
|
||||
else:
|
||||
try:
|
||||
with open(file_path, 'rb') as f: data_list = pickle.load(f)
|
||||
_worker_file_cache[file_path] = data_list
|
||||
if len(_worker_file_cache) > WORKER_CACHE_SIZE: _worker_file_cache.popitem(last=False)
|
||||
return data_list
|
||||
except Exception as e:
|
||||
print(f"Worker缓存加载失败 {file_path}: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
# --- 核心处理函数 (已修改) ---
|
||||
def process_single_timestamp(ts: Any) -> Optional[Dict[str, Any]]:
|
||||
global worker_index1, worker_index2
|
||||
|
||||
if worker_index1 is None or worker_index2 is None:
|
||||
raise RuntimeError(f"Worker索引未初始化")
|
||||
|
||||
location1 = worker_index1.get(ts)
|
||||
location2 = worker_index2.get(ts)
|
||||
|
||||
if not location1 or not location2:
|
||||
return None
|
||||
|
||||
file1_path, index1 = location1
|
||||
file2_path, index2 = location2
|
||||
|
||||
data1_list = load_data_from_file_cached(file1_path)
|
||||
data2_list = load_data_from_file_cached(file2_path)
|
||||
if not data1_list or not data2_list:
|
||||
return None
|
||||
|
||||
try:
|
||||
item1 = data1_list[index1]
|
||||
item2 = data2_list[index2]
|
||||
|
||||
# 确保ECG是一维数组 (length,)
|
||||
ecg_data = item1[DATA_KEY].flatten()
|
||||
ppg_acc_data = item2[DATA_KEY]
|
||||
|
||||
# --- 关键修改:检查并修正PPG/ACC数据的方向 ---
|
||||
# 假设通道数(4)远小于信号长度
|
||||
# 如果形状是 (4, length),则进行转置
|
||||
if ppg_acc_data.ndim == 2 and ppg_acc_data.shape[0] < ppg_acc_data.shape[1]:
|
||||
# 这是一个很好的指示,说明数据是 (channels, length) 格式
|
||||
# 我们需要的是 (length, channels)
|
||||
ppg_acc_data = ppg_acc_data.T # 转置操作
|
||||
|
||||
# --- 修改结束 ---
|
||||
|
||||
# 现在可以安全地假设 ppg_acc_data 的形状是 (length, 4)
|
||||
ecg_len = len(ecg_data)
|
||||
ppg_acc_len = ppg_acc_data.shape[0]
|
||||
|
||||
target_length = min(ecg_len, ppg_acc_len)
|
||||
|
||||
if ecg_len > target_length:
|
||||
ecg_data = downsample_multidim(ecg_data, target_length, axis=0)
|
||||
|
||||
if ppg_acc_len > target_length:
|
||||
# 降采样是沿着 axis=0 (长度维度) 进行的
|
||||
ppg_acc_data = downsample_multidim(ppg_acc_data, target_length, axis=0)
|
||||
|
||||
# 分离 PPG 和 ACC (现在这个切片逻辑是安全的)
|
||||
ppg = ppg_acc_data[:, 0] # 第1列是PPG
|
||||
acc = ppg_acc_data[:, 1:4] # 第2到4列是ACC
|
||||
|
||||
# 合并为 (5, length)
|
||||
# np.stack 会将一系列一维数组堆叠成一个二维数组
|
||||
combined = np.stack([
|
||||
ecg_data.astype(np.float32), # 形状: (target_length,)
|
||||
ppg.astype(np.float32), # 形状: (target_length,)
|
||||
acc[:, 0].astype(np.float32), # 形状: (target_length,)
|
||||
acc[:, 1].astype(np.float32), # 形状: (target_length,)
|
||||
acc[:, 2].astype(np.float32) # 形状: (target_length,)
|
||||
], axis=0) # axis=0 使它们成为行,最终形状 (5, target_length)
|
||||
|
||||
return {TIMESTAMP_KEY: ts, DATA_KEY: combined}
|
||||
|
||||
except Exception as e:
|
||||
print(f"处理 {ts} 时发生错误 (文件: {file1_path}, {file2_path}): {e}", file=sys.stderr)
|
||||
traceback.print_exc()
|
||||
return None
|
||||
|
||||
# --- 主程序 (无变化) ---
|
||||
if __name__ == '__main__':
|
||||
print("--- 开始处理 (使用降采样,自动修正数据方向) ---")
|
||||
|
||||
common_ts = read_common_timestamps(COMMON_TIMESTAMPS_FILE)
|
||||
if TIMESTAMP_LIMIT:
|
||||
common_ts = common_ts[:TIMESTAMP_LIMIT]
|
||||
|
||||
index1 = build_timestamp_index(FOLDER1_PATH, "ECG索引")
|
||||
index2 = build_timestamp_index(FOLDER2_PATH, "PPG索引")
|
||||
if not index1 or not index2:
|
||||
sys.exit()
|
||||
|
||||
valid_ts = []
|
||||
for ts in common_ts:
|
||||
if ts in index1 and ts in index2:
|
||||
valid_ts.append(ts)
|
||||
valid_ts.sort(key=lambda x: (index1[x][0], index2[x][0], x))
|
||||
|
||||
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
||||
chunk = []
|
||||
chunk_num = 1
|
||||
processed = 0
|
||||
|
||||
try:
|
||||
with concurrent.futures.ProcessPoolExecutor(
|
||||
max_workers=NUM_PROCESSES,
|
||||
initializer=worker_init,
|
||||
initargs=(index1, index2)
|
||||
) as executor:
|
||||
futures = {executor.submit(process_single_timestamp, ts): ts for ts in valid_ts}
|
||||
|
||||
for future in tqdm(concurrent.futures.as_completed(futures), total=len(valid_ts), desc="处理中"):
|
||||
ts = futures[future]
|
||||
try:
|
||||
result = future.result()
|
||||
if result:
|
||||
# 验证一下输出形状 (可选,但有助于调试)
|
||||
if result[DATA_KEY].shape[0] != 5:
|
||||
print(f"警告:时间戳 {ts} 的输出形状不正确: {result[DATA_KEY].shape}", file=sys.stderr)
|
||||
continue
|
||||
chunk.append(result)
|
||||
processed += 1
|
||||
if len(chunk) >= CHUNK_SIZE:
|
||||
output_path = os.path.join(OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
|
||||
with open(output_path, 'wb') as f:
|
||||
pickle.dump(chunk, f)
|
||||
chunk = []
|
||||
chunk_num += 1
|
||||
except Exception as e:
|
||||
print(f"处理 {ts} 的 future 时严重失败: {e}")
|
||||
except concurrent.futures.process.BrokenProcessPool:
|
||||
print("\n错误:进程池已损坏。通常是由于内存不足。请尝试将 NUM_PROCESSES 减小到 1。", file=sys.stderr)
|
||||
|
||||
if chunk:
|
||||
output_path = os.path.join(OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
|
||||
with open(output_path, 'wb') as f:
|
||||
pickle.dump(chunk, f)
|
||||
|
||||
print(f"处理完成!成功处理 {processed} 条数据,保存为 {chunk_num} 个文件。")
|
||||
+441513
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
import pickle
|
||||
import numpy as np
|
||||
from NormWear.pretrain_pipeline import dataset
|
||||
import os
|
||||
import tqdm
|
||||
import torch
|
||||
'''
|
||||
这个文件用于生成cwt,包含cwt变换和添加cwt字段
|
||||
|
||||
'''
|
||||
# # 读取pkl文件
|
||||
# with open('small_batch.pkl', 'rb') as f:
|
||||
# data = pickle.load(f,encoding="latin1")
|
||||
|
||||
'''首先要添加cwt字段
|
||||
'''
|
||||
# 添加cwt字段(使用空列表作为初始值,也可以改为None或其他空值类型)
|
||||
# data['cwt'] = np.array([]) # 或 data['cwt'] = None
|
||||
|
||||
# 写回pkl文件(注意会覆盖原文件)
|
||||
# with open('data\pretrain\dalia\demo2.pkl', 'wb') as f:
|
||||
# pickle.dump(data, f)
|
||||
|
||||
|
||||
'''cwt convert'''
|
||||
def process_pkl_file(pkl_path):
|
||||
"""处理单个 pkl 文件,生成并保存 CWT 特征"""
|
||||
with open(pkl_path, 'rb') as f:
|
||||
data_dict = pickle.load(f)
|
||||
|
||||
# 原始数据存储在 'data' 字段,形状为 [n_var, sequence_length]
|
||||
raw_signal = torch.from_numpy(data_dict['data']).float() # 转换为张量
|
||||
|
||||
# 生成 CWT 特征
|
||||
cwt_output = dataset.cwt_wrap(raw_signal) # 输出形状 [n_var, 3, L, 65]
|
||||
|
||||
# 将 CWT 保存到字典
|
||||
data_dict['cwt'] = cwt_output.numpy() # 转回 numpy 便于存储
|
||||
|
||||
# 保存更新后的数据
|
||||
with open(pkl_path, 'wb') as f:
|
||||
pickle.dump(data_dict, f)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 指定原始数据目录(用户需替换为实际路径)
|
||||
file = r"data\pretrain\dalia\00002384848d4e789cad2bc66153e519_20230615064144_seg1.pkl"
|
||||
print("begin")
|
||||
process_pkl_file(file)
|
||||
with open(file, "rb") as f:
|
||||
sample = pickle.load(f,encoding="latin1")
|
||||
print(type(sample)) # 示例输出 (2, 1000) → n_var=2
|
||||
print(sample['data'].shape)
|
||||
print(sample['cwt'].shape)
|
||||
@@ -0,0 +1,263 @@
|
||||
import os
|
||||
import pickle
|
||||
import json
|
||||
import shutil
|
||||
from sklearn.model_selection import train_test_split
|
||||
from tqdm import tqdm
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
import math
|
||||
|
||||
# ==============================================================================
|
||||
# --- 1. MASTER CONFIGURATION ---
|
||||
# ==============================================================================
|
||||
|
||||
# --- A. 原始数据源 ---
|
||||
RAW_DATA_FOLDERS = ['/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/compress_file/processed_ppg/train', '/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/compress_file/processed_ppg/test']
|
||||
|
||||
# --- B. 初始划分配置 ---
|
||||
# 【修改】: 移除 TRAIN_LABELS_TO_KEEP,因为现在是基于二分类标签来选择
|
||||
# 【修改】: 移除 NUM_TRAIN_SAMPLES 和 NUM_TEST_SAMPLES,替换为新的控制参数
|
||||
# 【新增】: 控制最终训练集和测试集的总样本数(基于原始文件)
|
||||
TOTAL_TRAIN_SAMPLES = 12000 # 训练集总样本数
|
||||
TOTAL_TEST_SAMPLES = 3000 # 测试集总样本数
|
||||
|
||||
# 【新增】: 控制最终训练集和测试集中的患病率(正样本比例)
|
||||
# 例如,0.05 表示 5% 的患病率
|
||||
TARGET_TRAIN_PREVALENCE = 0.5
|
||||
TARGET_TEST_PREVALENCE = 0.1
|
||||
|
||||
# 用于二分类转换的标签定义
|
||||
POSITIVE_CLASS_LABELS = [2] # 哪些原始标签被视为“患病”(正样本,binary_label=1)
|
||||
CONTROL_GROUP_LABEL = 1 # 哪个原始标签被视为“健康”(负样本,binary_label=0)
|
||||
|
||||
# 用于保证划分可复现的随机种子
|
||||
RANDOM_STATE = 42
|
||||
|
||||
# --- C. 分段处理配置 ---
|
||||
TARGET_LENGTH = 390
|
||||
OVERLAP_RATIO = 0.5
|
||||
|
||||
# --- D. 输出路径配置 ---
|
||||
OUTPUT_BASE_PATH = "/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/"
|
||||
OUTPUT_DATASET_NAME = "ppg22" # 建议用新名字以区分
|
||||
OUTPUT_SAMPLES_SUBFOLDER = "sample_for_downstream"
|
||||
TEMP_SPLIT_FILENAME = "temp_initial_split.json"
|
||||
|
||||
# ==============================================================================
|
||||
# --- 2. CORE FUNCTION 1: CREATE INITIAL SPLIT (基于原始文件) ---
|
||||
# ==============================================================================
|
||||
|
||||
def get_class_label(file_path):
|
||||
"""辅助函数:读取pkl文件并返回其'class'标签。"""
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
data = pickle.load(f)
|
||||
for label_dict in data.get('label', []):
|
||||
if 'class' in label_dict:
|
||||
return label_dict['class']
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error reading {file_path}: {e}")
|
||||
return None
|
||||
|
||||
# 【重大修改】: 重写 create_initial_split 函数
|
||||
def create_initial_split():
|
||||
"""
|
||||
根据目标样本数和患病率,从原始文件中抽取正负样本,并生成一个临时的JSON文件。
|
||||
"""
|
||||
print("--- Step 1: Creating Initial Split with Prevalence Control ---")
|
||||
|
||||
# 1. 扫描所有原始文件,并进行二分类标注
|
||||
all_samples_info = []
|
||||
for folder in RAW_DATA_FOLDERS:
|
||||
if not os.path.isdir(folder):
|
||||
print(f"Warning: Raw data folder '{folder}' not found. Skipping.")
|
||||
continue
|
||||
for filename in os.listdir(folder):
|
||||
if filename.endswith('.pkl'):
|
||||
file_path = os.path.join(folder, filename)
|
||||
original_label = get_class_label(file_path)
|
||||
if original_label is not None:
|
||||
# 判断是正样本、负样本还是其他
|
||||
if original_label in POSITIVE_CLASS_LABELS:
|
||||
binary_label = 1
|
||||
elif original_label == CONTROL_GROUP_LABEL:
|
||||
binary_label = 0
|
||||
else:
|
||||
continue # 忽略不属于正负样本定义的其他标签
|
||||
|
||||
all_samples_info.append({
|
||||
'name': filename,
|
||||
'path': file_path,
|
||||
'original_label': original_label,
|
||||
'binary_label': binary_label
|
||||
})
|
||||
|
||||
if not all_samples_info:
|
||||
raise ValueError("No valid .pkl files found matching positive or control labels.")
|
||||
|
||||
# 2. 将所有样本按二分类标签分组
|
||||
positive_pool = [s for s in all_samples_info if s['binary_label'] == 1]
|
||||
negative_pool = [s for s in all_samples_info if s['binary_label'] == 0]
|
||||
|
||||
print(f"Found {len(all_samples_info)} total eligible original samples.")
|
||||
print(f" - Positive samples (disease): {len(positive_pool)}")
|
||||
print(f" - Negative samples (control): {len(negative_pool)}")
|
||||
|
||||
# 3. 定义一个内部函数来执行抽样,避免代码重复
|
||||
def sample_dataset(total_samples, target_prevalence, pos_pool, neg_pool, dataset_name):
|
||||
print(f"\nSampling for {dataset_name} set...")
|
||||
|
||||
# 计算需要的正负样本数量
|
||||
num_positive = math.ceil(total_samples * target_prevalence)
|
||||
num_negative = total_samples - num_positive
|
||||
|
||||
print(f"Target: {total_samples} total samples ({num_positive} positive, {num_negative} negative).")
|
||||
|
||||
# 检查样本池是否有足够样本
|
||||
if len(pos_pool) < num_positive:
|
||||
print(f"Warning: Not enough positive samples for {dataset_name}. Requested {num_positive}, but only {len(pos_pool)} available. Using all.")
|
||||
num_positive = len(pos_pool)
|
||||
if len(neg_pool) < num_negative:
|
||||
print(f"Warning: Not enough negative samples for {dataset_name}. Requested {num_negative}, but only {len(neg_pool)} available. Using all.")
|
||||
num_negative = len(neg_pool)
|
||||
|
||||
# 从池中随机抽取样本
|
||||
rng = np.random.RandomState(RANDOM_STATE)
|
||||
|
||||
# 使用 permutation + slicing 来实现无放回抽样
|
||||
pos_indices = rng.permutation(len(pos_pool))[:num_positive]
|
||||
neg_indices = rng.permutation(len(neg_pool))[:num_negative]
|
||||
|
||||
selected_pos = [pos_pool[i] for i in pos_indices]
|
||||
selected_neg = [neg_pool[i] for i in neg_indices]
|
||||
|
||||
# 合并并打乱
|
||||
final_dataset = selected_pos + selected_neg
|
||||
rng.shuffle(final_dataset)
|
||||
|
||||
# 从总池中移除已选中的样本,以供下一个数据集使用
|
||||
remaining_pos = [p for i, p in enumerate(pos_pool) if i not in pos_indices]
|
||||
remaining_neg = [n for i, n in enumerate(neg_pool) if i not in neg_indices]
|
||||
|
||||
actual_prevalence = len(selected_pos) / len(final_dataset) if final_dataset else 0
|
||||
print(f"Created {dataset_name} set with {len(final_dataset)} samples. Actual prevalence: {actual_prevalence:.3f}")
|
||||
|
||||
return final_dataset, remaining_pos, remaining_neg
|
||||
|
||||
# 4. 依次为训练集和测试集抽样
|
||||
# 首先抽训练集
|
||||
final_train_pool, remaining_pos_pool, remaining_neg_pool = sample_dataset(
|
||||
TOTAL_TRAIN_SAMPLES, TARGET_TRAIN_PREVALENCE, positive_pool, negative_pool, "Train"
|
||||
)
|
||||
|
||||
# 然后从剩余的样本中抽测试集
|
||||
final_test_pool, _, _ = sample_dataset(
|
||||
TOTAL_TEST_SAMPLES, TARGET_TEST_PREVALENCE, remaining_pos_pool, remaining_neg_pool, "Test"
|
||||
)
|
||||
|
||||
# 5. 生成临时的划分文件
|
||||
initial_split_data = {
|
||||
'train': {s['name']: s['path'] for s in final_train_pool},
|
||||
'test': {s['name']: s['path'] for s in final_test_pool}
|
||||
}
|
||||
|
||||
with open(TEMP_SPLIT_FILENAME, 'w') as f:
|
||||
json.dump(initial_split_data, f, indent=2)
|
||||
|
||||
print(f"\nInitial split generated with {len(final_train_pool)} train and {len(final_test_pool)} test files.")
|
||||
print(f"Temporary split file created at: {TEMP_SPLIT_FILENAME}")
|
||||
return TEMP_SPLIT_FILENAME
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# --- 3. CORE FUNCTION 2: SEGMENT AND FINALIZE DATASET (保持不变) ---
|
||||
# ==============================================================================
|
||||
|
||||
def segment_and_finalize_dataset(initial_split_file):
|
||||
"""
|
||||
读取初始划分文件,对相应的文件进行分段,并生成最终的数据集和划分JSON。
|
||||
(此函数无需修改)
|
||||
"""
|
||||
print("\n--- Step 2: Segmenting Files and Finalizing Dataset ---")
|
||||
|
||||
output_dataset_path = os.path.join(OUTPUT_BASE_PATH, OUTPUT_DATASET_NAME)
|
||||
output_samples_root = os.path.join(output_dataset_path, OUTPUT_SAMPLES_SUBFOLDER)
|
||||
os.makedirs(output_samples_root, exist_ok=True)
|
||||
|
||||
stride = int(TARGET_LENGTH * (1 - OVERLAP_RATIO))
|
||||
if stride <= 0: stride = 1
|
||||
print(f"Segmentation settings: Target Length={TARGET_LENGTH}, Stride={stride}")
|
||||
|
||||
with open(initial_split_file, 'r') as f:
|
||||
initial_split = json.load(f)
|
||||
|
||||
final_split = {'train': [], 'test': []}
|
||||
all_original_files = {**initial_split['train'], **initial_split['test']}
|
||||
|
||||
for filename, file_path in tqdm(all_original_files.items(), desc="Segmenting all selected files"):
|
||||
base_filename, ext = os.path.splitext(filename)
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
original_data_dict = pickle.load(f)
|
||||
|
||||
original_data_array = original_data_dict['data']
|
||||
if original_data_array.ndim != 2 or original_data_array.shape[1] < TARGET_LENGTH:
|
||||
continue
|
||||
|
||||
sequence_length = original_data_array.shape[1]
|
||||
chunk_index = 0
|
||||
start_index = 0
|
||||
while start_index + TARGET_LENGTH <= sequence_length:
|
||||
segment_data_array = original_data_array[:, start_index : start_index + TARGET_LENGTH]
|
||||
|
||||
new_data_dict = {
|
||||
"uid": f"{original_data_dict.get('uid', base_filename)}_chunk_{chunk_index}",
|
||||
"data": segment_data_array.astype(original_data_array.dtype),
|
||||
"sampling_rate": original_data_dict.get('sampling_rate'),
|
||||
"label": original_data_dict.get('label')
|
||||
}
|
||||
|
||||
new_chunk_filename = f"{base_filename}_chunk_{chunk_index}{ext}"
|
||||
output_file_path = os.path.join(output_samples_root, new_chunk_filename)
|
||||
|
||||
with open(output_file_path, 'wb') as nf:
|
||||
pickle.dump(new_data_dict, nf)
|
||||
|
||||
if filename in initial_split['train']:
|
||||
final_split['train'].append(new_chunk_filename)
|
||||
elif filename in initial_split['test']:
|
||||
final_split['test'].append(new_chunk_filename)
|
||||
|
||||
chunk_index += 1
|
||||
start_index += stride
|
||||
except Exception as e:
|
||||
print(f"Error processing file {filename}: {e}")
|
||||
|
||||
final_split['train'] = sorted(list(set(final_split['train'])))
|
||||
final_split['test'] = sorted(list(set(final_split['test'])))
|
||||
|
||||
print(f"\nSegmentation complete.")
|
||||
print(f"Final train set size (after segmentation): {len(final_split['train'])} chunks")
|
||||
print(f"Final test set size (after segmentation): {len(final_split['test'])} chunks")
|
||||
|
||||
final_split_path = os.path.join(output_dataset_path, "train_test_split.json")
|
||||
with open(final_split_path, 'w') as f:
|
||||
json.dump(final_split, f, indent=2)
|
||||
print(f"Final split file created at: {final_split_path}")
|
||||
|
||||
# ==============================================================================
|
||||
# --- 4. MAIN EXECUTION BLOCK (保持不变) ---
|
||||
# ==============================================================================
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
temp_split_file = create_initial_split()
|
||||
segment_and_finalize_dataset(temp_split_file)
|
||||
os.remove(temp_split_file)
|
||||
print(f"\nTemporary file '{temp_split_file}' removed.")
|
||||
print("\n🎉 Pipeline finished successfully!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nAn error occurred during the pipeline: {e}")
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user