Multimodal Data Tables: Combining BERT/Transformers and Classical Tabular Models

Here we introduce how to use AutoGluon Tabular to deal with multimodal tabular data that contains text, numeric, and categorical columns. In AutoGluon, raw text data is considered as a first-class citizen of data tables. AutoGluon Tabular can help you train and combine a diverse set of models including classical tabular models like LightGBM/RF/CatBoost as well as our pretrained NLP model based multimodal network that is introduced in Section “What’s happening inside?” of Text Prediction - Multimodal Table with Text (used by AutoGluon’s TextPredictor).

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pprint
import random
from autogluon.tabular import TabularPredictor
import mxnet as mx

np.random.seed(123)
random.seed(123)
mx.random.seed(123)

Product Sentiment Analysis Dataset

We consider the product sentiment analysis dataset from a MachineHack hackathon. The goal is to predict a user’s sentiment towards a product given their review (raw text) and a categorical feature indicating the product’s type (e.g., Tablet, Mobile, etc.). We have already split the original dataset to be 90% for training and 10% for development/testing (if submitting your models to the hackathon, we recommend training them on 100% of the dataset).

!mkdir -p product_sentiment_machine_hack
!wget https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/train.csv -O product_sentiment_machine_hack/train.csv
!wget https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/dev.csv -O product_sentiment_machine_hack/dev.csv
!wget https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/test.csv -O product_sentiment_machine_hack/test.csv
--2021-03-01 07:38:20--  https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/train.csv
Resolving autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)... 52.216.105.235
Connecting to autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)|52.216.105.235|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 689486 (673K) [text/csv]
Saving to: ‘product_sentiment_machine_hack/train.csv’

product_sentiment_m 100%[===================>] 673.33K  2.02MB/s    in 0.3s

2021-03-01 07:38:21 (2.02 MB/s) - ‘product_sentiment_machine_hack/train.csv’ saved [689486/689486]

--2021-03-01 07:38:22--  https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/dev.csv
Resolving autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)... 52.216.105.235
Connecting to autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)|52.216.105.235|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75517 (74K) [text/csv]
Saving to: ‘product_sentiment_machine_hack/dev.csv’

product_sentiment_m 100%[===================>]  73.75K  --.-KB/s    in 0.1s

2021-03-01 07:38:22 (584 KB/s) - ‘product_sentiment_machine_hack/dev.csv’ saved [75517/75517]

--2021-03-01 07:38:23--  https://autogluon-text-data.s3.amazonaws.com/multimodal_text/machine_hack_product_sentiment/test.csv
Resolving autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)... 52.216.205.107
Connecting to autogluon-text-data.s3.amazonaws.com (autogluon-text-data.s3.amazonaws.com)|52.216.205.107|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 312194 (305K) [text/csv]
Saving to: ‘product_sentiment_machine_hack/test.csv’

product_sentiment_m 100%[===================>] 304.88K  1.16MB/s    in 0.3s

2021-03-01 07:38:23 (1.16 MB/s) - ‘product_sentiment_machine_hack/test.csv’ saved [312194/312194]
subsample_size = 2000  # for quick demo, try setting to larger values
feature_columns = ['Product_Description', 'Product_Type']
label = 'Sentiment'

train_df = pd.read_csv('product_sentiment_machine_hack/train.csv', index_col=0).sample(2000, random_state=123)
dev_df = pd.read_csv('product_sentiment_machine_hack/dev.csv', index_col=0)
test_df = pd.read_csv('product_sentiment_machine_hack/test.csv', index_col=0)

train_df = train_df[feature_columns + [label]]
dev_df = dev_df[feature_columns + [label]]
test_df = test_df[feature_columns]
print('Number of training samples:', len(train_df))
print('Number of dev samples:', len(dev_df))
print('Number of test samples:', len(test_df))
Number of training samples: 2000
Number of dev samples: 637
Number of test samples: 2728

There are two features in the dataset: the users’ review of the product and the product’s type, and four possible classes to predict.

train_df.head()
Product_Description Product_Type Sentiment
4532 they took away the lego pit but replaced it wi... 0 1
1831 #Apple to Open Pop-Up Shop at #SXSW [REPORT]: ... 9 2
3536 RT @mention False Alarm: Google Circles Not Co... 5 1
5157 Will Google reveal a new social network called... 9 2
4643 Niceness RT @mention Less than 2 hours until w... 6 3
dev_df.head()
Product_Description Product_Type Sentiment
3170 Do it. RT @mention Come party w/ Google tonigh... 3 3
6301 Line for iPads at #SXSW. Doesn't look too bad!... 6 3
5643 First up: iPad Design Headaches (2 Tablets, Ca... 6 2
1953 #SXSW: Mint Talks Mobile App Development Chall... 9 2
2658 ‰ÛÏ@mention Apple store downtown Austin open t... 9 2
test_df.head()
Product_Description Product_Type
Text_ID
5786 RT @mention Going to #SXSW? The new iPhone gui... 7
5363 RT @mention 95% of iPhone and Droid apps have ... 9
6716 RT @mention Thank you to @mention for letting ... 9
4339 #Thanks @mention we're lovin' the @mention app... 7
66 At #sxsw? @mention / @mention wanna buy you a ... 9

AutoGluon Tabular with Multimodal Support

To utilize the TextPredictor model inside of TabularPredictor, we must specify the hyperparameters = 'multimodal' in AutoGluon Tabular. Internally, this will train multiple tabular models as well as the TextPredictor model, and then combine them via either a weighted ensemble or stack ensemble, as explained in AutoGluon Tabular Paper. If you do not specify hyperparameters = 'multimodal', then AutoGluon Tabular will simply featurize text fields using N-grams and train only tabular models (which may work better if your text is mostly uncommon strings/vocabulary).

from autogluon.tabular import TabularPredictor
predictor = TabularPredictor(label='Sentiment', path='ag_tabular_product_sentiment_multimodal')
predictor.fit(train_df, hyperparameters='multimodal')
Beginning AutoGluon training ...
AutoGluon will save models to "ag_tabular_product_sentiment_multimodal/"
AutoGluon Version:  0.1.0b20210301
Train Data Rows:    2000
Train Data Columns: 2
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == int, but few unique label-values observed).
    4 unique label values:  [1, 2, 3, 0]
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type argument in fit() (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
NumExpr defaulting to 8 threads.
Train Data Class Count: 4
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    21929.38 MB
    Train Data (Original)  Memory Usage: 0.34 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting IdentityFeatureGenerator...
                    Fitting RenameFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
            Fitting TextSpecialFeatureGenerator...
                    Fitting BinnedFeatureGenerator...
                    Fitting DropDuplicatesFeatureGenerator...
            Fitting TextNgramFeatureGenerator...
                    Fitting CountVectorizer for text features: ['Product_Description']
                    CountVectorizer fit with vocabulary size = 230
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])          : 1 | ['Product_Type']
            ('object', ['text']) : 1 | ['Product_Description']
    Types of features in processed data (raw dtype, special dtypes):
            ('int', [])                         :   1 | ['Product_Type']
            ('int', ['binned', 'text_special']) :  38 | ['Product_Description.char_count', 'Product_Description.word_count', 'Product_Description.capital_ratio', 'Product_Description.lower_ratio', 'Product_Description.digit_ratio', ...]
            ('int', ['text_ngram'])             : 231 | ['__nlp__.about', '__nlp__.all', '__nlp__.amp', '__nlp__.an', '__nlp__.an ipad', ...]
            ('object', ['text'])                :   1 | ['Product_Description_raw_text']
    0.8s = Fit runtime
    2 features in original data used to generate 271 features in processed data.
    Train Data (Processed) Memory Usage: 0.9 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.83s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric argument of fit()
Automatically generating train/validation split with holdout_frac=0.2, Train Rows: 1600, Val Rows: 400
Fitting model: NeuralNetMXNet ...
    0.8825   = Validation accuracy score
    1.67s    = Training runtime
    0.03s    = Validation runtime
Fitting model: LightGBM ...
    0.8875   = Validation accuracy score
    0.69s    = Training runtime
    0.01s    = Validation runtime
Fitting model: LightGBMXT ...
    0.8625   = Validation accuracy score
    0.65s    = Training runtime
    0.01s    = Validation runtime
Fitting model: CatBoost ...
    0.8825   = Validation accuracy score
    0.62s    = Training runtime
    0.01s    = Validation runtime
Fitting model: XGBoost ...
    0.8925   = Validation accuracy score
    1.26s    = Training runtime
    0.01s    = Validation runtime
Fitting model: LightGBMLarge ...
    0.885    = Validation accuracy score
    2.05s    = Training runtime
    0.01s    = Validation runtime
Fitting model: TextNeuralNetwork ...
All Logs will be saved to /var/lib/jenkins/workspace/workspace/autogluon-tutorial-tabular-v3/docs/_build/eval/tutorials/tabular_prediction/ag_tabular_product_sentiment_multimodal/models/TextNeuralNetwork/task0/training.log
[Iter 3/130, Epoch 0] valid accuracy=6.8500e-01, log_loss=8.0902e-01, accuracy=6.8500e-01, time spent=1.187s, total time spent=0.11min. Find new best=True, Find new top-3=True
[Iter 6/130, Epoch 0] valid accuracy=8.8250e-01, log_loss=5.4640e-01, accuracy=8.8250e-01, time spent=1.173s, total time spent=0.21min. Find new best=True, Find new top-3=True
[Iter 9/130, Epoch 0] valid accuracy=8.8250e-01, log_loss=4.4830e-01, accuracy=8.8250e-01, time spent=1.198s, total time spent=0.31min. Find new best=True, Find new top-3=True
[Iter 12/130, Epoch 0] valid accuracy=8.8500e-01, log_loss=4.5225e-01, accuracy=8.8500e-01, time spent=1.206s, total time spent=0.45min. Find new best=True, Find new top-3=True
[Iter 15/130, Epoch 1] valid accuracy=8.8250e-01, log_loss=4.4176e-01, accuracy=8.8250e-01, time spent=1.193s, total time spent=0.54min. Find new best=False, Find new top-3=True
[Iter 18/130, Epoch 1] valid accuracy=8.9000e-01, log_loss=4.2254e-01, accuracy=8.9000e-01, time spent=1.202s, total time spent=0.65min. Find new best=True, Find new top-3=True
[Iter 21/130, Epoch 1] valid accuracy=7.9250e-01, log_loss=5.3988e-01, accuracy=7.9250e-01, time spent=1.221s, total time spent=0.73min. Find new best=False, Find new top-3=False
[Iter 24/130, Epoch 1] valid accuracy=8.8500e-01, log_loss=4.8991e-01, accuracy=8.8500e-01, time spent=1.214s, total time spent=0.82min. Find new best=False, Find new top-3=True
[Iter 27/130, Epoch 2] valid accuracy=8.9000e-01, log_loss=4.1033e-01, accuracy=8.9000e-01, time spent=1.206s, total time spent=0.93min. Find new best=True, Find new top-3=True
[Iter 30/130, Epoch 2] valid accuracy=8.5000e-01, log_loss=4.6091e-01, accuracy=8.5000e-01, time spent=1.224s, total time spent=1.01min. Find new best=False, Find new top-3=False
[Iter 33/130, Epoch 2] valid accuracy=8.9000e-01, log_loss=4.0818e-01, accuracy=8.9000e-01, time spent=1.224s, total time spent=1.12min. Find new best=True, Find new top-3=True
[Iter 36/130, Epoch 2] valid accuracy=8.9250e-01, log_loss=3.7211e-01, accuracy=8.9250e-01, time spent=1.229s, total time spent=1.23min. Find new best=True, Find new top-3=True
[Iter 39/130, Epoch 2] valid accuracy=9.0500e-01, log_loss=3.7962e-01, accuracy=9.0500e-01, time spent=1.225s, total time spent=1.34min. Find new best=True, Find new top-3=True
[Iter 42/130, Epoch 3] valid accuracy=8.9500e-01, log_loss=3.6979e-01, accuracy=8.9500e-01, time spent=1.240s, total time spent=1.44min. Find new best=False, Find new top-3=True
[Iter 45/130, Epoch 3] valid accuracy=9.0250e-01, log_loss=4.4334e-01, accuracy=9.0250e-01, time spent=1.240s, total time spent=1.54min. Find new best=False, Find new top-3=True
[Iter 48/130, Epoch 3] valid accuracy=8.9250e-01, log_loss=3.7222e-01, accuracy=8.9250e-01, time spent=1.256s, total time spent=1.62min. Find new best=False, Find new top-3=False
[Iter 51/130, Epoch 3] valid accuracy=9.0750e-01, log_loss=3.6317e-01, accuracy=9.0750e-01, time spent=1.247s, total time spent=1.73min. Find new best=True, Find new top-3=True
[Iter 54/130, Epoch 4] valid accuracy=9.0500e-01, log_loss=4.1408e-01, accuracy=9.0500e-01, time spent=1.270s, total time spent=1.82min. Find new best=False, Find new top-3=True
[Iter 57/130, Epoch 4] valid accuracy=9.0250e-01, log_loss=3.6191e-01, accuracy=9.0250e-01, time spent=1.265s, total time spent=1.90min. Find new best=False, Find new top-3=False
[Iter 60/130, Epoch 4] valid accuracy=9.0750e-01, log_loss=3.6103e-01, accuracy=9.0750e-01, time spent=1.259s, total time spent=2.02min. Find new best=True, Find new top-3=True
[Iter 63/130, Epoch 4] valid accuracy=9.1000e-01, log_loss=4.1278e-01, accuracy=9.1000e-01, time spent=1.279s, total time spent=2.13min. Find new best=True, Find new top-3=True
[Iter 66/130, Epoch 5] valid accuracy=8.9000e-01, log_loss=3.7437e-01, accuracy=8.9000e-01, time spent=1.284s, total time spent=2.22min. Find new best=False, Find new top-3=False
[Iter 69/130, Epoch 5] valid accuracy=8.9250e-01, log_loss=3.7972e-01, accuracy=8.9250e-01, time spent=1.283s, total time spent=2.30min. Find new best=False, Find new top-3=False
[Iter 72/130, Epoch 5] valid accuracy=9.0750e-01, log_loss=3.9485e-01, accuracy=9.0750e-01, time spent=1.289s, total time spent=2.40min. Find new best=False, Find new top-3=True
[Iter 75/130, Epoch 5] valid accuracy=9.0750e-01, log_loss=3.9445e-01, accuracy=9.0750e-01, time spent=1.295s, total time spent=2.49min. Find new best=False, Find new top-3=True
[Iter 78/130, Epoch 5] valid accuracy=9.0500e-01, log_loss=3.8109e-01, accuracy=9.0500e-01, time spent=1.297s, total time spent=2.58min. Find new best=False, Find new top-3=False
[Iter 81/130, Epoch 6] valid accuracy=9.0250e-01, log_loss=3.7090e-01, accuracy=9.0250e-01, time spent=1.289s, total time spent=2.66min. Find new best=False, Find new top-3=False
[Iter 84/130, Epoch 6] valid accuracy=9.0500e-01, log_loss=3.9091e-01, accuracy=9.0500e-01, time spent=1.297s, total time spent=2.74min. Find new best=False, Find new top-3=False
[Iter 87/130, Epoch 6] valid accuracy=9.0500e-01, log_loss=3.9383e-01, accuracy=9.0500e-01, time spent=1.327s, total time spent=2.83min. Find new best=False, Find new top-3=False
[Iter 90/130, Epoch 6] valid accuracy=9.0500e-01, log_loss=3.9027e-01, accuracy=9.0500e-01, time spent=1.318s, total time spent=2.91min. Find new best=False, Find new top-3=False
[Iter 93/130, Epoch 7] valid accuracy=9.0500e-01, log_loss=3.9749e-01, accuracy=9.0500e-01, time spent=1.312s, total time spent=3.00min. Find new best=False, Find new top-3=False
[Iter 96/130, Epoch 7] valid accuracy=9.0000e-01, log_loss=3.9372e-01, accuracy=9.0000e-01, time spent=1.332s, total time spent=3.08min. Find new best=False, Find new top-3=False
[Iter 99/130, Epoch 7] valid accuracy=9.0750e-01, log_loss=4.1423e-01, accuracy=9.0750e-01, time spent=1.331s, total time spent=3.18min. Find new best=False, Find new top-3=True
[Iter 102/130, Epoch 7] valid accuracy=9.0500e-01, log_loss=4.2846e-01, accuracy=9.0500e-01, time spent=1.331s, total time spent=3.27min. Find new best=False, Find new top-3=False
[Iter 105/130, Epoch 8] valid accuracy=9.0750e-01, log_loss=4.0725e-01, accuracy=9.0750e-01, time spent=1.330s, total time spent=3.37min. Find new best=False, Find new top-3=True
[Iter 108/130, Epoch 8] valid accuracy=9.0500e-01, log_loss=4.0536e-01, accuracy=9.0500e-01, time spent=1.341s, total time spent=3.45min. Find new best=False, Find new top-3=False
[Iter 111/130, Epoch 8] valid accuracy=9.0500e-01, log_loss=4.0858e-01, accuracy=9.0500e-01, time spent=1.340s, total time spent=3.54min. Find new best=False, Find new top-3=False
[Iter 114/130, Epoch 8] valid accuracy=9.0750e-01, log_loss=4.1866e-01, accuracy=9.0750e-01, time spent=1.341s, total time spent=3.64min. Find new best=False, Find new top-3=True
[Iter 117/130, Epoch 8] valid accuracy=9.0500e-01, log_loss=4.2452e-01, accuracy=9.0500e-01, time spent=1.329s, total time spent=3.73min. Find new best=False, Find new top-3=False
[Iter 120/130, Epoch 9] valid accuracy=9.1000e-01, log_loss=4.1915e-01, accuracy=9.1000e-01, time spent=1.332s, total time spent=3.84min. Find new best=True, Find new top-3=True
[Iter 123/130, Epoch 9] valid accuracy=9.0750e-01, log_loss=4.1409e-01, accuracy=9.0750e-01, time spent=1.342s, total time spent=3.95min. Find new best=False, Find new top-3=True
[Iter 126/130, Epoch 9] valid accuracy=9.0750e-01, log_loss=4.1246e-01, accuracy=9.0750e-01, time spent=1.339s, total time spent=4.05min. Find new best=False, Find new top-3=True
[Iter 129/130, Epoch 9] valid accuracy=9.0750e-01, log_loss=4.1382e-01, accuracy=9.0750e-01, time spent=1.339s, total time spent=4.15min. Find new best=False, Find new top-3=True
[Iter 130/130, Epoch 9] valid accuracy=9.0750e-01, log_loss=4.1382e-01, accuracy=9.0750e-01, time spent=1.334s, total time spent=4.21min. Find new best=False, Find new top-3=True
    0.9075   = Validation accuracy score
    264.21s  = Training runtime
    1.72s    = Validation runtime
Fitting model: WeightedEnsemble_L2 ...
    0.91     = Validation accuracy score
    0.22s    = Training runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 278.45s ...
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("ag_tabular_product_sentiment_multimodal/")
<autogluon.tabular.predictor.predictor.TabularPredictor at 0x7f6d77fe6210>
predictor.leaderboard(dev_df)
                 model  score_test  score_val  pred_time_test  pred_time_val    fit_time  pred_time_test_marginal  pred_time_val_marginal  fit_time_marginal  stack_level  can_infer  fit_order
0    TextNeuralNetwork    0.899529     0.9075        4.175249       1.722744  264.207438                 4.175249                1.722744         264.207438            1       True          7
1  WeightedEnsemble_L2    0.897959     0.9100        4.196687       1.728344  265.110279                 0.014357                0.000474           0.215358            2       True          8
2        LightGBMLarge    0.888540     0.8850        0.017300       0.005964    2.045071                 0.017300                0.005964           2.045071            1       True          6
3       NeuralNetMXNet    0.886970     0.8825        0.044420       0.029103    1.667168                 0.044420                0.029103           1.667168            1       True          1
4             LightGBM    0.885400     0.8875        0.007081       0.005126    0.687484                 0.007081                0.005126           0.687484            1       True          2
5             CatBoost    0.885400     0.8825        0.014005       0.013277    0.619002                 0.014005                0.013277           0.619002            1       True          4
6              XGBoost    0.882261     0.8925        0.139195       0.008446    1.264214                 0.139195                0.008446           1.264214            1       True          5
7           LightGBMXT    0.868132     0.8625        0.008704       0.005285    0.650856                 0.008704                0.005285           0.650856            1       True          3
model score_test score_val pred_time_test pred_time_val fit_time pred_time_test_marginal pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 TextNeuralNetwork 0.899529 0.9075 4.175249 1.722744 264.207438 4.175249 1.722744 264.207438 1 True 7
1 WeightedEnsemble_L2 0.897959 0.9100 4.196687 1.728344 265.110279 0.014357 0.000474 0.215358 2 True 8
2 LightGBMLarge 0.888540 0.8850 0.017300 0.005964 2.045071 0.017300 0.005964 2.045071 1 True 6
3 NeuralNetMXNet 0.886970 0.8825 0.044420 0.029103 1.667168 0.044420 0.029103 1.667168 1 True 1
4 LightGBM 0.885400 0.8875 0.007081 0.005126 0.687484 0.007081 0.005126 0.687484 1 True 2
5 CatBoost 0.885400 0.8825 0.014005 0.013277 0.619002 0.014005 0.013277 0.619002 1 True 4
6 XGBoost 0.882261 0.8925 0.139195 0.008446 1.264214 0.139195 0.008446 1.264214 1 True 5
7 LightGBMXT 0.868132 0.8625 0.008704 0.005285 0.650856 0.008704 0.005285 0.650856 1 True 3

Improve the Performance with Stack Ensemble

You can improve predictive performance by using stack ensembling. One way to turn it on is as follows:

predictor.fit(train_df, hyperparameters='multimodal', num_bag_folds=5, num_stack_levels=1)

or using:

predictor.fit(train_df, hyperparameters='multimodal', presets='best_quality')

which will automatically select values for num_stack_levels (how many stacking layers) and num_bag_folds (how many folds to split data into during bagging). Stack ensembling can take much longer, so we won’t run with this configuration here. You may explore more examples in https://github.com/awslabs/autogluon/tree/master/examples/text_prediction, which demonstrate how you can achieve top performance in competitions with a stack ensembling based solution.