To solve this machine learning problem, we'll develop a comprehensive pipeline that includes data preprocessing, feature engineering, model training, and prediction generation. Below is a step-by-step guide, complete with Python code snippets using popular libraries like Pandas, Scikit-learn, and LightGBM. This approach is optimized for handling large datasets efficiently.
Overview of the Solution
- Data Loading and Exploration
- Target Variable Construction
- Data Preprocessing
- Feature Engineering
- Handling Large Datasets
- Model Training
- Evaluation
- Prediction and Submission
Let's go through each step in detail.
1. Data Loading and Exploration
First, we'll load the necessary libraries and data. Since the datasets are in Parquet format and potentially large, we'll use efficient data processing libraries like Pandas and optimize memory usage where possible.
import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.metrics import f1_score
from sklearn.preprocessing import LabelEncoder
import gc
# Load datasets
train = pd.read_parquet('train.parquet')
test = pd.read_parquet('test.parquet')
video_stats = pd.read_parquet('video_stat.parquet')
# Sample submission
sample_submission = pd.read_csv('sample_submission.csv')
Exploratory Data Analysis (EDA):
Before proceeding, it's essential to understand the data distribution, null values, and basic statistics.
print(train.head())
print(train.info())
print(video_stats.head())
print(video_stats.info())
2. Target Variable Construction
We need to create the target variable long_view based on the provided criteria:
- For videos longer than 5 minutes (300 seconds):
long_view = 1 if watchtime > 0.25 * v_duration
- For videos ≤ 5 minutes:
long_view = 1 if watchtime > 30
- Else:
long_view = 0
We'll merge the train and video_stats datasets to access v_duration.
# Merge train with video_stats to get v_duration
train = train.merge(video_stats[['video_id', 'v_duration']], on='video_id', how='left')
# Define target variable
def get_long_view(row):
if row['v_duration'] > 300:
return 1 if row['watchtime'] > 0.25 * row['v_duration'] else 0
else:
return 1 if row['watchtime'] > 30 else 0
train['long_view'] = train.apply(get_long_view, axis=1)
# Drop unnecessary columns
train.drop(['watchtime'], axis=1, inplace=True)
3. Data Preprocessing
Handling Missing Values
Check for missing values and decide on appropriate strategies (e.g., imputation or removal).
# Check missing values
print(train.isnull().sum())
print(test.isnull().sum())
print(video_stats.isnull().sum())
# Example: Fill missing numerical values with median
numerical_cols = ['v_total_comments', 'v_year_views', 'v_month_views',
'v_week_views', 'v_day_views', 'v_likes', 'v_dislikes',
'v_duration', 'v_avg_watchtime_1_day', 'v_avg_watchtime_7_day',
'v_avg_watchtime_30_day']
for col in numerical_cols:
train[col].fillna(train[col].median(), inplace=True)
test[col].fillna(test[col].median(), inplace=True)
video_stats[col].fillna(video_stats[col].median(), inplace=True)
# Handle categorical variables if any (e.g., 'region', 'city')
categorical_cols = ['region', 'city', 'author_id', 'category_id']
for col in categorical_cols:
train[col].fillna('unknown', inplace=True)
test[col].fillna('unknown', inplace=True)
video_stats[col].fillna('unknown', inplace=True)
Encoding Categorical Variables
We'll use LabelEncoder for simplicity. For higher cardinality features, consider more sophisticated encoding techniques or feature hashing.
for col in categorical_cols:
le = LabelEncoder()
combined = pd.concat([train[col], test[col], video_stats[col]], axis=0).astype(str)
le.fit(combined)
train[col] = le.transform(train[col].astype(str))
test[col] = le.transform(test[col].astype(str))
video_stats[col] = le.transform(video_stats[col].astype(str))
4. Feature Engineering
Merging Datasets
Merge train and test with video_stats to include video metadata.
# Merge train and test with video_stats
train = train.merge(video_stats, on='video_id', how='left')
test = test.merge(video_stats, on='video_id', how='left')
Creating Interaction Features
Interaction between user and video can be crucial.
# Example: Number of times user has interacted with video
user_video_interaction = train.groupby(['user_id', 'video_id']).size().reset_index(name='user_video_interaction')
train = train.merge(user_video_interaction, on=['user_id', 'video_id'], how='left')
test = test.merge(user_video_interaction, on=['user_id', 'video_id'], how='left')
test['user_video_interaction'].fillna(0, inplace=True)
Time-Based Features
Extract features like the day of the week, hour, etc., from event_timestamp.
# Convert event_timestamp to datetime
train['event_datetime'] = pd.to_datetime(train['event_timestamp'])
test['event_datetime'] = pd.to_datetime(test['event_timestamp'])
# Extract features
for df in [train, test]:
df['event_hour'] = df['event_datetime'].dt.hour
df['event_dayofweek'] = df['event_datetime'].dt.dayofweek
df['event_month'] = df['event_datetime'].dt.month
# Drop original timestamp
train.drop(['event_timestamp', 'event_datetime'], axis=1, inplace=True)
test.drop(['event_timestamp', 'event_datetime'], axis=1, inplace=True)
Feature Selection
Select relevant features for the model. Avoid using identifiers like user_id and video_id directly unless they're encoded meaningfully.
# List of feature columns
feature_cols = [
'region', 'city', 'user_id', 'video_id', 'author_id', 'category_id',
'v_total_comments', 'v_year_views', 'v_month_views', 'v_week_views',
'v_day_views', 'v_likes', 'v_dislikes', 'v_duration',
'v_cr_click_like_7_days', 'v_cr_click_dislike_7_days',
'v_cr_click_vtop_7_days', 'v_cr_click_long_view_7_days',
'v_cr_click_comment_7_days', 'v_cr_click_like_30_days',
'v_cr_click_dislike_30_days', 'v_cr_click_vtop_30_days',
'v_cr_click_long_view_30_days', 'v_cr_click_comment_30_days',
'v_cr_click_like_1_days', 'v_cr_click_dislike_1_days',
'v_cr_click_vtop_1_days', 'v_cr_click_long_view_1_days',
'v_cr_click_comment_1_days', 'v_avg_watchtime_1_day',
'v_avg_watchtime_7_day', 'v_avg_watchtime_30_day',
'v_frac_avg_watchtime_1_day_duration',
'v_frac_avg_watchtime_7_day_duration',
'v_frac_avg_watchtime_30_day_duration',
'v_category_popularity_percent_7_days',
'v_category_popularity_percent_30_days',
'v_long_views_1_days', 'v_long_views_7_days',
'V_long_views_30_days', 'event_hour', 'event_dayofweek', 'event_month',
'user_video_interaction'
]
# Ensure all feature columns are present
train_features = train[feature_cols]
train_target = train['long_view']
test_features = test[feature_cols]
5. Handling Large Datasets
For large datasets, it's crucial to optimize memory usage and possibly use out-of-core learning techniques. Here are some strategies:
Convert data types to more memory-efficient types.
def optimize_memory(df):
for col in df.columns:
col_type = df[col].dtype
if col_type == 'int64':
df[col] = pd.to_numeric(df[col], downcast='integer')
elif col_type == 'float64':
df[col] = pd.to_numeric(df[col], downcast='float')
return df
train_features = optimize_memory(train_features)
test_features = optimize_memory(test_features)
- Using LightGBM with Efficient Parameters:
LightGBM is optimized for speed and memory usage.
6. Model Training
We'll use LightGBM, which is efficient for large datasets and provides excellent performance for classification tasks.
# Define parameters for LightGBM
params = {
'objective': 'binary',
'metric': 'binary_logloss',
'boosting_type': 'gbdt',
'learning_rate': 0.05,
'num_leaves': 31,
'max_depth': -1,
'min_data_in_leaf': 20,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': -1,
'random_state': 42
}
# Initialize cross-validation
kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
f1_scores = []
models = []
for train_index, val_index in kf.split(train_features, train_target):
X_train, X_val = train_features.iloc[train_index], train_features.iloc[val_index]
y_train, y_val = train_target.iloc[train_index], train_target.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
lgb_val = lgb.Dataset(X_val, y_val, reference=lgb_train)
# Train the model
model = lgb.train(
params,
lgb_train,
num_boost_round=10000,
valid_sets=[lgb_train, lgb_val],
early_stopping_rounds=100,
verbose_eval=100
)
# Predict on validation set
y_pred = model.predict(X_val, num_iteration=model.best_iteration)
y_pred_binary = (y_pred > 0.5).astype(int)
# Calculate F1 score
f1 = f1_score(y_val, y_pred_binary)
print(f'Fold F1 Score: {f1}')
f1_scores.append(f1)
# Save the model
models.append(model)
# Free memory
del X_train, X_val, y_train, y_val, lgb_train, lgb_val, y_pred, y_pred_binary
gc.collect()
print(f'Average F1 Score: {np.mean(f1_scores)}')
Notes:
- Early Stopping: Prevents overfitting by stopping training when the validation score doesn't improve.
- Cross-Validation: Ensures the model's performance is consistent across different subsets of data.
7. Evaluation
Since the metric is F1-Score, we've already calculated it during cross-validation. Ensure that the average F1-Score is satisfactory. If not, consider:
- Hyperparameter Tuning: Use techniques like Grid Search or Bayesian Optimization.
- Feature Selection: Remove less important features.
- Handling Class Imbalance: If the classes are imbalanced, consider techniques like SMOTE or adjusting class weights.
8. Prediction and Submission
After training, use all available training data to train the final model and generate predictions on the test set.
# Train final model on full training data
final_model = lgb.train(
params,
lgb.Dataset(train_features, train_target),
num_boost_round= models[0].best_iteration # Use the best iteration from CV
)
# Predict on test data
test_pred = final_model.predict(test_features, num_iteration=final_model.best_iteration)
test_pred_binary = (test_pred > 0.5).astype(int)
# Prepare submission
submission = pd.DataFrame({
'object_id': test['object_id'], # Assuming 'object_id' is the identifier
'long_view': test_pred_binary
})
# If 'object_id' is not present, use the index
if 'object_id' not in test.columns:
submission = pd.DataFrame({
'object_id': test.index,
'long_view': test_pred_binary
})
# Save to CSV
submission.to_csv('submission.csv', index=False)
Note: Ensure that 'object_id' is the correct identifier as per sample_submission.csv. Adjust accordingly.
Additional Optimization Tips
- Memory Management: Release memory after processing large DataFrames using
del and gc.collect().
- Batch Processing: If the dataset is too large to fit into memory, consider processing it in chunks using libraries like Dask or PySpark.
- Feature Importance: Analyze feature importance from the LightGBM model to understand which features contribute most to the prediction.
import matplotlib.pyplot as plt
# Plot feature importance
lgb.plot_importance(final_model, max_num_features=20)
plt.show()
Conclusion
This pipeline provides a robust framework for predicting long video views on a large-scale platform. By following these steps, you can efficiently preprocess data, engineer meaningful features, train a high-performing model, and generate accurate predictions for submission. Remember to iterate on feature engineering and model tuning to achieve the best possible F1-Score.
If you encounter specific challenges or require further optimization tailored to your dataset's nuances, feel free to ask!