Spaces:
Paused
Paused
Download notebooks/step2_prepare_data.py from yrlllllllllll/MindPulse: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/yrlllllllllll/MindPulse/resolve/main/notebooks/step2_prepare_data.py
- Command line
-
hf download hf://spaces/yrlllllllllll/MindPulse/notebooks/step2_prepare_data.py
-
curl -L -o step2_prepare_data.py https://huggingface.co/spaces/yrlllllllllll/MindPulse/resolve/main/notebooks/step2_prepare_data.py
12.3 kB
| #%% | |
| import os | |
| import dill | |
| import torch | |
| import torch.nn as nn | |
| from tqdm import tqdm | |
| import numpy as np | |
| import warnings | |
| from sklearn.model_selection import KFold | |
| try: | |
| from torch_geometric.data import Data | |
| except ImportError as err: | |
| raise ImportError( | |
| "torch_geometric is required for graph conversion. " | |
| "Install it via 'pip install torch-geometric' (see https://pytorch-geometric.readthedocs.io/ " | |
| "for platform-specific instructions)." | |
| ) from err | |
| # Set a random seed for reproducibility | |
| SEED = 42 | |
| np.random.seed(SEED) | |
| torch.manual_seed(SEED) | |
| #%% | |
| def extend_labels(data_idx, n_win): | |
| """ | |
| Extends subject-level indices to window-level indices. | |
| If a subject `i` has `n_win` windows, and `i` is in `data_idx`, | |
| then indices `i*n_win` to `(i+1)*n_win - 1` are included. | |
| Args: | |
| data_idx (np.ndarray): Array of subject indices. | |
| n_win (int): Number of windows per subject. | |
| Returns: | |
| np.ndarray: Array of extended (window-level) indices. | |
| """ | |
| ex_data_idx = [] | |
| for i in range(len(data_idx)): | |
| idx = data_idx[i] | |
| st = idx * n_win | |
| en = st + n_win | |
| ex_data_idx.extend(np.linspace(st, en - 1, n_win, dtype=int)) | |
| return np.array(ex_data_idx) | |
| def get_fold_indices(scores, max_splits=5): | |
| """ | |
| Generates nested cross-validation indices (outer and inner loops) for regression targets. | |
| Args: | |
| scores (np.ndarray): Array of cognitive scores (regression targets). | |
| max_splits (int): Maximum number of folds to attempt (default: 5). | |
| Returns: | |
| dict: A dictionary containing train, test, and validation indices for each fold. | |
| Structure: {'outerX_innerY': {'train': [...], 'test': [...], 'val': [...]}} | |
| """ | |
| scores = np.asarray(scores, dtype=float) | |
| n_samples = len(scores) | |
| n_splits_outer = min(max_splits, n_samples) | |
| if n_splits_outer < 2: | |
| raise ValueError( | |
| f"Not enough samples ({n_samples}) to create at least 2 folds." | |
| ) | |
| fold_idx = dict() | |
| kf_out = KFold(n_splits=n_splits_outer, shuffle=True, random_state=SEED) | |
| for outer_id, (train_idx_out, test_idx_out) in enumerate( | |
| kf_out.split(np.zeros(n_samples)), start=1 | |
| ): | |
| n_train = len(train_idx_out) | |
| n_splits_inner = min(max_splits, n_train) | |
| # If we cannot create an inner split (too few samples), | |
| # fallback to a single inner fold that reuses the outer training data for validation. | |
| if n_splits_inner < 2: | |
| fold_idx[f'outer{outer_id}_inner1'] = { | |
| 'train': train_idx_out, | |
| 'test': test_idx_out, | |
| 'val': train_idx_out | |
| } | |
| continue | |
| kf_in = KFold(n_splits=n_splits_inner, shuffle=True, random_state=SEED) | |
| for inner_id, (train_idx_in, val_idx_in) in enumerate( | |
| kf_in.split(np.zeros(n_train)), start=1 | |
| ): | |
| train_idx = train_idx_out[train_idx_in] | |
| val_idx = train_idx_out[val_idx_in] | |
| fold_idx[f'outer{outer_id}_inner{inner_id}'] = { | |
| 'train': train_idx, | |
| 'test': test_idx_out, | |
| 'val': val_idx | |
| } | |
| return fold_idx | |
| def load_data(): | |
| """ | |
| Loads the processed dynamic graph data (node features, adjacency matrices, cognitive scores) | |
| generated by step1_compute_ldw.py. | |
| Returns: | |
| tuple: (data, adj, cognitive_scores) | |
| data (list): List of node features (correlation matrices) for each subject and window. | |
| adj (list): List of adjacency matrices for each subject and window. | |
| cognitive_scores (np.ndarray): Subject-level regression targets. | |
| """ | |
| with open('./data/ldw_data/LDW_movie-hcp_data.pkl', 'rb') as f: | |
| payload = dill.load(f) # Using dill for potentially complex objects | |
| data = payload['node_feat'] | |
| adj = payload['adj_mat'] | |
| if 'cognitive_scores' in payload: | |
| cognitive_scores = np.asarray(payload['cognitive_scores'], dtype=float) | |
| elif 'behavioral_scores' in payload: | |
| cognitive_scores = np.asarray(payload['behavioral_scores'], dtype=float) | |
| warnings.warn( | |
| "Processed data did not contain 'cognitive_scores'; falling back to legacy 'behavioral_scores'.", | |
| RuntimeWarning | |
| ) | |
| else: | |
| cognitive_scores = np.asarray(payload['labels'], dtype=float) | |
| warnings.warn( | |
| "Processed data did not contain 'cognitive_scores'; falling back to 'labels'.", | |
| RuntimeWarning | |
| ) | |
| return data, adj, cognitive_scores | |
| def get_fold_data(data, adj, seqlen, scores, indices, name, fold_key): | |
| """ | |
| Retrieves data, adjacency matrices, sequence lengths, and labels for a specific fold | |
| (train, test, or validation set) based on the generated indices. | |
| Args: | |
| data (list): All node features data. | |
| adj (list): All adjacency matrices data. | |
| seqlen (list): All sequence lengths. | |
| scores (np.ndarray): All cognitive scores. | |
| indices (dict): Dictionary of fold indices from `get_fold_indices`. | |
| name (str): 'train', 'test', or 'val'. | |
| fold_key (str): Key identifying the fold subset (`outerX_innerY`). | |
| Returns: | |
| tuple: (Corr, Adj, SeqLen, Scores) | |
| Corr (list): Node features for the specified fold. | |
| Adj (list): Adjacency matrices for the specified fold. | |
| SeqLen (list): Sequence lengths for the specified fold. | |
| Scores (np.ndarray): Behavioral scores for the specified fold. | |
| """ | |
| current_indices = indices[fold_key][name] | |
| data_fold = [data[k] for k in current_indices] | |
| adj_fold = [adj[k] for k in current_indices] | |
| seqlen_fold = [seqlen[k] for k in current_indices] | |
| score_fold = [scores[k] for k in current_indices] | |
| return data_fold, adj_fold, seqlen_fold, score_fold | |
| def pad_graph_seq(data): | |
| """ | |
| Pads sequences of graph data (node features or adjacency matrices) to the same length | |
| within a batch, preparing them for recurrent processing. | |
| Args: | |
| data (list): A list of lists, where each inner list contains | |
| the sequence of node features/adjacency matrices for a subject. | |
| Each element in the inner list is a numpy array. | |
| Returns: | |
| tuple: (sequences_padded, seqlengths) | |
| sequences_padded (torch.Tensor): Padded sequences (batch_first=True). | |
| seqlengths (torch.LongTensor): Original sequence lengths for each subject. | |
| """ | |
| # Convert inner numpy arrays to torch tensors | |
| sequences = [torch.tensor(np.array(i), dtype=torch.float32) for i in data] | |
| # Get original sequence lengths | |
| seqlengths = torch.LongTensor([len(x) for x in sequences]) | |
| # Pad sequences to the maximum length in the batch | |
| sequences_padded = nn.utils.rnn.pad_sequence(sequences, batch_first=True) | |
| return sequences_padded, seqlengths | |
| def convert2graphs(Corr, Adj, SeqLen, Scores): | |
| """ | |
| Converts lists of correlation matrices, adjacency matrices, sequence lengths, | |
| and labels into a 2D NumPy array of `torch_geometric.data.Data` objects. | |
| Each `Data` object represents a single graph (a window from a subject's sequence). | |
| Args: | |
| Corr (list): List of correlation matrices (node features). | |
| Adj (list): List of adjacency matrices. | |
| SeqLen (list): List of sequence lengths for each subject. | |
| Scores (np.ndarray): Subject-level cognitive scores. | |
| Returns: | |
| np.ndarray: A 2D NumPy array (subjects x windows) of `torch_geometric.data.Data` objects. | |
| """ | |
| n_sub = len(Corr) | |
| if n_sub == 0: | |
| return np.empty((0,), dtype=object) | |
| # Assuming all subjects have the same max number of windows after padding | |
| n_win = Corr[0].shape[0] | |
| # Initiate empty container for graphs | |
| Graph = np.empty([n_sub, n_win], dtype=object) | |
| for i in tqdm(range(n_sub), desc="Converting to PyG Graphs"): | |
| for j in range(n_win): | |
| corr = Corr[i][j] # Node features for current window | |
| adj = Adj[i][j] # Adjacency matrix for current window | |
| seqlen = SeqLen[i] # Original sequence length for current subject | |
| score = Scores[i] # Behavioral score for current subject | |
| # Determine if this graph is a padding graph (all zeros in adjacency) | |
| # This check might be too strict if a valid graph can have all-zero rows/columns. | |
| # A more robust check for padding would be based on the original sequence length. | |
| padding = (torch.sum(adj) == 0) # Check if the sum of adjacency matrix is zero | |
| # Get non-zero elements of adj matrix to form edge_index | |
| nodeFeat = corr.float() # Convert node features to float tensor | |
| num_nodes = nodeFeat.shape[0] | |
| num_node_features = nodeFeat.shape[1] | |
| # Find indices of non-zero elements (edges) | |
| index = torch.nonzero(adj) | |
| # Get values of these non-zero elements (edge attributes, if any) | |
| values = adj[index[:, 0], index[:, 1]] | |
| # Format edge_index for PyTorch Geometric (2xNumEdges) | |
| edgeIndex = index.T.long() | |
| # Edge attributes (if values are used as attributes) | |
| edgeAttr = values.unsqueeze(-1).float() | |
| adj_node = adj.float() # Adjacency matrix as a tensor | |
| score_tensor = torch.tensor(float(score), dtype=torch.float32) | |
| # Create a PyTorch Geometric Data object | |
| graph = Data(x=nodeFeat, edge_index=edgeIndex, edge_attr=edgeAttr, adj=adj_node, y=score_tensor, | |
| num_nodes=num_nodes, num_node_features=num_node_features, | |
| pad=padding, # Indicates if this is a padding graph | |
| last=(j + 1 == seqlen)) # Indicates if this is the last valid graph in the sequence | |
| Graph[i, j] = graph # Store the created graph object | |
| return Graph | |
| # Main execution block | |
| if __name__ == "__main__": | |
| saveTo = './data/folds_data/' | |
| os.makedirs(saveTo, exist_ok=True) # Create directory for saving fold data | |
| print('Loading data from step1_compute_ldw.py...') | |
| all_data, all_adj, cognitive_scores = load_data() | |
| print('Data loaded.') | |
| print('Padding graph sequences...') | |
| # Pad node features and adjacency matrices | |
| all_data_padded, seqlengths = pad_graph_seq(all_data) | |
| all_adj_padded, _ = pad_graph_seq(all_adj) # Adjacency matrices also padded | |
| print('Padding complete.') | |
| print('Generating fold indices for cross-validation...') | |
| fold_indices = get_fold_indices(cognitive_scores) | |
| print(f'Fold indices generated ({len(fold_indices)} total splits).') | |
| for fold_key in sorted(fold_indices.keys()): | |
| print(f'Processing {fold_key}...') | |
| train_idx = fold_indices[fold_key]['train'] | |
| test_idx = fold_indices[fold_key]['test'] | |
| val_idx = fold_indices[fold_key]['val'] | |
| Corr, Adj, SeqLen, Scores = get_fold_data( | |
| all_data_padded, all_adj_padded, seqlengths, cognitive_scores, fold_indices, 'train', fold_key | |
| ) | |
| train_graphs = convert2graphs(Corr, Adj, SeqLen, Scores) | |
| Corr, Adj, SeqLen, Scores = get_fold_data( | |
| all_data_padded, all_adj_padded, seqlengths, cognitive_scores, fold_indices, 'test', fold_key | |
| ) | |
| test_graphs = convert2graphs(Corr, Adj, SeqLen, Scores) | |
| Corr, Adj, SeqLen, Scores = get_fold_data( | |
| all_data_padded, all_adj_padded, seqlengths, cognitive_scores, fold_indices, 'val', fold_key | |
| ) | |
| val_graphs = convert2graphs(Corr, Adj, SeqLen, Scores) | |
| graphs = { | |
| 'train_graphs': train_graphs, | |
| 'test_graphs': test_graphs, | |
| 'val_graphs': val_graphs, | |
| 'train_indices': train_idx, | |
| 'test_indices': test_idx, | |
| 'val_indices': val_idx, | |
| } | |
| print('Saving graphs...') | |
| with open(os.path.join(saveTo, f'graphs_{fold_key}.pkl'), 'wb') as f: | |
| torch.save(graphs, f) | |
| print(f'Graphs for {fold_key} saved successfully.') | |