for note_id, embeddings in tqdm(embeddings_dict.items(), desc=f'Aggregating with {pooling_method.__name__}'):
pooled_embedding = pooling_method(embeddings)
embeddings_list.append(pooled_embedding)
note_id_list.append(note_id)
embeddings_df = pd.DataFrame(embeddings_list, index=note_id_list)
return embeddings_df
Load datasets with progress tracking and logging
logging.info("Loading datasets...")
Timing for loading data
start_time = time.time()
with open(events_w_value_features_embeddings_embed_chunked_final, 'rb') as f:
events_df = pickle.load(f)
with open(oc_fp, 'rb') as f:
oc = pickle.load(f)
Log loading stats
end_time = time.time()
logging.info(f"Datasets loaded in {end_time - start_time:.2f} seconds.")
logging.info(f"Events DataFrame: {events_df.shape[0]} rows and {events_df.shape[1]} columns")
logging.info(f"OC DataFrame: {oc.shape[0]} rows and {oc.shape[1]} columns")
Step 1: Extract unique subjects and shuffle for train-valid-test split
logging.info("Splitting data into train/valid/test sets...")
start_time = time.time()
with open(embeddings_with_value, 'rb') as f:
embeddings_dict_value = pickle.load(f)
with open(embeddings_with_feature, 'rb') as f:
embeddings_dict_feature = pickle.load(f)
Step 3: Aggregate and save embeddings for each split
def process_and_save_embeddings(events, embeddings_dict_value, embeddings_dict_feature, split_name):
logging.info(f"Processing and saving embeddings for {split_name}...")
code
# Start time for processing
start_time = time.time()
# Extract ts_ids for the current split
split_ts_ids = events['ts_id'].unique()
logging.info(f"Number of unique ts_ids in {split_name} split: {len(split_ts_ids)}")
# Filter embeddings_dict by split ts_ids
split_value_embeddings = {k: v for k, v in embeddings_dict_value.items() if k in split_ts_ids}
split_feature_embeddings = {k: v for k, v in embeddings_dict_feature.items() if k in split_ts_ids}
# Debugging: Log the size of filtered embeddings
logging.info(f"{split_name} Value Embeddings: {len(split_value_embeddings)}")
logging.info(f"{split_name} Feature Embeddings: {len(split_feature_embeddings)}")
if not split_value_embeddings or not split_feature_embeddings:
logging.error(f"Error: No embeddings found for {split_name}.")
return
# Perform mean pooling
logging.info(f"Aggregating {split_name} embeddings using mean pooling...")
embeddings_df_value_mean = aggregate_embeddings(split_value_embeddings, mean_pooling)
embeddings_df_feature_mean = aggregate_embeddings(split_feature_embeddings, mean_pooling)
# Save mean-pooled embeddings
value_mean_path = os.path.join(output_dir, f'{split_name}_embeddings_value_mean.pkl')
feature_mean_path = os.path.join(output_dir, f'{split_name}_embeddings_feature_mean.pkl')
embeddings_df_value_mean.to_pickle(value_mean_path)
embeddings_df_feature_mean.to_pickle(feature_mean_path)
logging.info(f"Mean-pooled embeddings for {split_name} saved to {value_mean_path} and {feature_mean_path}")
# Perform max pooling
logging.info(f"Aggregating {split_name} embeddings using max pooling...")
embeddings_df_value_max = aggregate_embeddings(split_value_embeddings, max_pooling)
embeddings_df_feature_max = aggregate_embeddings(split_feature_embeddings, max_pooling)
# Save max-pooled embeddings
value_max_path = os.path.join(output_dir, f'{split_name}_embeddings_value_max.pkl')
feature_max_path = os.path.join(output_dir, f'{split_name}_embeddings_feature_max.pkl')
embeddings_df_value_max.to_pickle(value_max_path)
embeddings_df_feature_max.to_pickle(feature_max_path)
logging.info(f"Max-pooled embeddings for {split_name} saved to {value_max_path} and {feature_max_path}")
end_time = time.time()
logging.info(f"Processing for {split_name} completed in {end_time - start_time:.2f} seconds.")
Process embeddings for train, valid, and test splits
Upon reviewing the code you've provided and comparing it with the second code snippet, I've identified several areas where there may be flaws or misalignments. Below, I'll detail these issues and provide explanations to help you ensure your code is correct and aligned with the reference snippet.
1. Difference in DataFrames Used for Splitting
Your Code:
python
# Load datasets with progress tracking and logging
logging.info("Loading datasets...")
# Timing for loading data
start_time = time.time()
with open(events_w_value_features_embeddings_embed_chunked_final, 'rb') as f:
events_df = pickle.load(f)
with open(oc_fp, 'rb') as f:
oc = pickle.load(f)
You are loading an oc DataFrame and using it for splitting data into train, validation, and test sets.
Reference Code:
python
# Get train-valid-test split for sup task.
all_sup_subjects = icu.SUBJECT_ID.unique()
np.random.seed(0)
np.random.shuffle(all_sup_subjects)
S = len(all_sup_subjects)
bp1, bp2 = int(0.64*S), int(0.8*S)
train_sub = all_sup_subjects[:bp1]
valid_sub = all_sup_subjects[bp1:bp2]
test_sub = all_sup_subjects[bp2:]
The reference code uses an icu DataFrame for the splitting.
Issue Identified:
There is a potential misalignment between the DataFrames being used:
In your code, you are using oc (which likely stands for outcomes) to get SUBJECT_IDs and to map them to ts_ids.
In the reference code, icu data is used to perform these operations.
Potential Flaw:
If oc does not have a one-to-one mapping between SUBJECT_ID and ts_id analogous to the icu DataFrame, you may end up with incorrect splits. The icu DataFrame typically contains unique ICU stays (ICUSTAY_ID) mapped to patients (SUBJECT_ID), which is essential for accurate splitting based on patient-wise separation to prevent data leakage.
Recommendation:
Ensure that oc is appropriate for this purpose. If oc is not equivalent to icu in terms of containing ICU stay information (ICUSTAY_ID and SUBJECT_ID), you should replace it with the correct icu DataFrame.
Without renaming ICUSTAY_ID to ts_id, the mapping between SUBJECT_ID and ts_id may not be accurate, leading to incorrect ts_ids being used for filtering.
Recommendation:
If your oc DataFrame contains an ICUSTAY_ID column equivalent, you should rename it to ts_id to maintain consistency.
# Assign ts_ids to the respective sets based on SUBJECT_ID
train_ids = np.array(oc.loc[oc['SUBJECT_ID'].isin(train_sub), 'ts_id'])
valid_ids = np.array(oc.loc[oc['SUBJECT_ID'].isin(valid_sub), 'ts_id'])
test_ids = np.array(oc.loc[oc['SUBJECT_ID'].isin(test_sub), 'ts_id'])
You are selecting ts_ids based on SUBJECT_ID splits.
Issue Identified:
If a patient (SUBJECT_ID) has multiple ts_ids (e.g., multiple ICU stays), all their ts_ids will be in the same split in your code, which is correct and prevents data leakage.
Recommendation:
Ensure that this is intentional and that your oc DataFrame accurately reflects the mapping between patients and ICU stays.
4. Filtering of events_df
Your Code:
python
# Step 2: Filter 'events' based on the train, valid, and test ids
logging.info("Filtering events data by ts_id for each split...")
start_time = time.time()
events_train = events_df[events_df['ts_id'].isin(train_ids)]
events_valid = events_df[events_df['ts_id'].isin(valid_ids)]
events_test = events_df[events_df['ts_id'].isin(test_ids)]
You are filtering events_df based on ts_ids obtained from oc.
Reference Code:
In the reference code, after splitting, there is an additional step to filter and aggregate events:
In your code, there is no aggregation or preprocessing of events_df before filtering.
The reference code performs crucial data cleaning and aggregation before proceeding.
Potential Flaw:
By not performing the aggregation and cleaning steps, you might be working with unprocessed data, which could affect the quality of the embeddings and the downstream tasks.
Recommendation:
Include the data cleaning and aggregation steps as per the reference code before filtering the events_df into train, validation, and test sets.
5. Handling of Embeddings
Your Code:
You load pre-existing embeddings and process them based on the splits.
python
with open(embeddings_with_value, 'rb') as f:
embeddings_dict_value = pickle.load(f)
with open(embeddings_with_feature, 'rb') as f:
embeddings_dict_feature = pickle.load(f)
You then process and save the embeddings for each split.
Issue Identified:
It's essential to ensure that the embeddings correspond correctly to the ts_ids in events_df.
If there is any misalignment in the ts_ids used in events_df and those in the embeddings, you may end up with missing or incorrect embeddings.
Recommendation:
Verify that the keys in embeddings_dict_value and embeddings_dict_feature match the ts_ids in events_df. Any discrepancy could lead to errors or incomplete data.
6. Function Definitions and Usage
Your Code:
You have defined functions for pooling and aggregation:
While the functions themselves are correctly defined, you should ensure that:
The embeddings being pooled are in the correct format (e.g., list or array of embeddings).
The pooling functions match the intended mathematical operations.
Recommendation:
Double-check that the input to aggregate_embeddings is as expected and that the pooling operations produce the desired results.
7. Final Saving of Data
Your Code:
You save the processed embeddings for each split:
python
# Save mean-pooled embeddings
value_mean_path = os.path.join(output_dir, f'{split_name}_embeddings_value_mean.pkl')
feature_mean_path = os.path.join(output_dir, f'{split_name}_embeddings_feature_mean.pkl')
embeddings_df_value_mean.to_pickle(value_mean_path)
embeddings_df_feature_mean.to_pickle(feature_mean_path)
logging.info(f"Mean-pooled embeddings for {split_name} saved to {value_mean_path} and {feature_mean_path}")
Issue Identified:
Ensure that the paths are correctly specified and that the output_dir exists. Also, make sure that the data saved is in the correct format for downstream usage.
Recommendation:
Verify the output_dir and file paths.
After saving, consider adding a step to load a sample of the saved data to ensure it's correctly saved.
8. Consistency with Reference Snippet
Overall, your code performs similar steps to the reference snippet but lacks some of the data preprocessing steps present in the reference. Specifically, the reference code includes:
Filtering specific columns from events.
Converting value to float and handling missing TABLE entries.
Grouping and aggregating events data.
These steps are crucial for ensuring data integrity and preparing the data for embedding generation.
Make sure that the embeddings correspond to the correct ts_ids and that there are no missing entries.
Conclusion
Flaws Identified:
Potential misuse of the oc DataFrame instead of the icu DataFrame for splitting.
Missing data preprocessing steps for events_df.
Possible discrepancies in column names and data alignment.
Alignment with Reference Snippet:
The overarching structure aligns with the reference snippet.
To fully align, include the data preprocessing steps and ensure the correct DataFrames and mappings are used.
By addressing these issues and aligning your code with the reference snippet, you can ensure that your data splitting and processing are performed correctly, avoiding potential data leakage and ensuring data integrity for your embeddings and downstream tasks.