combined_data = {}
# Get all unique activity names from both datasets
all_activities = set(imu_data.keys()).union(set(emg_data.keys()))
print(f"Total unique activities to merge: {len(all_activities)}")
for activity in all_activities:
imu_features = imu_data.get(activity, []) # Get IMU features or an empty list
emg_features = emg_data.get(activity, []) # Get EMG features or an empty list
print('emg',len(emg_features))
# Combine features for the activity
combined_activity_features = []
# Print only the first sample if available
'''if imu_features:
print(f"First IMU Sample for {activity}: {imu_features[0]}")
else:
print(f"No IMU samples for {activity}.")
if emg_features:
print(f"First EMG Sample for {activity}: {emg_features[0]}")
else:
print(f"No EMG samples for {activity}.")'''
# Concatenate features where lengths match
for imu_sample in imu_features:
#print('inside it',len(imu_sample) )
for emg_sample in emg_features:
print('inside it emg_sample',len(emg_sample) )
# Combine features only if they have the same length
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample # Concatenating the feature vectors
print('inside combined',len(combined_sample))
combined_activity_features.append(combined_sample)
print('jump here')
# Store combined data, ensuring the key is correctly formatted
combined_data[(activity[0], 'Combined_Data')] = combined_activity_features
return combined_data
Assistant
The issue you are experiencing where the print statements inside the EMG sample loop do not show any output may be due to the condition that filters which EMG samples are used in the loop. If the EMG features list is empty or if none of the IMU samples match the length criteria with the EMG samples, the inner print statements will not execute.
Here's how you can troubleshoot and improve the print statements to better understand the issue:
Check Input Data: Ensure that emg_data and imu_data actually contain data for the activities you're processing.
Print All Activities: Before the nested loops, print the activity and its corresponding EMG features count to confirm data presence.
Refine Loop Logic: Instead of iterating through EMG features for each IMU feature, consider checking if at least one IMU feature matches the length of EMG features.
Here is a revision of your code with some additional print statements for clarity:
python
def fuse_sensor_data(imu_data, emg_data):
combined_data = {}
# Get all unique activity names from both datasets
all_activities = set(imu_data.keys()).union(set(emg_data.keys()))
print(f"Total unique activities to merge: {len(all_activities)}")
for activity in all_activities:
imu_features = imu_data.get(activity, []) # Get IMU features or an empty list
emg_features = emg_data.get(activity, []) # Get EMG features or an empty list
print(f'Activity: {activity} | IMU Features: {len(imu_features)} | EMG Features: {len(emg_features)}')
# Combine features for the activity
combined_activity_features = []
# Check if there are EMG samples
if emg_features:
print(f"Processing {len(emg_features)} EMG samples for activity '{activity}'")
# Concatenate features where lengths match
for imu_sample in imu_features:
for emg_sample in emg_features:
print(f'Checking IMU Sample Length: {len(imu_sample)} | EMG Sample Length: {len(emg_sample)}')
# Combine features only if they have the same length
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample # Concatenating the feature vectors
print(f'Combined Sample Length: {len(combined_sample)}')
combined_activity_features.append(combined_sample)
if not combined_activity_features:
print(f"No matching samples found for activity '{activity}'")
# Store combined data
combined_data[(activity[0], 'Combined_Data')] = combined_activity_features
return combined_data
User
Activity: ('Fetch', 'EMG_Data') | IMU Features: 0 | EMG Features: 3
Processing 3 EMG samples for activity '('Fetch', 'EMG_Data')'
No matching samples found for activity '('Fetch', 'EMG_Data')'
Activity: ('Walking', 'EMG_Data') | IMU Features: 0 | EMG Features: 3
Processing 3 EMG samples for activity '('Walking', 'EMG_Data')'
No matching samples found for activity '('Walking', 'EMG_Data')'
Activity: ('OpenSpaceWaterCollection', 'EMG_Data') | IMU Features: 0 | EMG Features: 3
Processing 3 EMG samples for activity '('OpenSpaceWaterCollection', 'EMG_Data')'
Assistant
The output you've provided indicates that for each of the activities you are processing, there are EMG features available (specifically, 3 EMG samples), but there are no IMU features (denoted by "IMU Features: 0"). As a result, the nested loop that combines IMU and EMG features never executes, leading to the message "No matching samples found for activity..." for each activity.
Key Observations
No IMU Data: Since the IMU feature count is zero for each activity, there are no samples to combine with the available EMG samples.
Only EMG Samples Available: In each case, you have EMG samples, but without corresponding IMU data, there’s no possibility for combination.
Suggestions for Improvement
Check Your Data Sources: Ensure that your imu_data variable is populated with the correct data. You might need to verify how you're populating the IMU data before this function is called.
Adjust Output or Logic: If it’s acceptable to process and return EMG data even when there are no corresponding IMU data, you need to adjust your logic to account for this. Here’s how you could modify the function to handle such situations:
Revised Function
Here's the updated function that accommodates the scenario of having EMG data without IMU data:
python
User
in the prevouis example Total unique activities to merge: 22
but should be 11
Assistant
The observation that you have 22 unique activities instead of the expected 11 indicates that there may be duplicates in your imu_data or emg_data dictionaries, or the way you are defining the activities in the datasets is causing them to be treated as different entries.
Diagnosing the Issue
Verify the Keys in imu_data and emg_data:
Print the keys from both dictionaries to see if there are any duplicates or differences in formatting (e.g., case sensitivity, extra spaces, etc.).
Check Activity Naming:
Make sure that the naming convention for activities is consistent across both datasets. Adjustments might be needed to ensure they match accurately.
Example Code to Debug Keys
Here’s a simple snippet that can help you identify what keys are present in each dataset:
python
def debug_activity_keys(imu_data, emg_data):
print("IMU Activity Keys:")
for key in imu_data.keys():
print(f"- {key}")
print("\nEMG Activity Keys:")
for key in emg_data.keys():
print(f"- {key}")
# Call this function with your datasets
debug_activity_keys(imu_data, emg_data)
Consolidating Keys
If you find that there are indeed duplicates or variations that are causing the count to be too high, you might want to normalize the activity names before combining the datasets. Here’s how you can do that:
Strip Whitespace: Remove any leading or trailing whitespace from the keys.
Convert to Lowercase: Make all activity names lowercase to prevent case-sensitive duplicates.
Example Code to Normalize Keys
Here’s an example of how you might normalize keys before merging:
python
def normalize_keys(data):
return {key.strip().lower(): value for key, value in data.items()}
# Normalize your datasets
imu_data_normalized = normalize_keys(imu_data)
emg_data_normalized = normalize_keys(emg_data)
# Now call the fuse_sensor_data with normalized data
combined_data = fuse_sensor_data(imu_data_normalized, emg_data_normalized)
User
IMU Activity Keys:
('KitchenMakingTea', 'IMU_Data')
('StandandDrink', 'IMU_Data')
('KitchenWaterCollection', 'IMU_Data')
('OpenSpaceMakingTea', 'IMU_Data')
('SitandRead', 'IMU_Data')
('Walking', 'IMU_Data')
Assistant
Based on the output you've shared for the IMU Activity Keys, it seems that each activity is represented as a tuple with a second element, denoting it's part of the IMU data. For example, ('KitchenMakingTea', 'IMU_Data') is treated as a unique key, which might lead to the discrepancy in the total count of unique activities when you compare it with the EMG activity keys.
The Issue
The IMU activity keys include a second element ('IMU_Data') that might be leading to confusion and resulting in what looks like duplicates when combined with EMG activity keys. On the other hand, if your EMG activity keys (not provided yet) have a similar structure (e.g., they all contain 'EMG_Data'), this would inflate the count of unique activities when you perform the union.
Goal
To achieve the expected count of 11 unique activities, you need to sanitize or normalize the activity keys so that only the first part of each tuple (e.g., 'KitchenMakingTea') is considered for the unique count. Let's update your code to address this:
Code to Normalize Keys
You should create a helper function that extracts just the names of the activities while disregarding the second element in the tuples:
python
def extract_activity_names(data):
return {key[0] for key in data.keys()}
# Extract the unique activity names from both datasets
imu_activity_names = extract_activity_names(imu_data)
emg_activity_names = extract_activity_names(emg_data)
# Combine the names to analyze the unique ones
all_activity_names = imu_activity_names.union(emg_activity_names)
print(f"Total unique activities to merge: {len(all_activity_names)}")
Putting It All Together
Here’s how you can integrate this normalization into the existing fuse_sensor_data function:
python
User
do it in this version def fuse_sensor_data(imu_data, emg_data):
combined_data = {}
code
# Get all unique activity names from both datasets
all_activities = set(imu_data.keys()).union(set(emg_data.keys()))
print(f"Total unique activities to merge: {len(all_activities)}")
for activity in all_activities:
imu_features = imu_data.get(activity, []) # Get IMU features or an empty list
emg_features = emg_data.get(activity, []) # Get EMG features or an empty list
print(f'Activity: {activity} | IMU Features: {len(imu_features)} | EMG Features: {len(emg_features)}')
# Combine features for the activity
combined_activity_features = []
# Check if there are EMG samples
if emg_features:
print(f"Processing {len(emg_features)} EMG samples for activity '{activity}'")
# Concatenate features where lengths match
for imu_sample in imu_features:
for emg_sample in emg_features:
print(f'Checking IMU Sample Length: {len(imu_sample)} | EMG Sample Length: {len(emg_sample)}')
# Combine features only if they have the same length
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample # Concatenating the feature vectors
print(f'Combined Sample Length: {len(combined_sample)}')
combined_activity_features.append(combined_sample)
if not combined_activity_features:
print(f"No matching samples found for activity '{activity}'")
# Store combined data
combined_data[(activity[0], 'Combined_Data')] = combined_activity_features
return combined_data
Assistant
To adjust your fuse_sensor_data function to correctly handle the unique activity keys and count them accurately, we will extract just the activity names from the tuples by using the first element of each tuple (the activity name).
Let's modify your function while keeping the existing structure:
python
def fuse_sensor_data(imu_data, emg_data):
combined_data = {}
# Extract unique activity names from both datasets while ignoring the second element of the tuple
imu_activity_names = {key[0] for key in imu_data.keys()}
emg_activity_names = {key[0] for key in emg_data.keys()}
# Combine the unique activity names
all_activities = imu_activity_names.union(emg_activity_names)
print(f"Total unique activities to merge: {len(all_activities)}") # Should now correctly show the count
for activity in all_activities:
imu_features = imu_data.get((activity, 'IMU_Data'), []) # Get IMU features or an empty list
emg_features = emg_data.get((activity, 'EMG_Data'), []) # Get EMG features or an empty list
print(f'Activity: {activity} | IMU Features: {len(imu_features)} | EMG Features: {len(emg_features)}')
# Combine features for the activity
combined_activity_features = []
# Check if there are EMG samples
if emg_features:
print(f"Processing {len(emg_features)} EMG samples for activity '{activity}'")
# Concatenate features where lengths match
for imu_sample in imu_features:
for emg_sample in emg_features:
print(f'Checking IMU Sample Length: {len(imu_sample)} | EMG Sample Length: {len(emg_sample)}')
# Combine features only if they have the same length
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample # Concatenating the feature vectors
print(f'Combined Sample Length: {len(combined_sample)}')
combined_activity_features.append(combined_sample)
if not combined_activity_features:
print(f"No matching samples found for activity '{activity}'")
# Store combined data, ensuring the key is correctly formatted
combined_data[(activity, 'Combined_Data')] = combined_activity_features
return combined_data
User
Correct this and improve it to fit the results comes from combined data: def preprocess_combined_data(training_data):
all_features = []
all_labels = []
num_samples_per_subject = []
number_of_subjects = 0
labels_per_subject = []
code
for key, file_contents_list in training_data.items():
activity_name, data_type_folder = key
number_of_subjects += len(file_contents_list)
for file_contents in file_contents_list:
rows = file_contents.strip().split('\n')[5:] # Skip the first five lines
features_per_file = []
for row in rows:
row_values = row.split(',') # Assuming comma-separated values
# Extract features (excluding the first two columns) and labels
features_row = []
# Extracting feature values and handling empty values
for val in row_values[2:]:
if val.strip(): # Check if the value is not an empty string
features_row.append(float(val))
else:
features_row.append(0.0) # Fill empty string with 0.0
if any(feature != 0.0 for feature in features_row): # Check if any feature is non-zero
features_per_file.append(features_row)
all_features.append(features_row)
all_labels.append(activity_name) # Using activity_name as the label
num_samples_per_subject.append(len(features_per_file))
labels_per_subject.append(activity_name) # Append activity name for labeling
# Convert features to a numpy array
features_array = np.array(all_features)
# Find columns with non-zero values
non_zero_columns = np.any(features_array != 0, axis=0)
# Filter features based on non-zero columns
filtered_features = features_array[:, non_zero_columns]
filtered_labels = np.array(all_labels)
print(filtered_features.shape)
Assistant
To improve your preprocess_combined_data function and ensure that it fits well with the results coming from the combined data, let's consider a few key aspects:
Code Clarity and Efficiency: Improve readability by using descriptive variable names and clean up unnecessary checks.
Data Integrity: Ensure the code handles empty data correctly and respects the shape of the dataset.
Performance: Use efficient data processing options, such as NumPy, where appropriate.
Here's a revised version of your function:
Revised Code
python
import numpy as np
def preprocess_combined_data(training_data):
all_features = []
all_labels = []
num_samples_per_subject = []
number_of_subjects = 0
labels_per_subject = []
for key, file_contents_list in training_data.items():
activity_name, data_type_folder = key
number_of_subjects += len(file_contents_list)
for file_contents in file_contents_list:
rows = file_contents.strip().split('\n')[5:] # Skip the first five lines
features_per_file = []
for row in rows:
row_values = row.split(',') # Assuming comma-separated values
# Extract and convert feature values, filling empty values with 0.0
features_row = [
float(val) if val.strip() else 0.0
for val in row_values[2:] # Assuming the first two columns are not features
]
# Only append if there's at least one non-zero feature
if any(feature != 0.0 for feature in features_row):
features_per_file.append(features_row)
all_features.append(features_row)
all_labels.append(activity_name) # Using activity_name as the label
num_samples_per_subject.append(len(features_per_file))
labels_per_subject.append(activity_name) # Append activity name for labeling
# Convert features to a numpy array
features_array = np.array(all_features)
# Find columns with non-zero values
non_zero_columns = np.any(features_array != 0, axis=0)
# Filter features based on non-zero columns
filtered_features = features_array[:, non_zero_columns]
filtered_labels = np.array(all_labels)
print(f'Filtered features shape: {filtered_features.shape}')
print(f'Total number of subjects: {number_of_subjects}')
print(f'Number of samples per subject: {num_samples_per_subject}')
print(f'Labels per subject: {labels_per_subject}')
return filtered_features, filtered_labels, num_samples_per_subject, number_of_subjects, labels_per_subject
User
Filtered features shape: (0, 0)
Total number of subjects: 18
Number of samples per subject: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Labels per subject: ['OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceMakingTea', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection', 'OpenSpaceWaterCollection']
(0, 0)
Assistant
The output you've provided indicates that the filtered features array has a shape of (0, 0), meaning that no valid feature rows passed the filtering criteria. Additionally, the number of samples per subject is all zeros, indicating that no features were successfully extracted from the training data.
Here are possible reasons for this behavior, along with improvements you can make to debug and resolve the issue:
Potential Issues
Empty or Incorrectly Formatted Input: Ensure that the training_data input is well-formed. If file_contents_list contains empty strings or improperly formatted lines, it could lead to no features being extracted.
Row Content: The logic strips the first five lines from each file contents. If the subsequent rows are unexpectedly empty or incorrectly formatted, this could cause issues in the extraction process.
Row Values Format: If the data does not properly convert to float, or if all features are zero or empty, no rows will be added to features_per_file.
Label Handling: The labels are being collected, but if all samples are empty, that may not be useful.
Steps to Debug
To help diagnose what's happening, you can add some debugging prints that give you insights into the contents of file_contents and the rows being processed. Here’s how you can adapt the preprocess_combined_data function to include more diagnostic output:
python
User
No data available after skipping the first five lines for activity 'OpenSpaceWaterCollection'
Processing file 6 for activity 'OpenSpaceWaterCollection'
No data available after skipping the first five lines for activity 'OpenSpaceWaterCollection'
Processing file 7 for activity 'OpenSpaceWaterCollection'
No data available after skipping the first five lines for activity 'OpenSpaceWaterCollection'
Processing file 8 for activity 'OpenSpaceWaterCollection'
No data available after skipping the first five lines for activity 'OpenSpaceWaterCollection'
Processing file 9 for activity 'OpenSpaceWaterCollection'
No data available after skipping the first five lines for activity 'OpenSpaceWaterCollection'
Filtered features shape: (0, 0)
Total number of subjects: 18
Number of samples per subject: []
Labels per subject: []
(0, 0) but doesn't process other activities?
Assistant
The output you're getting indicates that the file_contents_list for the activity 'OpenSpaceWaterCollection' might not contain any data after the first five lines, which leads to the message "No data available after skipping the first five lines." This issue can arise for several reasons:
Empty or Improperly Formatted Files: The files for the activity 'OpenSpaceWaterCollection' might be empty or have fewer than six lines, which would prevent any data from being processed.
File Format Consistency: If other activities are being processed but 'OpenSpaceWaterCollection' is not, it could indicate that there is an inconsistency in how the data is formatted across different activities.
Data Extraction Logic: Ensure the logic for accessing and processing the data is structured to handle multiple activities without failing when some datasets do not conform to expected patterns.
Suggestions for Troubleshooting
1. Verify Content of All Files:
Before running your function, check the actual content of your data files for all activities to confirm they all have the expected structure and sufficient lines for processing.
2. Update Debugging Information:
Include more detailed print statements to understand what’s contained in each file_contents_list regardless of the activity being processed.
3. Process All Activities:
Make sure your loop iterates over all activities and files accordingly. Here’s a more robust version of your preprocess_combined_data function that adds additional checks and more comprehensive debugging output:
Revised Function with Enhanced Debugging:
python
User
some activites are empty but not all why not procees other
Assistant
If some activities have data while others are empty and not all activities are being processed correctly, we need to ensure that your preprocess_combined_data function is effectively iterating through all available file_contents_list for each activity. Here are the reasons why this might happen, along with suggested adjustments to the function to ensure all activities, including those that are empty, are handled properly:
Reasons for Inconsistent Processing
Empty Files: If certain activities have files that are empty or contain insufficient lines, the function may skip those without processing. This is handled by the debug log, but we need to ensure it doesn’t halt the processing of other files.
Incorrect File Structure: If the structure of the data files deviate (e.g., some do not have the expected number of columns), those individually might cause failures or skips in processing.
Logic for Handling Files: The logic might be inadvertently preventing some files from being processed if it stops after the first empty file for a given activity.
Initialization of Variables: Ensure that tracking variables are properly initialized and reset for each activity, so they do not interfere with subsequent activities.
Suggested Improvements to Ensure All Activities Are Processed
Here’s an updated version of the preprocessing function that is adjusted to ensure that even if some activities have empty or improperly formatted data, it will still process all other activities:
I've added more print statements to provide context about the lengths of IMU and EMG features as well as what happens during the checks.
Each activity's feature counts are printed before entering the nested loops.
A check for matching samples is included, so you'll be informed if there are no matching features.
Run this revised code and check the console output; it should provide you with insights about what's happening with your data during execution. If your EMG features are consistently empty, then you'll need to investigate the source of emg_data.
def fuse_sensor_data(imu_data, emg_data):
combined_data = {}
# Get all unique activity names from both datasets
all_activities = set(imu_data.keys()).union(set(emg_data.keys()))
print(f"Total unique activities to merge: {len(all_activities)}")
for activity in all_activities:
imu_features = imu_data.get(activity, []) # Get IMU features or an empty list
emg_features = emg_data.get(activity, []) # Get EMG features or an empty list
print(f'Activity: {activity} | IMU Features: {len(imu_features)} | EMG Features: {len(emg_features)}')
# Combine features for the activity
combined_activity_features = []
# If EMG features are available
if emg_features:
print(f"Processing {len(emg_features)} EMG samples for activity '{activity}'")
if imu_features:
# Concatenate features if there are both IMU and EMG features
for imu_sample in imu_features:
for emg_sample in emg_features:
print(f'Checking IMU Sample Length: {len(imu_sample)} | EMG Sample Length: {len(emg_sample)}')
# Combine features only if they have the same length
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample # Concatenating the feature vectors
print(f'Combined Sample Length: {len(combined_sample)}')
combined_activity_features.append(combined_sample)
# If no IMU samples are found, consider outputting EMG data alone
if not combined_activity_features:
print(f"No matching IMU samples found for activity '{activity}'. Collecting even EMG data alone.")
combined_activity_features.extend(emg_features) # keep EMG features as-is
else:
print(f"No EMG samples available for activity '{activity}'")
if combined_activity_features:
# Store combined or EMG-only data
combined_data[(activity[0], 'Combined_Data')] = combined_activity_features
return combined_data
Key Changes:
The code now checks if there are EMG features available. If there are, it will attempt to combine them with IMU features.
If no IMU samples are found, it still collects the EMG features, ensuring that you don't lose any valuable EMG data when IMU data is unavailable.
An additional check was added to log when EMG data is collected without IMU data.
By applying these changes, your function can handle scenarios where IMU data may be missing while still preserving the EMG data for analysis.
Further Adjustments
If you confirm that there are indeed only 11 unique activities, but your logic is still resulting in more than that, ensure that when combining the data, you’re not inadvertently creating additional unique keys based on combination logic.
Final Check
After making these adjustments and normalizations, run your activity merging function again and check the printed output for the total unique activities:
python
all_activities = set(imu_data.keys()).union(set(emg_data.keys()))
print(f"Total unique activities to merge: {len(all_activities)}")
Conclusion
This analysis should help you identify the source of the discrepancy in the number of unique activities and adjust your data handling accordingly. If you're still facing issues after following these steps, please share the structure or examples of your imu_data and emg_data, and I can provide more tailored assistance.
def fuse_sensor_data(imu_data, emg_data):
combined_data = {}
# Extract unique activity names
imu_activity_names = extract_activity_names(imu_data)
emg_activity_names = extract_activity_names(emg_data)
# Combine the unique activity names
all_activity_names = imu_activity_names.union(emg_activity_names)
print(f"Total unique activities to merge: {len(all_activity_names)}") # Should be 11 now
for activity in all_activity_names:
imu_features = imu_data.get((activity, 'IMU_Data'), []) # Get IMU features or an empty list
emg_features = emg_data.get((activity, 'EMG_Data'), []) # Get EMG features or an empty list
print(f'Activity: {activity} | IMU Features: {len(imu_features)} | EMG Features: {len(emg_features)}')
# Combine features for the activity
combined_activity_features = []
if emg_features:
print(f"Processing {len(emg_features)} EMG samples for activity '{activity}'")
if imu_features:
for imu_sample in imu_features:
for emg_sample in emg_features:
print(f'Checking IMU Sample Length: {len(imu_sample)} | EMG Sample Length: {len(emg_sample)}')
if len(imu_sample) == len(emg_sample):
combined_sample = imu_sample + emg_sample
print(f'Combined Sample Length: {len(combined_sample)}')
combined_activity_features.append(combined_sample)
if not combined_activity_features:
print(f"No matching IMU samples found for activity '{activity}'. Collecting even EMG data alone.")
combined_activity_features.extend(emg_features)
else:
print(f"No EMG samples available for activity '{activity}'")
if combined_activity_features:
combined_data[(activity, 'Combined_Data')] = combined_activity_features
return combined_data
Summary
By extracting just the activity names from the tuples and only considering them for counting unique activities, you should now see that the total is correctly reported as 11.
Running this modified function should give you the correct count of unique activities while still allowing you to properly combine and handle the data. If you find any further discrepancies, especially with the EMG keys, repeating the same normalization process for them might help.
Changes Made:
Extract Unique Activity Names:
Used a set comprehension to extract the first element of each tuple from the keys of both imu_data and emg_data. This ensures that we only consider the activity name and ignore the data type suffix (like 'IMU_Data' or 'EMG_Data').
Adjust Key Access:
When obtaining features, use (activity, 'IMU_Data') and (activity, 'EMG_Data') to retrieve the corresponding feature vectors for the matching activity.
Correct Unique Activity Calculation:
Print the total number of unique activities based solely on the activity names, which should now reflect the correct count of 11 instead of 22.
Summary
This rewritten version keeps the integrity of your original function while ensuring that activities are counted based on unique names only, leading to the expected outcome. By using the set of activity names extracted from the keys, we ensure the correct merging process occurs and print relevant debug information for clarity during execution.
Changes and Improvements
List Comprehension: Utilized list comprehension for creating features_row to make the code more concise and readable.
Non-Zero Check: Added a separate comprehension to fill empty values with 0.0, which enhances clarity.
Debugging Information: The final print statements provide a clear overview of the shape of the filtered features and additional statistics, which can assist in debugging and validation.
Return Values: The function now returns the filtered features, labels, and summaries about the subjects and samples, which offers better integration for further processing steps.
Error Handling: While this code expects a specific format (e.g., skipping the first five lines, assuming comma-separated values), proper error handling can be included based on the specific data you're working with.
Considerations for Use
Ensure that you have NumPy imported (import numpy as np) because the function uses NumPy arrays.
Modify the assumption about the format of data (numeric values and the number of skipped lines) according to the specific needs of your dataset.
Test the function with your actual data to ensure that it behaves as expected, tailoring any sections as necessary based on your dataset's characteristics.
import numpy as np
def preprocess_combined_data(training_data):
all_features = []
all_labels = []
num_samples_per_subject = []
number_of_subjects = 0
labels_per_subject = []
for key, file_contents_list in training_data.items():
activity_name, data_type_folder = key
number_of_subjects += len(file_contents_list)
for index, file_contents in enumerate(file_contents_list):
print(f"Processing file {index + 1} for activity '{activity_name}'")
rows = file_contents.strip().split('\n')[5:] # Skip the first five lines
if not rows:
print(f"No data available after skipping the first five lines for activity '{activity_name}'")
continue
features_per_file = []
for row_index, row in enumerate(rows):
row_values = row.split(',') # Assuming comma-separated values
if len(row_values) < 3: # Ensure that there are enough columns
print(f"Row {row_index + 1} is not valid (too few columns): {row}")
continue
# Extract and convert feature values, filling empty values with 0.0
features_row = [
float(val) if val.strip() else 0.0
for val in row_values[2:] # Extract features
]
# Check if any feature is non-zero before appending
if any(feature != 0.0 for feature in features_row):
features_per_file.append(features_row)
all_features.append(features_row)
all_labels.append(activity_name) # Using activity_name as the label
num_samples_per_subject.append(len(features_per_file))
labels_per_subject.append(activity_name) # Append activity name for labeling
if features_per_file: # Print number of features extracted per file
print(f"Extracted {len(features_per_file)} features from file {index + 1}")
# Convert features to a numpy array if there are any features
features_array = np.array(all_features) if all_features else np.empty((0, 0))
# Find non-zero columns
non_zero_columns = np.any(features_array != 0, axis=0)
# Filter features based on non-zero columns
filtered_features = features_array[:, non_zero_columns] if features_array.size else features_array
filtered_labels = np.array(all_labels)
print(f'Filtered features shape: {filtered_features.shape}')
print(f'Total number of subjects: {number_of_subjects}')
print(f'Number of samples per subject: {num_samples_per_subject}')
print(f'Labels per subject: {labels_per_subject}')
return filtered_features, filtered_labels, num_samples_per_subject, number_of_subjects, labels_per_subject
Added Debugging Steps:
File Processing Information: I added a print statement indicating which file is currently being processed and for which activity. This helps you track progress.
Row Validation: Checks if there are enough columns in each row and prints a message if a row does not contain valid data.
Feature Extraction Validation: A print statement indicating how many features were successfully extracted from each file.
Initial Check on Feature Array: Before constructing the filtered_features, it checks if all_features contains any entries.
The above changes should help you identify where the process may be failing. After running this modified version, check the console logs for any indications of what might be going wrong with your data. Adjust your input accordingly based on the diagnostics you receive.
import numpy as np
def preprocess_combined_data(training_data):
all_features = []
all_labels = []
num_samples_per_subject = []
number_of_subjects = 0
labels_per_subject = []
for key, file_contents_list in training_data.items():
activity_name, data_type_folder = key
number_of_subjects += len(file_contents_list)
for index, file_contents in enumerate(file_contents_list):
print(f"Processing file {index + 1} for activity '{activity_name}'")
rows = file_contents.strip().split('\n')[5:] # Skip the first five lines
if not rows or all(not row.strip() for row in rows): # Check if rows are empty
print(f"File {index + 1} for activity '{activity_name}' has no data after skipping the first five lines.")
continue
features_per_file = []
for row_index, row in enumerate(rows):
row_values = row.split(',') # Assuming comma-separated values
if len(row_values) < 3: # Ensure that there are enough columns
print(f"Row {row_index + 1} in file {index + 1} is not valid (too few columns): {row}")
continue
# Extract and convert feature values, filling empty values with 0.0
features_row = [
float(val) if val.strip() else 0.0
for val in row_values[2:] # Extract features
]
# Check if any feature is non-zero before appending
if any(feature != 0.0 for feature in features_row):
features_per_file.append(features_row)
all_features.append(features_row)
all_labels.append(activity_name)
# For debug: print how many features were extracted from each file
num_samples = len(features_per_file)
num_samples_per_subject.append(num_samples)
labels_per_subject.append(activity_name)
print(f"Extracted {num_samples} features from file {index + 1} for activity '{activity_name}'")
# Convert features to a numpy array if there are any features
features_array = np.array(all_features) if all_features else np.empty((0, 0))
# Find non-zero columns
non_zero_columns = np.any(features_array != 0, axis=0)
# Filter features based on non-zero columns
filtered_features = features_array[:, non_zero_columns] if features_array.size else features_array
filtered_labels = np.array(all_labels)
print(f'Filtered features shape: {filtered_features.shape}')
print(f'Total number of subjects: {number_of_subjects}')
print(f'Number of samples per subject: {num_samples_per_subject}')
print(f'Labels per subject: {labels_per_subject}')
return filtered_features, filtered_labels, num_samples_per_subject, number_of_subjects, labels_per_subject
Key Changes:
Row Validation: Added a check to determine if the rows are empty after skipping the first five lines. This will catch cases where files may not contain sufficient data.
Detailed Processing Logs: Each file processed logs its number of features extracted, making it easier to trace which files succeed or fail in providing usable data.
Error Handling: Implemented condition checks to ensure that rows with insufficient data or empty lines are gracefully handled without terminating processing of other files or activities.
Next Steps
Run the Revised Function: Execute the enhanced function against your training_data.
Inspect Outputs: Pay close attention to the print statements for all activities; ensure they log appropriately.
Verify Input Data: If you still encounter issues, manually verify the content of specific files associated with 'OpenSpaceWaterCollection' to check for formatting or data completeness. Adjust your data preprocessing logic based on those findings.
By following these debugging steps and revisions, you should be able to identify why the function is not processing some activities and ensure that it operates correctly on all datasets.
import numpy as np
def preprocess_combined_data(training_data):
all_features = []
all_labels = []
num_samples_per_subject = []
number_of_subjects = 0
for key, file_contents_list in training_data.items():
activity_name, data_type_folder = key
number_of_subjects += len(file_contents_list)
# Initialize tracking for this activity
activity_features = []
activity_labels = []
for index, file_contents in enumerate(file_contents_list):
print(f"Processing file {index + 1} for activity '{activity_name}'")
rows = file_contents.strip().split('\n')[5:] # Skip the first five lines
# Check if there are any rows after skipping the first five lines
if not rows or all(not row.strip() for row in rows):
print(f"File {index + 1} for activity '{activity_name}' has no data after skipping the first five lines.")
continue # Skip to the next file
features_per_file = []
for row_index, row in enumerate(rows):
row_values = row.split(',') # Assuming comma-separated values
# Validate that there are enough columns
if len(row_values) < 3:
print(f"Row {row_index + 1} in file {index + 1} is not valid (too few columns): {row}")
continue # Skip invalid rows
# Extract feature values, filling empty values with 0.0
features_row = [
float(val) if val.strip() else 0.0
for val in row_values[2:] # Extract features
]
# Only keep the row if at least one feature is non-zero
if any(feature != 0.0 for feature in features_row):
features_per_file.append(features_row)
activity_features.append(features_row)
activity_labels.append(activity_name) # Use activity_name as the label
num_samples = len(features_per_file)
num_samples_per_subject.append(num_samples)
print(f"Extracted {num_samples} features from file {index + 1} for activity '{activity_name}'")
# Consolidate features and labels from this activity into the main lists
all_features.extend(activity_features)
all_labels.extend(activity_labels)
# Convert to numpy array if there are features
features_array = np.array(all_features) if all_features else np.empty((0, 0))
# Identify non-zero columns
non_zero_columns = np.any(features_array != 0, axis=0)
# Filter out zero columns
filtered_features = features_array[:, non_zero_columns] if features_array.size else features_array
filtered_labels = np.array(all_labels)
print(f'Filtered features shape: {filtered_features.shape}')
print(f'Total number of subjects: {number_of_subjects}')
print(f'Number of samples per subject: {num_samples_per_subject}')
print(f'Labels per subject: {all_labels}') # Show all collected labels
return filtered_features, filtered_labels, num_samples_per_subject, number_of_subjects
Key Changes and Improvements
Ensure Activity Processing: Each activity now initializes its own list of features and labels (activity_features and activity_labels), preventing issues from propagating if one file is empty.
Continued Processing: The function now explicitly states that it will continue processing files even if some files or rows are empty or invalid.
More Comprehensive Logging: The print statements should provide enough detail on what is happening for each file processed under each activity.
Proper Aggregation: At the end of processing all files for an activity, it combines the individual activity features into the global all_features and all_labels lists.
Recommended Next Steps
Run the Revised Function: Execute this updated function against your training_data.
Review Debug Outputs: Pay close attention to the printed outputs for all activities. Verify they behave as expected.
Inspect Data Files: If certain activities still seem to not process, manually check the respective files to confirm their content and formatting.
Trace Empty Activities: If specific activities are consistently empty, consider inspecting their associated files to understand why they do not yield results.
This should provide a clearer overall structure for processing multiple activities, accommodating empty datasets without hindering overall functionality.