# Copyright 2022 NVIDIA Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =======
https://developer.download.nvidia.com/notebooks/dlsw-notebooks/merlin_transformers4rec_getting-started-session-based-01-etl-with-nvtabular/nvidia_logo.png

ETL with NVTabular

In this notebook we are going to generate synthetic data and then create sequential features with NVTabular. Such data will be used in the next notebook to train a session-based recommendation model.

NVTabular is a feature engineering and preprocessing library for tabular data designed to quickly and easily manipulate terabyte scale datasets used to train deep learning based recommender systems. It provides a high level abstraction to simplify code and accelerates computation on the GPU using the RAPIDS cuDF library.

Import required libraries

import os
import glob

import numpy as np
import pandas as pd

import cudf
import cupy as cp
import nvtabular as nvt
from nvtabular.ops import *
from merlin.schema.tags import Tags

Define Input/Output Path

INPUT_DATA_DIR = os.environ.get("INPUT_DATA_DIR", "/workspace/data/")

Create a Synthetic Input Data

NUM_ROWS = 10000000
long_tailed_item_distribution = np.clip(np.random.lognormal(3., 1., NUM_ROWS).astype(np.int32), 1, 50000)

# generate random item interaction features 
df = pd.DataFrame(np.random.randint(70000, 90000, NUM_ROWS), columns=['session_id'])
df['item_id'] = long_tailed_item_distribution

# generate category mapping for each item-id
df['category'] = pd.cut(df['item_id'], bins=334, labels=np.arange(1, 335)).astype(np.int32)
df['timestamp/age_days'] = np.random.uniform(0, 1, NUM_ROWS)
df['timestamp/weekday/sin']= np.random.uniform(0, 1, NUM_ROWS)

# generate day mapping for each session 
map_day = dict(zip(df.session_id.unique(), np.random.randint(1, 10, size=(df.session_id.nunique()))))
df['day'] =  df.session_id.map(map_day)
  • Visualize couple of rows of the synthetic dataset

df.head()
session_id item_id category timestamp/age_days timestamp/weekday/sin day
0 79895 72 7 0.575559 0.463627 5
1 72384 8 1 0.423588 0.439379 9
2 80895 26 3 0.257796 0.793980 9
3 70485 17 2 0.354155 0.121522 2
4 87857 142 12 0.930029 0.894743 8

Feature Engineering with NVTabular

Deep Learning models require dense input features. Categorical features are sparse, and need to be represented by dense embeddings in the model. To allow for that, categorical features need first to be encoded as contiguous integers (0, ..., |C|), where |C| is the feature cardinality (number of unique values), so that their embeddings can be efficiently stored in embedding layers. We will use NVTabular to preprocess the categorical features, so that all categorical columns are encoded as contiguous integers. Note that in the Categorify op we set start_index=1, the reason for that we want the encoded null values to start from 1 instead of 0 because we reserve 0 for padding the sequence features.

Here our goal is to create sequential features. In this cell, we are creating temporal features and grouping them together at the session level, sorting the interactions by time. Note that we also trim each feature sequence in a session to a certain length. Here, we use the NVTabular library so that we can easily preprocess and create features on GPU with a few lines.

# Categorify categorical features
categ_feats = ['session_id', 'item_id', 'category'] >> nvt.ops.Categorify(start_index=1)

# Define Groupby Workflow
groupby_feats = categ_feats + ['day', 'timestamp/age_days', 'timestamp/weekday/sin']

# Groups interaction features by session and sorted by timestamp
groupby_features = groupby_feats >> nvt.ops.Groupby(
    groupby_cols=["session_id"], 
    aggs={
        "item_id": ["list", "count"],
        "category": ["list"],     
        "day": ["first"],
        "timestamp/age_days": ["list"],
        'timestamp/weekday/sin': ["list"],
        },
    name_sep="-")

# Select and truncate the sequential features
sequence_features_truncated = (groupby_features['category-list']) >> nvt.ops.ListSlice(0,20) >> nvt.ops.Rename(postfix = '_trim')

sequence_features_truncated_item = (
    groupby_features['item_id-list']
    >> nvt.ops.ListSlice(0,20) 
    >> nvt.ops.Rename(postfix = '_trim')
    >> TagAsItemID()
)  
sequence_features_truncated_cont = (
    groupby_features['timestamp/age_days-list', 'timestamp/weekday/sin-list'] 
    >> nvt.ops.ListSlice(0,20) 
    >> nvt.ops.Rename(postfix = '_trim')
    >> nvt.ops.AddMetadata(tags=[Tags.CONTINUOUS])
)

# Filter out sessions with length 1 (not valid for next-item prediction training and evaluation)
MINIMUM_SESSION_LENGTH = 2
selected_features = (
    groupby_features['item_id-count', 'day-first', 'session_id'] + 
    sequence_features_truncated_item +
    sequence_features_truncated + 
    sequence_features_truncated_cont
)
    
filtered_sessions = selected_features >> nvt.ops.Filter(f=lambda df: df["item_id-count"] >= MINIMUM_SESSION_LENGTH)


workflow = nvt.Workflow(filtered_sessions)
dataset = nvt.Dataset(df, cpu=False)
# Generating statistics for the features
workflow.fit(dataset)
# Applying the preprocessing and returning an NVTabular dataset
sessions_ds = workflow.transform(dataset)
# Converting the NVTabular dataset to a Dask cuDF dataframe (`to_ddf()`) and then to cuDF dataframe (`.compute()`)
sessions_gdf = sessions_ds.to_ddf().compute()
/usr/local/lib/python3.8/dist-packages/cudf/core/frame.py:384: UserWarning: The deep parameter is ignored and is only included for pandas compatibility.
  warnings.warn(
sessions_gdf.head(3)
item_id-count day-first session_id item_id-list_trim category-list_trim timestamp/age_days-list_trim timestamp/weekday/sin-list_trim
0 591 2 2 [36, 64, 32, 46, 2, 52, 8, 39, 11, 34, 86, 9, ... [4, 7, 4, 5, 2, 6, 2, 5, 3, 4, 9, 2, 3, 2, 3, ... [0.21271311423191075, 0.47673105314236597, 0.6... [0.053377759448017814, 0.13143816418738208, 0....
1 591 3 3 [9, 29, 15, 2, 3, 32, 18, 57, 29, 17, 38, 20, ... [2, 4, 3, 2, 2, 4, 3, 6, 4, 3, 5, 3, 5, 5, 2, ... [0.5194944043984934, 0.7865161467150079, 0.516... [0.2768566421516725, 0.8165712246233945, 0.052...
2 590 1 4 [16, 2, 3, 93, 36, 19, 25, 115, 3, 9, 49, 4, 2... [3, 2, 2, 9, 4, 3, 4, 11, 2, 2, 5, 2, 4, 6, 4,... [0.22325654804391093, 0.4402565281570716, 0.38... [0.15944257060229772, 0.013476143111235905, 0....

It is possible to save the preprocessing workflow. That is useful to apply the same preprocessing to other data (with the same schema) and also to deploy the session-based recommendation pipeline to Triton Inference Server.

workflow.save('workflow_etl')

The following will generate schema.pbtxt file in the provided folder.

workflow.fit_transform(dataset).to_parquet(os.path.join(INPUT_DATA_DIR, "processed_nvt"))
/usr/local/lib/python3.8/dist-packages/cudf/core/frame.py:384: UserWarning: The deep parameter is ignored and is only included for pandas compatibility.
  warnings.warn(

Export pre-processed data by day

In this example we are going to split the preprocessed parquet files by days, to allow for temporal training and evaluation. There will be a folder for each day and three parquet files within each day folder: train.parquet, validation.parquet and test.parquet

OUTPUT_DIR = os.environ.get("OUTPUT_DIR",os.path.join(INPUT_DATA_DIR, "sessions_by_day"))
!mkdir -p $OUTPUT_DIR
from transformers4rec.data.preprocessing import save_time_based_splits
save_time_based_splits(data=nvt.Dataset(sessions_gdf),
                       output_dir= OUTPUT_DIR,
                       partition_col='day-first',
                       timestamp_col='session_id', 
                      )
Creating time-based splits: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:02<00:00,  4.22it/s]

Checking the preprocessed outputs

TRAIN_PATHS = sorted(glob.glob(os.path.join(OUTPUT_DIR, "1", "train.parquet")))
gdf = cudf.read_parquet(TRAIN_PATHS[0])
gdf
item_id-count session_id item_id-list_trim category-list_trim timestamp/age_days-list_trim timestamp/weekday/sin-list_trim
0 590 4 [16, 2, 3, 93, 36, 19, 25, 115, 3, 9, 49, 4, 2... [3, 2, 2, 9, 4, 3, 4, 11, 2, 2, 5, 2, 4, 6, 4,... [0.22325654804391093, 0.4402565281570716, 0.38... [0.15944257060229772, 0.013476143111235905, 0....
1 582 8 [3, 34, 81, 12, 19, 48, 10, 15, 18, 19, 61, 33... [2, 4, 8, 3, 3, 5, 2, 3, 3, 3, 7, 2, 4, 2, 5, ... [0.01301034794234468, 0.8975850168095207, 0.11... [0.37244707643279873, 0.6430649865767125, 0.84...
2 579 10 [7, 5, 96, 36, 12, 10, 81, 54, 36, 120, 3, 69,... [2, 2, 9, 4, 3, 2, 8, 6, 4, 12, 2, 7, 4, 6, 3,... [0.2608925140795695, 0.7891122184433232, 0.302... [0.8785835481938361, 0.7364014617152856, 0.896...
4 569 30 [20, 56, 38, 14, 24, 34, 9, 26, 28, 14, 32, 9,... [3, 6, 5, 2, 3, 4, 2, 4, 4, 2, 4, 2, 3, 4, 3, ... [0.15751497487991506, 0.016492940806796086, 0.... [0.15627788549590182, 0.9837698990155679, 0.11...
5 568 33 [31, 50, 36, 86, 4, 28, 35, 7, 133, 10, 36, 2,... [4, 6, 4, 9, 2, 4, 4, 2, 13, 2, 4, 2, 2, 4, 3,... [0.6335526717564155, 0.7895328077124247, 0.803... [0.18652468074823958, 0.8376901269790153, 0.59...
... ... ... ... ... ... ...
2226 441 19927 [134, 94, 11, 47, 92, 277, 3, 6, 34, 4, 212, 1... [13, 9, 3, 5, 9, 25, 2, 2, 4, 2, 19, 12, 3, 3,... [0.07049606626554561, 0.6801535673513188, 0.25... [0.15023170301789446, 0.6831186301779653, 0.80...
2227 441 19928 [6, 17, 9, 31, 42, 34, 21, 16, 39, 16, 42, 26,... [2, 3, 2, 4, 5, 4, 2, 3, 5, 3, 5, 4, 2, 3, 3, ... [0.943628011644158, 0.35946685478883145, 0.881... [0.3740112539329261, 0.6214578812223325, 0.379...
2228 441 19929 [19, 14, 19, 98, 17, 5, 13, 26, 18, 2, 35, 3, ... [3, 2, 3, 10, 3, 2, 3, 4, 3, 2, 4, 2, 2, 2, 6,... [0.11114081502978823, 0.8287223990056634, 0.04... [0.22701859646654832, 0.46340023643004713, 0.8...
2229 439 19942 [101, 14, 8, 30, 36, 41, 13, 9, 10, 82, 6, 195... [10, 2, 2, 4, 4, 5, 3, 2, 2, 8, 2, 18, 3, 2, 4... [0.9677378334614682, 0.005930902643004221, 0.0... [0.29683409646692904, 0.3718404566751601, 0.03...
2230 438 19954 [164, 120, 34, 16, 7, 20, 49, 13, 74, 4, 33, 1... [15, 12, 4, 3, 2, 3, 5, 3, 8, 2, 2, 3, 5, 3, 1... [0.7573636520838789, 0.8658570560696931, 0.758... [0.1346140801544553, 0.3068511774606606, 0.674...

1786 rows × 6 columns

You have just created session-level features to train a session-based recommendation model using NVTabular. Now you can move to the the next notebook,02-session-based-XLNet-with-PyT.ipynb to train a session-based recommendation model using XLNet, one of the state-of-the-art NLP model.