# Copyright 2021 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.
# =======

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

Define Input/Output Path

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

Create a Synthetic Input Data

NUM_ROWS = 100000
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, 80000, 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 72794 25 8 0.425057 0.796974 9
1 72989 57 18 0.729572 0.924252 7
2 78236 2 1 0.922154 0.532076 4
3 72766 9 3 0.956614 0.567720 3
4 76730 9 3 0.361798 0.611959 4

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', 'item_id-list', 'timestamp/age_days-list', 'timestamp/weekday/sin-list']) >>nvt.ops.ListSlice(0,20) >> nvt.ops.Rename(postfix = '_trim')

# 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
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()
sessions_gdf.head(3)
item_id-count day-first session_id category-list_trim item_id-list_trim timestamp/age_days-list_trim timestamp/weekday/sin-list_trim
0 25 3 2 [24, 12, 6, 3, 3, 6, 9, 2, 8, 15, 9, 5, 6, 8, ... [79, 36, 13, 5, 8, 12, 27, 4, 21, 42, 28, 10, ... [0.4751982727759114, 0.055393015414691105, 0.2... [0.8122129009074556, 0.5284590396837701, 0.041...
1 24 6 3 [3, 12, 16, 14, 13, 10, 13, 9, 24, 19, 32, 68,... [2, 33, 55, 40, 39, 23, 38, 27, 78, 57, 109, 1... [0.5303167840438227, 0.800766191594587, 0.3993... [0.0484016923364502, 0.9895741720728333, 0.020...
2 23 7 4 [2, 11, 3, 11, 6, 9, 2, 29, 21, 3, 5, 3, 5, 12... [4, 32, 5, 30, 13, 26, 3, 87, 62, 2, 22, 5, 14... [0.40259610248511546, 0.7994956663950287, 0.11... [0.13638022767099878, 0.5088356162643055, 0.06...

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')

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

Checking the preprocessed outputs

TRAIN_PATHS = sorted(glob.glob(os.path.join(OUTPUT_FOLDER, "1", "train.parquet")))
gdf = cudf.read_parquet(TRAIN_PATHS[0])
gdf.head()
item_id-count session_id category-list_trim item_id-list_trim timestamp/age_days-list_trim timestamp/weekday/sin-list_trim
0 22 7 [6, 9, 5, 2, 7, 8, 5, 2, 6, 16, 2, 10, 35, 5, ... [15, 27, 10, 3, 17, 19, 10, 3, 13, 53, 3, 25, ... [0.05018395805258469, 0.3675245026471312, 0.45... [0.4569657788661693, 0.3016987134228405, 0.444...
1 20 17 [3, 3, 3, 2, 29, 3, 4, 3, 17, 2, 21, 16, 8, 4,... [5, 8, 8, 4, 92, 5, 7, 5, 47, 3, 62, 52, 20, 1... [0.6514417831915809, 0.4076816703281344, 0.632... [0.14429839204039463, 0.9164664830523597, 0.28...
2 19 45 [4, 34, 9, 3, 4, 11, 3, 7, 7, 6, 3, 5, 20, 8, ... [7, 95, 26, 2, 7, 32, 5, 17, 17, 15, 5, 10, 59... [0.8375365213796201, 0.5405179079133022, 0.779... [0.7202554739875682, 0.22750431643945657, 0.22...
4 19 62 [10, 7, 8, 4, 26, 27, 5, 13, 6, 2, 9, 8, 3, 11... [25, 17, 19, 7, 75, 81, 10, 37, 12, 3, 29, 19,... [0.4649937741449487, 0.5034045853366875, 0.566... [0.05637671244260656, 0.26188954412734744, 0.1...
5 19 63 [30, 14, 6, 3, 5, 6, 5, 2, 11, 9, 9, 45, 5, 9,... [96, 43, 12, 5, 22, 13, 22, 3, 31, 29, 26, 134... [0.17334992894139045, 0.883403092448823, 0.933... [0.2423479210589905, 0.7296242799474274, 0.335...

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.