Certainly! Below is an integrated and streamlined script that automates the mapping process by ensuring synchronization across all relevant datasets (train.tsv, val.tsv, test.tsv, and item_attributes_filtered.tsv). This script consolidates all unique asin values from these files, creates a consistent mapping, and applies this mapping to index all datasets accordingly.
Integrated Mapping Script
import numpy as np
import pandas as pd
import os
import argparse
def main(folder_name):
# File paths
train_path = os.path.join(folder_name, 'train.tsv')
val_path = os.path.join(folder_name, 'val.tsv')
test_path = os.path.join(folder_name, 'test.tsv')
attributes_path = os.path.join(folder_name, 'item_attributes_filtered.tsv')
# Read datasets
train = pd.read_csv(train_path, sep='\t', header=None, names=['user_asin', 'item_asin', 'rating'])
val = pd.read_csv(val_path, sep='\t', header=None, names=['user_asin', 'item_asin', 'rating'])
test = pd.read_csv(test_path, sep='\t', header=None, names=['user_asin', 'item_asin', 'rating'])
attributes = pd.read_csv(attributes_path, sep='\t', header=None)
# Assume the first column in attributes is 'asin' and the rest are one-hot attributes
attributes.columns = ['item_asin'] + [f'attr_{i}' for i in range(1, attributes.shape[1])]
# Concatenate all ASINs from train, val, test, and attributes to build a comprehensive mapping
all_item_asins = pd.concat([
train['item_asin'],
val['item_asin'],
test['item_asin'],
attributes['item_asin']
]).unique()
# Optional: If you also need to map user ASINs (if they are different from item ASINs)
all_user_asins = pd.concat([
train['user_asin'],
val['user_asin'],
test['user_asin']
]).unique()
# Create mappings
# Mapping for items
items_map = {asin: idx for idx, asin in enumerate(all_item_asins)}
# Mapping for users (if user ASINs are different and need separate mapping)
users_map = {u_asin: idx for idx, u_asin in enumerate(all_user_asins)}
# Save item mapping
items_map_df = pd.DataFrame(list(items_map.items()), columns=['Original_ASIN', 'Mapped_ID'])
items_map_df.to_csv(os.path.join(folder_name, 'items_map.tsv'), sep='\t', index=False)
# Save user mapping
users_map_df = pd.DataFrame(list(users_map.items()), columns=['Original_User_ASIN', 'Mapped_User_ID'])
users_map_df.to_csv(os.path.join(folder_name, 'users_map.tsv'), sep='\t', index=False)
# Apply mappings to train, val, and test datasets
train['user_asin'] = train['user_asin'].map(users_map)
train['item_asin'] = train['item_asin'].map(items_map)
val['user_asin'] = val['user_asin'].map(users_map)
val['item_asin'] = val['item_asin'].map(items_map)
test['user_asin'] = test['user_asin'].map(users_map)
test['item_asin'] = test['item_asin'].map(items_map)
# Apply mapping to attributes
attributes['item_asin'] = attributes['item_asin'].map(items_map).astype(int)
# Save indexed datasets
train.to_csv(os.path.join(folder_name, 'train_indexed.tsv'), sep='\t', index=False, header=None)
val.to_csv(os.path.join(folder_name, 'val_indexed.tsv'), sep='\t', index=False, header=None)
test.to_csv(os.path.join(folder_name, 'test_indexed.tsv'), sep='\t', index=False, header=None)
attributes.to_csv(os.path.join(folder_name, 'item_attributes_filtered_indexed.tsv'), sep='\t', index=False, header=None)
# Optional: Handle multimodal embeddings if needed
# Uncomment and modify the following lines as per your embedding handling requirements
"""
multimodal_embeddings_folder = os.path.join(folder_name, args.folder_name)
multimodal_embeddings_folder_indexed = os.path.join(folder_name, f'{args.folder_name}_indexed')
if not os.path.exists(multimodal_embeddings_folder_indexed):
os.makedirs(multimodal_embeddings_folder_indexed)
for asin, idx in items_map.items():
embedding_path = os.path.join(multimodal_embeddings_folder, f'{asin}.npy')
if os.path.exists(embedding_path):
np.save(os.path.join(multimodal_embeddings_folder_indexed, f'{idx}.npy'), np.load(embedding_path))
else:
print(f'Warning: Embedding for ASIN {asin} not found at {embedding_path}')
"""
print("Mapping and indexing completed successfully.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Automated ASIN Mapping and Synchronization.")
parser.add_argument('--folder_name', type=str, help="Directory containing the TSV files.", required=True)
args = parser.parse_args()
main(args.folder_name)
Explanation of the Script
-
Argument Parsing:
- The script accepts a
--folder_name argument which specifies the directory containing all the necessary TSV files (train.tsv, val.tsv, test.tsv, item_attributes_filtered.tsv).
-
Reading Datasets:
- It reads the training, validation, and testing datasets, assuming the first two columns are
user_asin and item_asin, and the third column is rating.
- It also reads the
item_attributes_filtered.tsv file, assuming the first column is item_asin followed by one-hot encoded attribute columns.
-
Building Comprehensive Mappings:
- Item ASINs: Consolidates all unique
item_asin values from the train, val, test, and attributes datasets to ensure that every item is accounted for in the mapping.
- User ASINs: Similarly, consolidates all unique
user_asin values from the train, val, and test datasets. If your users and items share ASINs, you might not need a separate user mapping.
-
Creating and Saving Mappings:
- Items Mapping: Creates a dictionary
items_map that maps each unique item_asin to a unique integer ID.
- Users Mapping: Creates a dictionary
users_map that maps each unique user_asin to a unique integer ID.
- Saves both mappings as TSV files (
items_map.tsv and users_map.tsv) for future reference or debugging.
-
Applying Mappings:
- Transforms the
user_asin and item_asin columns in the train, val, and test datasets using the created mappings.
- Transforms the
item_asin in the attributes dataset to their corresponding mapped IDs.
-
Saving Indexed Datasets:
- Saves the transformed datasets as new TSV files with
_indexed suffixes to distinguish them from the original datasets.
Notes
-
Consistency: By consolidating all ASINs from every relevant dataset before creating the mapping, the script ensures that the mapping is comprehensive and consistent across all datasets.
-
Error Handling: The optional embedding handling section includes a warning message if an expected embedding file is missing. This can help in debugging missing data issues.
-
Flexibility: The script is designed to be easily adaptable. If your dataset has a different structure or additional processing steps, you can modify the script accordingly.
-
Performance: For very large datasets, consider optimizing the script further, such as by processing data in chunks or using more efficient data structures.
Conclusion
This integrated script automates the mapping and synchronization process, ensuring that all datasets are consistently indexed based on their asin values. By following the structure and explanations provided, you can seamlessly map and synchronize your recommendation datasets, paving the way for accurate and efficient downstream operations.