In [1]:
#| default_exp model.optimization.nn.tsc.vittsc.pen_digits_evaluation_mask
%load_ext autoreload
%autoreload 2
In [2]:
# declare a list tasks whose products you want to use as inputs
upstream = ['tabular_to_timeseries_pen_digits', 'model_training_pen_digits']
In [3]:
# Parameters
upstream = {"model_training_pen_digits": {"nb": "/home/ubuntu/vitmtsc_nbdev/output/403_model.optimization.nn.tsc.vittsc.pen_digits_training_mask_tune.html", "PenDigits_MODEL_TUNE_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/ray_results", "PenDigits_MODEL_TRAINING_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result", "PenDigits_MODEL_TRAINING_CHECKPOINT_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/checkpoint", "PenDigits_BEST_MODEL": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/best_model.ckpt", "PenDigits_BEST_MODEL_CONFIG": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/best_model_config.json"}, "tabular_to_timeseries_pen_digits": {"nb": "/home/ubuntu/vitmtsc_nbdev/output/303_feature_preprocessing.pen_digits.tabular_to_timeseries.html", "PenDigits_TRAIN_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/train", "PenDigits_VALID_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/valid", "PenDigits_TEST_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/test"}}
product = {"nb": "/home/ubuntu/vitmtsc_nbdev/output/503_model.optimization.nn.tsc.vittsc.pen_digits_evaluation_mask.html", "PenDigits_MODEL_VALID_EVAL_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/valid", "PenDigits_MODEL_TEST_EVAL_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/test"}
In [4]:
#| hide
from nbdev.showdoc import *
In [5]:
#| export
import sys
import pathlib as p

def is_running_from_ipython():
    from IPython import get_ipython
    return get_ipython() is not None

if not is_running_from_ipython() and __package__ is None:
    DIR = p.Path(__file__).resolve().parent
    sys.path.insert(0, str(DIR.parent))
    __package__ = DIR.name
In [6]:
#| export
from vitmtsc.model.optimization.nn.tsc.vittsc.pen_digits_training_mask_tune import *
class_weight: [0.47730892 0.48191318 0.46982759 0.51327055 0.47428797 0.52865961
 0.5362254  0.48660714 0.52959364 0.51415094]
In [7]:
#| export
upstream = {
    "tabular_to_timeseries_pen_digits": {
        "nb": "/home/ubuntu/vitmtsc_nbdev/output/303_feature_preprocessing.pen_digits.tabular_to_timeseries.html",
        "PenDigits_TRAIN_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/train",
        "PenDigits_VALID_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/valid",
        "PenDigits_TEST_MODEL_INPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/test",
    },
    "model_training_pen_digits": {
        "nb": "/home/ubuntu/vitmtsc_nbdev/output/403_model.optimization.nn.tsc.vittsc.pen_digits_training_mask_tune.html",
        "PenDigits_MODEL_TUNE_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/ray_results",
        "PenDigits_MODEL_TRAINING_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result",
        "PenDigits_MODEL_TRAINING_CHECKPOINT_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/checkpoint",
        "PenDigits_BEST_MODEL": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/best_model.ckpt",
        "PenDigits_BEST_MODEL_CONFIG": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/best_model_config.json",
    },
}
product = {
    "nb": "/home/ubuntu/vitmtsc_nbdev/output/503_model.optimization.nn.tsc.vittsc.pen_digits_evaluation_mask.html",
    "PenDigits_MODEL_VALID_EVAL_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/valid",
    "PenDigits_MODEL_TEST_EVAL_OUTPUT": "/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/test",
}
In [8]:
# |export
import json
def get_best_model_config():
    with open(upstream['model_training_pen_digits']['PenDigits_BEST_MODEL_CONFIG'], 'r') as json_file:
        return json.load(json_file)
In [9]:
#| export
import pandas as pd
import os
import torch
import math
import glob

import pytorch_lightning as pl
from torch.nn import functional as F
import matplotlib.pyplot as plt
import scikitplot as skplt
from pytorch_lightning import LightningModule
from pytorch_lightning import Trainer
from petastorm import make_batch_reader
from petastorm.pytorch import DataLoader

Vision Transformer for Multivariate Time-Series Classification (VitMTSC) Model with Masking - Evaluation¶

Load Model

Model Evaluation: Evaluate Model on test and validation dataset using PR-AUC

In [10]:
#| export
DATASET_NAME = 'PenDigits'

VALID_DATA_DIR = f"file://{upstream['tabular_to_timeseries_pen_digits']['PenDigits_VALID_MODEL_INPUT']}"
TEST_DATA_DIR = f"file://{upstream['tabular_to_timeseries_pen_digits']['PenDigits_TEST_MODEL_INPUT']}"
VALID_EVAL_OUTPUT_DIR = product['PenDigits_MODEL_VALID_EVAL_OUTPUT']
TEST_EVAL_OUTPUT_DIR = product['PenDigits_MODEL_TEST_EVAL_OUTPUT']
BEST_MODEL_CHECKPOINT = upstream['model_training_pen_digits']['PenDigits_BEST_MODEL']
NUM_WORKERS=1
SHARD_COUNT=1
BATCH_SIZE = 64
TOTAL_VALID_BATCHES = math.ceil(get_valid_dataset_size()/BATCH_SIZE)
TOTAL_TEST_BATCHES = math.ceil(get_test_dataset_size()/BATCH_SIZE)
BEST_MODEL_CHECKPOINT, TOTAL_VALID_BATCHES, TOTAL_TEST_BATCHES, VALID_DATA_DIR, TEST_DATA_DIR, VALID_EVAL_OUTPUT_DIR, TEST_EVAL_OUTPUT_DIR
Out[10]:
('/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/best_model.ckpt',
 94,
 55,
 'file:///home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/valid',
 'file:///home/ubuntu/vitmtsc_nbdev/output/PenDigits/target_encoding-nn/test',
 '/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/valid',
 '/home/ubuntu/vitmtsc_nbdev/output/PenDigits/experiments_result/evaluation/test')
In [11]:
!mkdir -p $VALID_EVAL_OUTPUT_DIR
!mkdir -p $TEST_EVAL_OUTPUT_DIR

1. VitMTSC Classification Prediction Task¶

In [12]:
#| export
class VitMTSCClassificationPredictionTask(LightningModule):
    def __init__(self, 
                 model,
                 output_pred_dir,
                 input_data_dir,
                 batch_size=BATCH_SIZE,
                 num_workers=NUM_WORKERS,
                 shard_count = SHARD_COUNT):
        super().__init__()
        pl.seed_everything(42, workers=True)
        self.model = model
        self.case_id = []
        self.probability_0 = []
        self.probability_1 = []
        self.probability_2 = []
        self.probability_3 = []
        self.probability_4 = []
        self.probability_5 = []
        self.probability_6 = []
        self.probability_7 = []
        self.probability_8 = []
        self.probability_9 = []
        self.prediction = []
        self.target = []
        self.output_pred_dir = output_pred_dir
        self.input_data_dir = input_data_dir
        self.prediction_files = input_data_dir
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.shard_count = shard_count
    
    def test_step(self, batch, batch_idx):
        x, y, case_id_1, mask = batch
        y_hat = self.model(x, mask)
        self.case_id.extend(case_id_1.to('cpu').numpy())
        self.probability_0.extend(F.softmax(y_hat, dim=1)[:,0].to('cpu').numpy())
        self.probability_1.extend(F.softmax(y_hat, dim=1)[:,1].to('cpu').numpy())
        self.probability_2.extend(F.softmax(y_hat, dim=1)[:,2].to('cpu').numpy())
        self.probability_3.extend(F.softmax(y_hat, dim=1)[:,3].to('cpu').numpy())
        self.probability_4.extend(F.softmax(y_hat, dim=1)[:,4].to('cpu').numpy())
        self.probability_5.extend(F.softmax(y_hat, dim=1)[:,5].to('cpu').numpy())
        self.probability_6.extend(F.softmax(y_hat, dim=1)[:,6].to('cpu').numpy())
        self.probability_7.extend(F.softmax(y_hat, dim=1)[:,7].to('cpu').numpy())
        self.probability_8.extend(F.softmax(y_hat, dim=1)[:,8].to('cpu').numpy())
        self.probability_9.extend(F.softmax(y_hat, dim=1)[:,9].to('cpu').numpy())
        self.prediction.extend(torch.max(y_hat.data, 1)[1].to('cpu').numpy())
        self.target.extend(y.to('cpu').numpy())
        
    def test_dataloader(self):
        print('test_dataloader: local rank :', int(os.environ['LOCAL_RANK']), 'shard count: ', self.shard_count)
        self.test_ds = make_batch_reader(self.prediction_files, workers_count=self.num_workers, 
                                         cur_shard = int(os.environ['LOCAL_RANK']), 
                                         shard_count = self.shard_count, num_epochs = 2)
        return DataLoader(self.test_ds, batch_size = self.batch_size, collate_fn= petastorm_collate_fn) 
    
    def test_epoch_end(self, outputs):
        print('Consolidating predictions on GPU:', os.environ['LOCAL_RANK'])
        df_text_predictions = pd.DataFrame({'case_id': self.case_id, 
                                            'probability_0': self.probability_0, 
                                            'probability_1': self.probability_1, 
                                            'probability_2': self.probability_2, 
                                            'probability_3': self.probability_3, 
                                            'probability_4': self.probability_4, 
                                            'probability_5': self.probability_5, 
                                            'probability_6': self.probability_6, 
                                            'probability_7': self.probability_7, 
                                            'probability_8': self.probability_8, 
                                            'probability_9': self.probability_9,
                                            'prediction': self.prediction,
                                            'target': self.target
                                            })
        print('Writing predictions on GPU:', os.environ['LOCAL_RANK'])
        df_text_predictions.to_csv(self.output_pred_dir + "/" + os.environ['LOCAL_RANK'] + '_predictions.csv', index=False)
        print('Finished Writing predictions on GPU:', os.environ['LOCAL_RANK'])
In [13]:
#| export
def get_model_for_prediction(BEST_MODEL_CHECKPOINT, config, output_pred_dir, input_data_dir, shard_count = SHARD_COUNT):
    # load the best model
    pl.seed_everything(42, workers=True)
    model = VitTimeSeriesTransformer.load_from_checkpoint(BEST_MODEL_CHECKPOINT, config = config)
    model.eval()
    return VitMTSCClassificationPredictionTask(model = model, shard_count = shard_count, output_pred_dir = output_pred_dir, input_data_dir = input_data_dir)
In [14]:
#| export   
def write_prediction_for_valid_dataset(BEST_MODEL_CHECKPOINT,
                                      config,
                                      shard_count,
                                      output_pred_dir = VALID_EVAL_OUTPUT_DIR,
                                      input_data_dir=VALID_DATA_DIR):
    pl.seed_everything(42, workers=True)
    model = get_model_for_prediction(BEST_MODEL_CHECKPOINT = BEST_MODEL_CHECKPOINT, 
                                     config = config,
                                     shard_count = shard_count, 
                                     output_pred_dir = output_pred_dir, 
                                     input_data_dir = input_data_dir)
    trainer = Trainer(gpus = [0], 
                      accelerator='dp', 
                      progress_bar_refresh_rate=1, 
                      limit_test_batches = TOTAL_VALID_BATCHES)
    trainer.test(model)
    
def write_prediction_for_test_dataset(BEST_MODEL_CHECKPOINT,
                                      config,
                                      shard_count,
                                      output_pred_dir = TEST_EVAL_OUTPUT_DIR,
                                      input_data_dir=TEST_DATA_DIR):
    pl.seed_everything(42, workers=True)
    model = get_model_for_prediction(BEST_MODEL_CHECKPOINT = BEST_MODEL_CHECKPOINT, 
                                     config = config,
                                     shard_count = shard_count, 
                                     output_pred_dir = output_pred_dir, 
                                     input_data_dir = input_data_dir)
    trainer = Trainer(gpus = [0], 
                      accelerator='dp', 
                      progress_bar_refresh_rate=1, 
                      limit_test_batches = TOTAL_TEST_BATCHES)
    trainer.test(model)
In [15]:
%env LOCAL_RANK=0
env: LOCAL_RANK=0
In [16]:
#| export
if __name__ == "__main__":
    print('Processing valid dataset...\n')
    write_prediction_for_valid_dataset(BEST_MODEL_CHECKPOINT = BEST_MODEL_CHECKPOINT, 
                                      config = get_best_model_config(),
                                      shard_count = SHARD_COUNT)
    print('Finished Processing valid dataset!!!\n')
    
    print('Processing test dataset...\n')
    write_prediction_for_test_dataset(BEST_MODEL_CHECKPOINT = BEST_MODEL_CHECKPOINT, 
                                      config = get_best_model_config(),
                                      shard_count = SHARD_COUNT)
    print('Finished Processing test dataset!!!\n')
Global seed set to 42
Global seed set to 42
Global seed set to 42
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/trainer/connectors/accelerator_connector.py:297: LightningDeprecationWarning: Passing `Trainer(accelerator='dp')` has been deprecated in v1.5 and will be removed in v1.7. Use `Trainer(strategy='dp')` instead.
  rank_zero_deprecation(
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/loops/utilities.py:91: PossibleUserWarning: `max_epochs` was not set. Setting it to 1000 epochs. To train without an epoch limit, set `max_epochs=-1`.
  rank_zero_warn(
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/trainer/connectors/callback_connector.py:96: LightningDeprecationWarning: Setting `Trainer(progress_bar_refresh_rate=1)` is deprecated in v1.5 and will be removed in v1.7. Please pass `pytorch_lightning.callbacks.progress.TQDMProgressBar` with `refresh_rate` directly to the Trainer's `callbacks` argument instead. Or, to disable the progress bar pass `enable_progress_bar = False` to the Trainer.
  rank_zero_deprecation(
GPU available: True, used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
Missing logger folder: /home/ubuntu/vitmtsc_nbdev/lightning_logs
Processing valid dataset...

LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0,1,2,3]
test_dataloader: local rank : 0 shard count:  1
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/fs_utils.py:88: FutureWarning: pyarrow.localfs is deprecated as of 2.0.0, please use pyarrow.fs.LocalFileSystem instead.
  self._filesystem = pyarrow.localfs
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:402: FutureWarning: Specifying the 'metadata_nthreads' argument is deprecated as of pyarrow 8.0.0, and the argument will be removed in a future version
  dataset = pq.ParquetDataset(path_or_paths, filesystem=fs, validate_schema=False, metadata_nthreads=10)
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:362: FutureWarning: 'ParquetDataset.common_metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  if not dataset.common_metadata:
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/reader.py:405: FutureWarning: Specifying the 'metadata_nthreads' argument is deprecated as of pyarrow 8.0.0, and the argument will be removed in a future version
  self.dataset = pq.ParquetDataset(dataset_path, filesystem=pyarrow_filesystem,
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/unischema.py:317: FutureWarning: 'ParquetDataset.pieces' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.fragments' attribute instead.
  meta = parquet_dataset.pieces[0].get_metadata()
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/unischema.py:321: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  for partition in (parquet_dataset.partitions or []):
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:253: FutureWarning: 'ParquetDataset.metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  metadata = dataset.metadata
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:254: FutureWarning: 'ParquetDataset.common_metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  common_metadata = dataset.common_metadata
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:350: FutureWarning: 'ParquetDataset.pieces' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.fragments' attribute instead.
  futures_list = [thread_pool.submit(_split_piece, piece, dataset.fs.open) for piece in dataset.pieces]
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:350: FutureWarning: 'ParquetDataset.fs' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.filesystem' attribute instead.
  futures_list = [thread_pool.submit(_split_piece, piece, dataset.fs.open) for piece in dataset.pieces]
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:334: FutureWarning: ParquetDatasetPiece is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  return [pq.ParquetDatasetPiece(piece.path, open_file_func=fs_open,
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:138: FutureWarning: 'ParquetDataset.fs' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.filesystem' attribute instead.
  parquet_file = ParquetFile(self._dataset.fs.open(piece.path))
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:286: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  partition_names = self._dataset.partitions.partition_names if self._dataset.partitions else set()
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:289: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  table = piece.read(columns=column_names - partition_names, partitions=self._dataset.partitions)
Testing: 0it [00:00, ?it/s]
Global seed set to 42
Global seed set to 42
Global seed set to 42
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/trainer/connectors/accelerator_connector.py:297: LightningDeprecationWarning: Passing `Trainer(accelerator='dp')` has been deprecated in v1.5 and will be removed in v1.7. Use `Trainer(strategy='dp')` instead.
  rank_zero_deprecation(
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/loops/utilities.py:91: PossibleUserWarning: `max_epochs` was not set. Setting it to 1000 epochs. To train without an epoch limit, set `max_epochs=-1`.
  rank_zero_warn(
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/pytorch_lightning/trainer/connectors/callback_connector.py:96: LightningDeprecationWarning: Setting `Trainer(progress_bar_refresh_rate=1)` is deprecated in v1.5 and will be removed in v1.7. Please pass `pytorch_lightning.callbacks.progress.TQDMProgressBar` with `refresh_rate` directly to the Trainer's `callbacks` argument instead. Or, to disable the progress bar pass `enable_progress_bar = False` to the Trainer.
  rank_zero_deprecation(
GPU available: True, used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0,1,2,3]
Consolidating predictions on GPU: 0
Writing predictions on GPU: 0
Finished Writing predictions on GPU: 0
Finished Processing valid dataset!!!

Processing test dataset...

test_dataloader: local rank : 0 shard count:  1
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/fs_utils.py:88: FutureWarning: pyarrow.localfs is deprecated as of 2.0.0, please use pyarrow.fs.LocalFileSystem instead.
  self._filesystem = pyarrow.localfs
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:402: FutureWarning: Specifying the 'metadata_nthreads' argument is deprecated as of pyarrow 8.0.0, and the argument will be removed in a future version
  dataset = pq.ParquetDataset(path_or_paths, filesystem=fs, validate_schema=False, metadata_nthreads=10)
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:362: FutureWarning: 'ParquetDataset.common_metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  if not dataset.common_metadata:
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/reader.py:405: FutureWarning: Specifying the 'metadata_nthreads' argument is deprecated as of pyarrow 8.0.0, and the argument will be removed in a future version
  self.dataset = pq.ParquetDataset(dataset_path, filesystem=pyarrow_filesystem,
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/unischema.py:317: FutureWarning: 'ParquetDataset.pieces' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.fragments' attribute instead.
  meta = parquet_dataset.pieces[0].get_metadata()
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/unischema.py:321: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  for partition in (parquet_dataset.partitions or []):
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:253: FutureWarning: 'ParquetDataset.metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  metadata = dataset.metadata
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:254: FutureWarning: 'ParquetDataset.common_metadata' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  common_metadata = dataset.common_metadata
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:350: FutureWarning: 'ParquetDataset.pieces' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.fragments' attribute instead.
  futures_list = [thread_pool.submit(_split_piece, piece, dataset.fs.open) for piece in dataset.pieces]
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:350: FutureWarning: 'ParquetDataset.fs' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.filesystem' attribute instead.
  futures_list = [thread_pool.submit(_split_piece, piece, dataset.fs.open) for piece in dataset.pieces]
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/etl/dataset_metadata.py:334: FutureWarning: ParquetDatasetPiece is deprecated as of pyarrow 5.0.0 and will be removed in a future version.
  return [pq.ParquetDatasetPiece(piece.path, open_file_func=fs_open,
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:138: FutureWarning: 'ParquetDataset.fs' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.filesystem' attribute instead.
  parquet_file = ParquetFile(self._dataset.fs.open(piece.path))
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:286: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  partition_names = self._dataset.partitions.partition_names if self._dataset.partitions else set()
/home/ubuntu/anaconda3/envs/rapids-22.08_ploomber/lib/python3.8/site-packages/petastorm/arrow_reader_worker.py:289: FutureWarning: 'ParquetDataset.partitions' attribute is deprecated as of pyarrow 5.0.0 and will be removed in a future version. Specify 'use_legacy_dataset=False' while constructing the ParquetDataset, and then use the '.partitioning' attribute instead.
  table = piece.read(columns=column_names - partition_names, partitions=self._dataset.partitions)
Testing: 0it [00:00, ?it/s]
Consolidating predictions on GPU: 0
Writing predictions on GPU: 0
Finished Writing predictions on GPU: 0
Finished Processing test dataset!!!

2. Valid Dataset Prediction Evaluation¶

In [17]:
import scikitplot as skplt
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
from sklearn.metrics import f1_score

valid_gdf = pd.concat(map(pd.read_csv, glob.glob(f'{VALID_EVAL_OUTPUT_DIR}/*.csv')))
valid_gdf['target'] = valid_gdf['target'].astype('int64')
valid_gdf['case_id'] = valid_gdf['case_id'].astype('int64')
valid_gdf = valid_gdf.drop_duplicates()
valid_gdf
Out[17]:
case_id probability_0 probability_1 probability_2 probability_3 probability_4 probability_5 probability_6 probability_7 probability_8 probability_9 prediction target
0 1058 0.000166 0.998261 2.286276e-04 0.000024 0.000112 0.000011 0.000177 0.000130 0.000011 0.000879 1 1
1 6385 0.002315 0.000215 2.023655e-05 0.000069 0.996016 0.000097 0.000470 0.000003 0.000270 0.000524 4 4
2 589 0.000025 0.001607 1.686597e-04 0.988019 0.000664 0.002243 0.000065 0.000020 0.000504 0.006686 3 3
3 4333 0.000013 0.000997 5.663831e-04 0.996973 0.000340 0.000167 0.000090 0.000012 0.000772 0.000069 3 3
4 954 0.000006 0.000268 1.630294e-03 0.996070 0.000302 0.000273 0.000040 0.000019 0.001298 0.000094 3 3
... ... ... ... ... ... ... ... ... ... ... ... ... ...
5990 529 0.000191 0.000014 7.946492e-06 0.000054 0.000092 0.997461 0.000424 0.000773 0.000319 0.000663 5 5
5991 5793 0.000064 0.000381 8.207239e-07 0.000098 0.000773 0.000231 0.000015 0.000037 0.000037 0.998364 9 9
5992 2856 0.001553 0.000047 8.179735e-06 0.000072 0.997188 0.000118 0.000592 0.000002 0.000242 0.000178 4 4
5993 3911 0.000006 0.000488 2.501828e-04 0.998382 0.000222 0.000213 0.000036 0.000005 0.000284 0.000113 3 3
5994 2643 0.000009 0.004174 9.939153e-01 0.000575 0.000033 0.000055 0.000377 0.000721 0.000140 0.000001 2 2

5995 rows × 13 columns

In [18]:
valid_gdf[valid_gdf.prediction == valid_gdf.target].count()
Out[18]:
case_id          5963
probability_0    5963
probability_1    5963
probability_2    5963
probability_3    5963
probability_4    5963
probability_5    5963
probability_6    5963
probability_7    5963
probability_8    5963
probability_9    5963
prediction       5963
target           5963
dtype: int64
In [19]:
valid_gdf['target'].min(), valid_gdf['prediction'].min(), valid_gdf['target'].max(), valid_gdf['prediction'].max()
Out[19]:
(0, 0, 9, 9)
In [20]:
skplt.metrics.plot_precision_recall(valid_gdf['target'].to_numpy(), 
                                    valid_gdf[['probability_0', 'probability_1', 'probability_2', 'probability_3', 'probability_4',
                                             'probability_5', 'probability_6', 'probability_7', 'probability_8', 'probability_9']].to_numpy(), 
                                    cmap='nipy_spectral')
plt.show()
In [21]:
skplt.metrics.plot_roc(valid_gdf['target'].to_numpy(), 
                       valid_gdf[['probability_0', 'probability_1', 'probability_2', 'probability_3', 'probability_4',
                                  'probability_5', 'probability_6', 'probability_7', 'probability_8', 'probability_9']].to_numpy(), 
                       cmap='nipy_spectral')
plt.show()
In [22]:
f1_score(valid_gdf['target'], valid_gdf['prediction'], average='macro')
Out[22]:
0.9947727404900883
In [23]:
f1_score(valid_gdf['target'], valid_gdf['prediction'], average='weighted')
Out[23]:
0.9946631280402078

3. Test Dataset Prediction Evaluation¶

In [24]:
test_gdf = pd.concat(map(pd.read_csv, glob.glob(f'{TEST_EVAL_OUTPUT_DIR}/*.csv')))
test_gdf['target'] = test_gdf['target'].astype('int64')
test_gdf['case_id'] = test_gdf['case_id'].astype('int64')
test_gdf = test_gdf.drop_duplicates()
test_gdf
Out[24]:
case_id probability_0 probability_1 probability_2 probability_3 probability_4 probability_5 probability_6 probability_7 probability_8 probability_9 prediction target
0 819 0.000568 0.000003 0.000020 0.000162 0.000025 0.000181 0.000017 0.000125 0.998855 0.000046 8 8
1 2500 0.000098 0.000004 0.000051 0.000339 0.000051 0.000112 0.000011 0.000047 0.999252 0.000033 8 8
2 2683 0.000009 0.000929 0.000306 0.997776 0.000154 0.000341 0.000037 0.000007 0.000302 0.000140 3 3
3 3266 0.000329 0.972163 0.019162 0.000075 0.000017 0.000117 0.001428 0.006386 0.000274 0.000048 1 1
4 2445 0.000005 0.000510 0.000505 0.998208 0.000182 0.000162 0.000038 0.000005 0.000310 0.000075 3 3
... ... ... ... ... ... ... ... ... ... ... ... ... ...
3493 3181 0.000004 0.000679 0.996775 0.001046 0.000040 0.000050 0.000300 0.000896 0.000209 0.000001 2 2
3494 2392 0.997786 0.000401 0.000030 0.000009 0.000752 0.000083 0.000209 0.000199 0.000347 0.000184 0 0
3495 1736 0.000165 0.000156 0.000189 0.000014 0.000259 0.000422 0.998451 0.000310 0.000031 0.000002 6 6
3496 1641 0.000327 0.000101 0.000240 0.000014 0.000620 0.000396 0.997998 0.000250 0.000050 0.000003 6 6
3497 2782 0.000284 0.998244 0.000577 0.000015 0.000010 0.000030 0.000362 0.000351 0.000027 0.000100 1 1

3498 rows × 13 columns

In [25]:
test_gdf[test_gdf.prediction == test_gdf.target].count()
Out[25]:
case_id          3402
probability_0    3402
probability_1    3402
probability_2    3402
probability_3    3402
probability_4    3402
probability_5    3402
probability_6    3402
probability_7    3402
probability_8    3402
probability_9    3402
prediction       3402
target           3402
dtype: int64
In [26]:
test_gdf['target'].min(), test_gdf['prediction'].min(), test_gdf['target'].max(), test_gdf['prediction'].max()
Out[26]:
(0, 0, 9, 9)
In [27]:
skplt.metrics.plot_precision_recall(test_gdf['target'].to_numpy(), 
                                    test_gdf[['probability_0', 'probability_1', 'probability_2', 'probability_3', 'probability_4',
                                             'probability_5', 'probability_6', 'probability_7', 'probability_8', 'probability_9']].to_numpy(), 
                                    cmap='nipy_spectral')
plt.show()
In [28]:
skplt.metrics.plot_roc(test_gdf['target'].to_numpy(), 
                       test_gdf[['probability_0', 'probability_1', 'probability_2', 'probability_3', 'probability_4',
                                 'probability_5', 'probability_6', 'probability_7', 'probability_8', 'probability_9']].to_numpy(), 
                       cmap='nipy_spectral')
plt.show()
In [29]:
f1_score(test_gdf['target'], test_gdf['prediction'], average='macro')
Out[29]:
0.9729983939882019
In [30]:
f1_score(test_gdf['target'], test_gdf['prediction'], average='weighted')
Out[30]:
0.972562580397056

We shutdown the kernel!!!

In [31]:
from nbdev import nbdev_export
nbdev_export()