У меня есть датафрейм train, содержащий столбцы user_id, item_id, target (бинарная переменная, кликнул ли пользователь на предмет). Также есть датафрейм test, содержащий столбцы user_id и item_id, для которого нужно предсказать target. Напиши код для создания рекомендательной сисетмы на основе модели BERT4Rec
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# Install the RecBole library
!pip install recbole
import pandas as pd
import numpy as np
import torch
from recbole.config import Config
from recbole.data import create_dataset, data_preparation
from recbole.model.sequential_recommender import BERT4Rec
from recbole.trainer import Trainer
from recbole.utils import init_seed, init_logger
# Load your training and test dataframes
# Assuming your train DataFrame has columns: user_id, item_id, target
# And your test DataFrame has columns: user_id, item_id
# Replace 'train.csv' and 'test.csv' with your actual data file paths if needed
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# Prepare sequence data from positive interactions (where target == 1)
train_positive = train[train['target'] == 1]
# Group by user_id and collect item_ids as sequences
user_sequences = train_positive.groupby('user_id')['item_id'].apply(list).reset_index()
# Since we don't have timestamps, we'll assign arbitrary timestamps based on the order
train_positive['timestamp'] = np.arange(len(train_positive))
# Prepare the interaction data expected by RecBole
# The columns should be: user_id, item_id, timestamp (optional), and rating/label (optional)
interactions = train_positive[['user_id', 'item_id', 'timestamp']]
interactions['rating'] = 1 # Since these are positive interactions
# Save interactions to a CSV file
interactions.to_csv('train_interactions.csv', index=False)
# Prepare test interactions with dummy timestamps
test['timestamp'] = max(interactions['timestamp']) + 1
test['rating'] = 0 # Dummy rating for test data
test_interactions = test[['user_id', 'item_id', 'timestamp', 'rating']]
# Save test interactions to a CSV file
test_interactions.to_csv('test_interactions.csv', index=False)
# Define the configuration for RecBole
config_dict = {
'model': 'BERT4Rec',
'dataset': 'train_interactions', # The dataset name without file extension
'data_path': './', # The path where your data files are stored
'user_id_field': 'user_id',
'item_id_field': 'item_id',
'timestamp_field': 'timestamp',
'rating_field': 'rating',
'seq_len': 50, # Maximum sequence length for BERT4Rec
'epochs': 10,
'train_batch_size': 256,
'eval_batch_size': 256,
'learning_rate': 0.001,
'neg_sampling': None, # Disable negative sampling for full prediction
'device': 'cuda' if torch.cuda.is_available() else 'cpu',
'seed': 42,
'log_wandb': False,
'metrics': ['Recall', 'MRR', 'NDCG']
}
config = Config(model='BERT4Rec', config_dict=config_dict)
init_seed(config['seed'], config['reproducibility'])
init_logger(config)
logger = getLogger()
# Create the dataset
dataset = create_dataset(config)
# Split the dataset into training, validation, and test sets
train_data, valid_data, _ = data_preparation(config, dataset)
# Create the BERT4Rec model
model = BERT4Rec(config, train_data.dataset).to(config['device'])
# Initialize the trainer
trainer = Trainer(config, model)
# Train the model
best_valid_score, best_valid_result = trainer.fit(train_data, valid_data)
# Load the trained model for inference
# Note: If you have saved the model, you can load it using torch.load()
# Prepare the test dataset for prediction
# Map raw user/item IDs to internal IDs used by the model
user_id_series = test['user_id'].map(dataset.field2token_id['user_id'])
item_id_series = test['item_id'].map(dataset.field2token_id['item_id'])
# Handle unknown users/items by replacing NaNs with default IDs (e.g., 0)
user_id_series = user_id_series.fillna(0).astype(int)
item_id_series = item_id_series.fillna(0).astype(int)
# Create an Interaction object for test data
from recbole.data.interaction import Interaction
test_interaction = Interaction({
'user_id': torch.tensor(user_id_series.values),
'item_id': torch.tensor(item_id_series.values),
'timestamp': torch.tensor(test['timestamp'].values),
'rating': torch.tensor(test['rating'].values),
})
# Move test_interaction to the device
test_interaction = test_interaction.to(config['device'])
# Set the model to evaluation mode
model.eval()
# Disable gradient calculation for inference
with torch.no_grad():
# Get prediction scores for the test user-item pairs
scores = model.predict(test_interaction)
# The scores tensor contains the predicted likelihoods for each interaction
# Add the scores to the test DataFrame
test['predicted_score'] = scores.cpu().numpy()
# Optionally, you can set a threshold to classify the scores into binary targets
# For example, items with scores above the mean score are considered as clicked (target = 1)
threshold = test['predicted_score'].mean()
test['predicted_target'] = (test['predicted_score'] >= threshold).astype(int)
# Save the predictions to a CSV file
test[['user_id', 'item_id', 'predicted_target']].to_csv('test_predictions.csv', index=False)
print("Prediction results saved to 'test_predictions.csv'.")
This code performs the following steps:
Installs RecBole: Installs the recbole library, which provides implementations of various recommendation algorithms, including BERT4Rec.
Loads Data: Loads your training and test datasets from CSV files.
Prepares Training Data: Filters positive interactions (where target == 1) and assigns arbitrary timestamps since the original data lacks them. It then creates an interactions file in the format expected by RecBole.
Configures the Model: Sets up the configuration dictionary for RecBole, specifying parameters like the model type, data paths, batch sizes, and evaluation metrics.
Creates Dataset and Splits Data: Uses RecBole functions to create the dataset and split it into training and validation sets.
Trains BERT4Rec Model: Initializes the BERT4Rec model and trains it using the prepared data.
Prepares Test Data for Prediction: Maps the raw user and item IDs in the test set to the internal IDs used by the model. It handles unseen users or items by mapping them to a default ID.
Makes Predictions: Uses the trained model to predict the likelihood of each user-item interaction in the test set.
Processes Predictions: Assigns a binary predicted_target based on the predicted scores using a threshold (in this case, the mean score).
Saves Results: Outputs the predictions to a CSV file named test_predictions.csv.
Notes:
Sequence Information: BERT4Rec is a sequential recommendation model that relies on the sequence of items interacted with by each user. Since the original data does not include timestamps, we assign arbitrary timestamps to simulate sequence information.
Handling Unknown Users/Items: The code maps raw IDs to internal IDs used by the model. For users or items in the test set that were not seen during training, it replaces their IDs with a default value (e.g., 0). This is essential to prevent errors during prediction.
Threshold Selection: The threshold for classifying predicted scores into binary targets can significantly impact the results. You might want to experiment with different threshold values or methods (e.g., using a validation set) to find the optimal threshold for your specific data.
Evaluation: Since the test set does not include actual target values, you cannot compute evaluation metrics like accuracy or AUC directly. If you have a validation set with known target values, you can use it to tune hyperparameters and thresholds.
Model Saving and Loading: If you plan to reuse the trained model later, consider saving it using torch.save() and loading it with torch.load() when needed.
Please ensure that your actual data files are correctly loaded and that all paths and configurations match your environment. Adjust the parameters and thresholds as necessary to suit your specific dataset and requirements.