Custom DataLoader for Imbalanced dataset¶
- In this notebook we will use the higly imbalanced Protein Homology Dataset from KDD cup 2004
* The first element of each line is a BLOCK ID that denotes to which native sequence this example belongs. There is a unique BLOCK ID for each native sequence. BLOCK IDs are integers running from 1 to 303 (one for each native sequence, i.e. for each query). BLOCK IDs were assigned before the blocks were split into the train and test sets, so they do not run consecutively in either file.
* The second element of each line is an EXAMPLE ID that uniquely describes the example. You will need this EXAMPLE ID and the BLOCK ID when you submit results.
* The third element is the class of the example. Proteins that are homologous to the native sequence are denoted by 1, non-homologous proteins (i.e. decoys) by 0. Test examples have a "?" in this position.
* All following elements are feature values. There are 74 feature values in each line. The features describe the match (e.g. the score of a sequence alignment) between the native protein sequence and the sequence that is tested for homology.
Initial imports¶
In [15]:
Copied!
from pytorch_widedeep import Trainer
from pytorch_widedeep.preprocessing import TabPreprocessor
from pytorch_widedeep.models import TabMlp, WideDeep
from pytorch_widedeep.dataloaders import DataLoaderImbalanced
from pytorch_widedeep.metrics import Accuracy, Precision
from pytorch_widedeep.initializers import XavierNormal
from pytorch_widedeep.datasets import load_bio_kdd04
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import time
import datetime
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
from pytorch_widedeep import Trainer
from pytorch_widedeep.preprocessing import TabPreprocessor
from pytorch_widedeep.models import TabMlp, WideDeep
from pytorch_widedeep.dataloaders import DataLoaderImbalanced
from pytorch_widedeep.metrics import Accuracy, Precision
from pytorch_widedeep.initializers import XavierNormal
from pytorch_widedeep.datasets import load_bio_kdd04
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import time
import datetime
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
In [10]:
Copied!
df = load_bio_kdd04(as_frame=True)
# drop columns we won't need in this example
df.drop(columns=["EXAMPLE_ID", "BLOCK_ID"], inplace=True)
df_train, df_valid = train_test_split(
df, test_size=0.2, stratify=df["target"], random_state=1
)
df_valid, df_test = train_test_split(
df_valid, test_size=0.5, stratify=df_valid["target"], random_state=1
)
continuous_cols = df.drop(columns=["target"]).columns.values.tolist()
df = load_bio_kdd04(as_frame=True)
# drop columns we won't need in this example
df.drop(columns=["EXAMPLE_ID", "BLOCK_ID"], inplace=True)
df_train, df_valid = train_test_split(
df, test_size=0.2, stratify=df["target"], random_state=1
)
df_valid, df_test = train_test_split(
df_valid, test_size=0.5, stratify=df_valid["target"], random_state=1
)
continuous_cols = df.drop(columns=["target"]).columns.values.tolist()
In [11]:
Copied!
# deeptabular
tab_preprocessor = TabPreprocessor(continuous_cols=continuous_cols, scale=True)
X_tab_train = tab_preprocessor.fit_transform(df_train)
X_tab_valid = tab_preprocessor.transform(df_valid)
X_tab_test = tab_preprocessor.transform(df_test)
# target
y_train = df_train["target"].values
y_valid = df_valid["target"].values
y_test = df_test["target"].values
# deeptabular
tab_preprocessor = TabPreprocessor(continuous_cols=continuous_cols, scale=True)
X_tab_train = tab_preprocessor.fit_transform(df_train)
X_tab_valid = tab_preprocessor.transform(df_valid)
X_tab_test = tab_preprocessor.transform(df_test)
# target
y_train = df_train["target"].values
y_valid = df_valid["target"].values
y_test = df_test["target"].values
In [12]:
Copied!
deeptabular = TabMlp(
column_idx=tab_preprocessor.column_idx,
continuous_cols=tab_preprocessor.continuous_cols,
mlp_hidden_dims=[64, 32],
)
model = WideDeep(deeptabular=deeptabular)
model
deeptabular = TabMlp(
column_idx=tab_preprocessor.column_idx,
continuous_cols=tab_preprocessor.continuous_cols,
mlp_hidden_dims=[64, 32],
)
model = WideDeep(deeptabular=deeptabular)
model
Out[12]:
WideDeep(
(deeptabular): Sequential(
(0): TabMlp(
(cont_norm): Identity()
(encoder): MLP(
(mlp): Sequential(
(dense_layer_0): Sequential(
(0): Linear(in_features=74, out_features=64, bias=True)
(1): ReLU(inplace=True)
(2): Dropout(p=0.1, inplace=False)
)
(dense_layer_1): Sequential(
(0): Linear(in_features=64, out_features=32, bias=True)
(1): ReLU(inplace=True)
(2): Dropout(p=0.1, inplace=False)
)
)
)
)
(1): Linear(in_features=32, out_features=1, bias=True)
)
)
In [13]:
Copied!
trainer = Trainer(
model,
objective="binary",
metrics=[Accuracy(), Precision()],
verbose=1,
)
trainer = Trainer(
model,
objective="binary",
metrics=[Accuracy(), Precision()],
verbose=1,
)
In [16]:
Copied!
train_dataloader = DataLoaderImbalanced(kwargs={"oversample_mul": 5})
# in reality one should not really do this, but just to illustrate
eval_dataloader = DataLoaderImbalanced(kwargs={"oversample_mul": 5})
trainer.fit(
X_train={"X_tab": X_tab_train, "target": y_train},
X_val={"X_tab": X_tab_valid, "target": y_valid},
n_epochs=1,
batch_size=32,
train_dataloader=train_dataloader,
eval_dataloader=eval_dataloader,
)
preds = trainer.predict(X_tab=X_tab_test)
print(classification_report(df_test["target"].to_list(), preds))
train_dataloader = DataLoaderImbalanced(kwargs={"oversample_mul": 5})
# in reality one should not really do this, but just to illustrate
eval_dataloader = DataLoaderImbalanced(kwargs={"oversample_mul": 5})
trainer.fit(
X_train={"X_tab": X_tab_train, "target": y_train},
X_val={"X_tab": X_tab_valid, "target": y_valid},
n_epochs=1,
batch_size=32,
train_dataloader=train_dataloader,
eval_dataloader=eval_dataloader,
)
preds = trainer.predict(X_tab=X_tab_test)
print(classification_report(df_test["target"].to_list(), preds))
epoch 1: 100%|██████████| 2074/2074 [00:10<00:00, 194.90it/s, loss=0.115, metrics={'acc': 0.959, 'prec': 0.9637}]
valid: 100%|██████████| 258/258 [00:00<00:00, 330.04it/s, loss=0.189, metrics={'acc': 0.9147, 'prec': 0.9825}]
predict: 100%|██████████| 456/456 [00:00<00:00, 679.61it/s]
precision recall f1-score support
0 1.00 0.98 0.99 14446
1 0.26 0.94 0.41 130
accuracy 0.98 14576
macro avg 0.63 0.96 0.70 14576
weighted avg 0.99 0.98 0.98 14576