{"cells":[{"metadata":{},"cell_type":"markdown","source":"# SEResNeXt 0.9663"},{"metadata":{},"cell_type":"markdown","source":"![](https://images.lingvozone.com/languages/Language%20Information21_files/image005.gif)"},{"metadata":{"trusted":true,"_kg_hide-output":true,"_kg_hide-input":true},"cell_type":"code","source":"# !pip install pretrainedmodels  # <- need internet connection\n# Ref: https://www.kaggle.com/rishabhiitbhu/unet-starter-kernel-pytorch-lb-0-88 for installation\n\n!pip install ../input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/ > /dev/null # no output\n# !pip install ../input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import gc\nimport os\nfrom pathlib import Path\nimport random\nimport sys\n\nfrom tqdm.notebook import tqdm\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom IPython.core.display import display, HTML\n\n# --- plotly ---\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\n\n# --- models ---\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb\n\n# --- setup ---\npd.set_option('max_columns', 50)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"debug=False\nsubmission=True\nbatch_size=256\ndevice='cuda:0'\nout='.'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":false,"_kg_hide-output":true},"cell_type":"code","source":"datadir = Path('/kaggle/input/bengaliai-cv19')\nfeatherdir = Path('/kaggle/input/bengaliaicv19feather')\noutdir = Path('.')","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# Read in the data CSV files\n# train = pd.read_csv(datadir/'train.csv')\n# test = pd.read_csv(datadir/'test.csv')\n# sample_submission = pd.read_csv(datadir/'sample_submission.csv')\n# class_map = pd.read_csv(datadir/'class_map.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define util classes"},{"metadata":{},"cell_type":"markdown","source":"## Dataset"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\"\"\"\nReferenced `chainer.dataset.DatasetMixin` to work with pytorch Dataset.\n\"\"\"\nimport numpy\nimport six\nimport torch\nfrom torch.utils.data.dataset import Dataset\n\n\nclass DatasetMixin(Dataset):\n\n    def __init__(self, transform=None):\n        self.transform = transform\n\n    def __getitem__(self, index):\n        \"\"\"Returns an example or a sequence of examples.\"\"\"\n        if torch.is_tensor(index):\n            index = index.tolist()\n        if isinstance(index, slice):\n            current, stop, step = index.indices(len(self))\n            return [self.get_example_wrapper(i) for i in\n                    six.moves.range(current, stop, step)]\n        elif isinstance(index, list) or isinstance(index, numpy.ndarray):\n            return [self.get_example_wrapper(i) for i in index]\n        else:\n            return self.get_example_wrapper(index)\n\n    def __len__(self):\n        \"\"\"Returns the number of data points.\"\"\"\n        raise NotImplementedError\n\n    def get_example_wrapper(self, i):\n        \"\"\"Wrapper of `get_example`, to apply `transform` if necessary\"\"\"\n        example = self.get_example(i)\n        if self.transform:\n            example = self.transform(example)\n        return example\n\n    def get_example(self, i):\n        \"\"\"Returns the i-th example.\n\n        Implementations should override it. It should raise :class:`IndexError`\n        if the index is invalid.\n\n        Args:\n            i (int): The index of the example.\n\n        Returns:\n            The i-th example.\n\n        \"\"\"\n        raise NotImplementedError\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import numpy as np\n\n\nclass BengaliAIDataset(DatasetMixin):\n    def __init__(self, images, labels=None, transform=None, indices=None):\n        super(BengaliAIDataset, self).__init__(transform=transform)\n        self.images = images\n        self.labels = labels\n        if indices is None:\n            indices = np.arange(len(images))\n        self.indices = indices\n        self.train = labels is not None\n\n    def __len__(self):\n        \"\"\"return length of this dataset\"\"\"\n        return len(self.indices)\n\n    def get_example(self, i):\n        \"\"\"Return i-th data\"\"\"\n        i = self.indices[i]\n        x = self.images[i]\n        # Opposite white and black: background will be white (1.0) and\n        # for future Affine transformation\n        x = (255 - x).astype(np.float32) / 255.\n        if self.train:\n            y = self.labels[i]\n            return x, y\n        else:\n            return x\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Data augmentation/processing"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"\"\"\"\nFrom https://www.kaggle.com/corochann/deep-learning-cnn-with-chainer-lb-0-99700\n\"\"\"\nimport cv2\nfrom skimage.transform import AffineTransform, warp\nimport numpy as np\n\n\ndef affine_image(img):\n    \"\"\"\n\n    Args:\n        img: (h, w) or (1, h, w)\n\n    Returns:\n        img: (h, w)\n    \"\"\"\n    # ch, h, w = img.shape\n    # img = img / 255.\n    if img.ndim == 3:\n        img = img[0]\n\n    # --- scale ---\n    min_scale = 0.8\n    max_scale = 1.2\n    sx = np.random.uniform(min_scale, max_scale)\n    sy = np.random.uniform(min_scale, max_scale)\n\n    # --- rotation ---\n    max_rot_angle = 7\n    rot_angle = np.random.uniform(-max_rot_angle, max_rot_angle) * np.pi / 180.\n\n    # --- shear ---\n    max_shear_angle = 10\n    shear_angle = np.random.uniform(-max_shear_angle, max_shear_angle) * np.pi / 180.\n\n    # --- translation ---\n    max_translation = 4\n    tx = np.random.randint(-max_translation, max_translation)\n    ty = np.random.randint(-max_translation, max_translation)\n\n    tform = AffineTransform(scale=(sx, sy), rotation=rot_angle, shear=shear_angle,\n                            translation=(tx, ty))\n    transformed_image = warp(img, tform)\n    assert transformed_image.ndim == 2\n    return transformed_image\n\n\ndef crop_char_image(image, threshold=40./255.):\n    assert image.ndim == 2\n    is_black = image > threshold\n\n    is_black_vertical = np.sum(is_black, axis=0) > 0\n    is_black_horizontal = np.sum(is_black, axis=1) > 0\n    left = np.argmax(is_black_horizontal)\n    right = np.argmax(is_black_horizontal[::-1])\n    top = np.argmax(is_black_vertical)\n    bottom = np.argmax(is_black_vertical[::-1])\n    height, width = image.shape\n    cropped_image = image[left:height - right, top:width - bottom]\n    return cropped_image\n\n\ndef resize(image, size=(128, 128)):\n    return cv2.resize(image, size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import numpy as np\n\n\ndef add_gaussian_noise(x, sigma):\n    x += np.random.randn(*x.shape) * sigma\n    x = np.clip(x, 0., 1.)\n    return x\n\n\nclass Transform:\n    def __init__(self, affine=True, crop=True, size=(64, 64),\n                 normalize=True, train=True, threshold=40.,\n                 sigma=-1.):\n        self.affine = affine\n        self.crop = crop\n        self.size = size\n        self.normalize = normalize\n        self.train = train\n        self.threshold = threshold / 255.\n        self.sigma = sigma / 255.\n\n    def __call__(self, example):\n        if self.train:\n            x, y = example\n        else:\n            x = example\n        # --- Augmentation ---\n        if self.affine:\n            x = affine_image(x)\n\n        # --- Train/Test common preprocessing ---\n        if self.crop:\n            x = crop_char_image(x, threshold=self.threshold)\n        if self.size is not None:\n            x = resize(x, size=self.size)\n        if self.sigma > 0.:\n            x = add_gaussian_noise(x, sigma=self.sigma)\n        if self.normalize:\n            x = (x.astype(np.float32) - 0.0692) / 0.2051\n        if x.ndim == 2:\n            x = x[None, :, :]\n        x = x.astype(np.float32)\n        if self.train:\n            y = y.astype(np.int64)\n            return x, y\n        else:\n            return x","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## pytorch model & define classifier"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import torch\n\n\ndef residual_add(lhs, rhs):\n    lhs_ch, rhs_ch = lhs.shape[1], rhs.shape[1]\n    if lhs_ch < rhs_ch:\n        out = lhs + rhs[:, :lhs_ch]\n    elif lhs_ch > rhs_ch:\n        out = torch.cat([lhs[:, :rhs_ch] + rhs, lhs[:, rhs_ch:]], dim=1)\n    else:\n        out = lhs + rhs\n    return out\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"from typing import List\n\nimport torch\nfrom torch import nn\nfrom torch.nn.parameter import Parameter\n\n\nclass LazyLoadModule(nn.Module):\n    \"\"\"Lazy buffer/parameter loading using load_state_dict_pre_hook\n\n    Define all buffer/parameter in `_lazy_buffer_keys`/`_lazy_parameter_keys` and\n    save buffer with `register_buffer`/`register_parameter`\n    method, which can be outside of __init__ method.\n    Then this module can load any shape of Tensor during de-serializing.\n\n    Note that default value of lazy buffer is torch.Tensor([]), while lazy parameter is None.\n    \"\"\"\n    _lazy_buffer_keys: List[str] = []     # It needs to be override to register lazy buffer\n    _lazy_parameter_keys: List[str] = []  # It needs to be override to register lazy parameter\n\n    def __init__(self):\n        super(LazyLoadModule, self).__init__()\n        for k in self._lazy_buffer_keys:\n            self.register_buffer(k, torch.tensor([]))\n        for k in self._lazy_parameter_keys:\n            self.register_parameter(k, None)\n        self._register_load_state_dict_pre_hook(self._hook)\n\n    def _hook(self, state_dict, prefix, local_metadata, strict, missing_keys,\n             unexpected_keys, error_msgs):\n        for key in self._lazy_buffer_keys:\n            self.register_buffer(key, state_dict[prefix + key])\n\n        for key in self._lazy_parameter_keys:\n            self.register_parameter(key, Parameter(state_dict[prefix + key]))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import math\nimport torch\nfrom torch.nn import init\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\n\n\nclass LazyLinear(LazyLoadModule):\n    \"\"\"Linear module with lazy input inference\n\n    `in_features` can be `None`, and it is determined at the first time of forward step dynamically.\n    \"\"\"\n\n    __constants__ = ['bias', 'in_features', 'out_features']\n    _lazy_parameter_keys = ['weight']\n\n    def __init__(self, in_features, out_features, bias=True):\n        super(LazyLinear, self).__init__()\n        self.in_features = in_features\n        self.out_features = out_features\n        if bias:\n            self.bias = Parameter(torch.Tensor(out_features))\n        else:\n            self.register_parameter('bias', None)\n\n        if in_features is not None:\n            self.weight = Parameter(torch.Tensor(out_features, in_features))\n            self.reset_parameters()\n\n    def reset_parameters(self):\n        init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n        if self.bias is not None:\n            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)\n            bound = 1 / math.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def forward(self, input):\n        if self.weight is None:\n            self.in_features = input.shape[-1]\n            self.weight = Parameter(torch.Tensor(self.out_features, self.in_features))\n            self.reset_parameters()\n\n            # Need to send lazy defined parameter to device...\n            self.to(input.device)\n        return F.linear(input, self.weight, self.bias)\n\n    def extra_repr(self):\n        return 'in_features={}, out_features={}, bias={}'.format(\n            self.in_features, self.out_features, self.bias is not None\n        )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"from torch import nn\nimport torch.nn.functional as F\n\n\nclass LinearBlock(nn.Module):\n\n    def __init__(self, in_features, out_features, bias=True,\n                 use_bn=True, activation=F.relu, dropout_ratio=-1, residual=False,):\n        super(LinearBlock, self).__init__()\n        if in_features is None:\n            self.linear = LazyLinear(in_features, out_features, bias=bias)\n        else:\n            self.linear = nn.Linear(in_features, out_features, bias=bias)\n        if use_bn:\n            self.bn = nn.BatchNorm1d(out_features)\n        if dropout_ratio > 0.:\n            self.dropout = nn.Dropout(p=dropout_ratio)\n        else:\n            self.dropout = None\n        self.activation = activation\n        self.use_bn = use_bn\n        self.dropout_ratio = dropout_ratio\n        self.residual = residual\n\n    def __call__(self, x):\n        h = self.linear(x)\n        if self.use_bn:\n            h = self.bn(h)\n        if self.activation is not None:\n            h = self.activation(h)\n        if self.residual:\n            h = residual_add(h, x)\n        if self.dropout_ratio > 0:\n            h = self.dropout(h)\n        return h","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import pretrainedmodels\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.nn import Sequential\n\n\nclass PretrainedCNN(nn.Module):\n    def __init__(self, model_name='se_resnext101_32x4d',\n                 in_channels=1, out_dim=10, use_bn=True,\n                 pretrained=None):\n        super(PretrainedCNN, self).__init__()\n        self.conv0 = nn.Conv2d(\n            in_channels, 3, kernel_size=3, stride=1, padding=1, bias=True)\n        self.base_model = pretrainedmodels.__dict__[model_name](pretrained=pretrained)\n        activation = F.leaky_relu\n        self.do_pooling = True\n        if self.do_pooling:\n            inch = self.base_model.last_linear.in_features\n        else:\n            inch = None\n        hdim = 512\n        lin1 = LinearBlock(inch, hdim, use_bn=use_bn, activation=activation, residual=False)\n        lin2 = LinearBlock(hdim, out_dim, use_bn=use_bn, activation=None, residual=False)\n        self.lin_layers = Sequential(lin1, lin2)\n\n    def forward(self, x):\n        h = self.conv0(x)\n        h = self.base_model.features(h)\n\n        if self.do_pooling:\n            h = torch.sum(h, dim=(-1, -2))\n        else:\n            # [128, 2048, 4, 4] when input is (128, 128)\n            bs, ch, height, width = h.shape\n            h = h.view(bs, ch*height*width)\n        for layer in self.lin_layers:\n            h = layer(h)\n        return h","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Classifier"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\n\ndef accuracy(y, t):\n    pred_label = torch.argmax(y, dim=1)\n    count = pred_label.shape[0]\n    correct = (pred_label == t).sum().type(torch.float32)\n    acc = correct / count\n    return acc\n\n\nclass BengaliClassifier(nn.Module):\n    def __init__(self, predictor, n_grapheme=168, n_vowel=11, n_consonant=7):\n        super(BengaliClassifier, self).__init__()\n        self.n_grapheme = n_grapheme\n        self.n_vowel = n_vowel\n        self.n_consonant = n_consonant\n        self.n_total_class = self.n_grapheme + self.n_vowel + self.n_consonant\n        self.predictor = predictor\n\n        self.metrics_keys = [\n            'loss', 'loss_grapheme', 'loss_vowel', 'loss_consonant',\n            'acc_grapheme', 'acc_vowel', 'acc_consonant']\n\n    def forward(self, x, y=None):\n        pred = self.predictor(x)\n        if isinstance(pred, tuple):\n            assert len(pred) == 3\n            preds = pred\n        else:\n            assert pred.shape[1] == self.n_total_class\n            preds = torch.split(pred, [self.n_grapheme, self.n_vowel, self.n_consonant], dim=1)\n        loss_grapheme = F.cross_entropy(preds[0], y[:, 0])\n        loss_vowel = F.cross_entropy(preds[1], y[:, 1])\n        loss_consonant = F.cross_entropy(preds[2], y[:, 2])\n        loss = loss_grapheme + loss_vowel + loss_consonant\n        metrics = {\n            'loss': loss.item(),\n            'loss_grapheme': loss_grapheme.item(),\n            'loss_vowel': loss_vowel.item(),\n            'loss_consonant': loss_consonant.item(),\n            'acc_grapheme': accuracy(preds[0], y[:, 0]),\n            'acc_vowel': accuracy(preds[1], y[:, 1]),\n            'acc_consonant': accuracy(preds[2], y[:, 2]),\n        }\n        return loss, metrics, pred\n\n    def calc(self, data_loader):\n        device: torch.device = next(self.parameters()).device\n        self.eval()\n        output_list = []\n        with torch.no_grad():\n            for batch in tqdm(data_loader):\n                # TODO: support general preprocessing.\n                # If `data` is not `Data` instance, `to` method is not supported!\n                batch = batch.to(device)\n                pred = self.predictor(batch)\n                output_list.append(pred)\n        output = torch.cat(output_list, dim=0)\n        preds = torch.split(output, [self.n_grapheme, self.n_vowel, self.n_consonant], dim=1)\n        return preds\n\n    def predict_proba(self, data_loader):\n        preds = self.calc(data_loader)\n        return [F.softmax(p, dim=1) for p in preds]\n\n    def predict(self, data_loader):\n        preds = self.calc(data_loader)\n        pred_labels = [torch.argmax(p, dim=1) for p in preds]\n        return pred_labels\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def build_predictor(arch, out_dim, model_name=None):\n    if arch == 'pretrained':\n        predictor = PretrainedCNN(in_channels=1, out_dim=out_dim, model_name=model_name)\n    else:\n        raise ValueError(\"[ERROR] Unexpected value arch={}\".format(arch))\n    return predictor\n\n\ndef build_classifier(arch, load_model_path, n_total, model_name='', device='cuda:0'):\n    if isinstance(device, str):\n        device = torch.device(device)\n    predictor = build_predictor(arch, out_dim=n_total, model_name=model_name)\n    print('predictor', type(predictor))\n    classifier = BengaliClassifier(predictor)\n    if load_model_path:\n        predictor.load_state_dict(torch.load(load_model_path))\n    else:\n        print(\"[WARNING] Unexpected value load_model_path={}\"\n              .format(load_model_path))\n    classifier.to(device)\n    return classifier\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediction code"},{"metadata":{},"cell_type":"markdown","source":"## prepare data"},{"metadata":{"trusted":true,"_kg_hide-input":false},"cell_type":"code","source":"import gc\nimport numpy as np\nimport pandas as pd\n\n\ndef prepare_image(datadir, featherdir, data_type='train',\n                  submission=False, indices=[0, 1, 2, 3]):\n    assert data_type in ['train', 'test']\n    if submission:\n        image_df_list = [pd.read_parquet(datadir / f'{data_type}_image_data_{i}.parquet')\n                         for i in indices]\n    else:\n        image_df_list = [pd.read_feather(featherdir / f'{data_type}_image_data_{i}.feather')\n                         for i in indices]\n\n    print('image_df_list', len(image_df_list))\n    HEIGHT = 137\n    WIDTH = 236\n    images = [df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH) for df in image_df_list]\n    del image_df_list\n    gc.collect()\n    images = np.concatenate(images, axis=0)\n    return images\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def predict_core(test_images, image_size, threshold,\n                 arch, n_total, model_name, load_model_path, batch_size=512, device='cuda:0', **kwargs):\n    classifier = build_classifier(arch, load_model_path, n_total, model_name, device=device)\n    test_dataset = BengaliAIDataset(\n        test_images, None,\n        transform=Transform(affine=False, crop=True, size=(image_size, image_size),\n                            threshold=threshold, train=False))\n    print('test_dataset', len(test_dataset))\n    test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n    test_pred_proba = classifier.predict_proba(test_loader)\n    return test_pred_proba\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# --- Model ---\ndevice = torch.device(device)\nn_grapheme = 168\nn_vowel = 11\nn_consonant = 7\nn_total = n_grapheme + n_vowel + n_consonant\nprint('n_total', n_total)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from torch.utils.data.dataloader import DataLoader\nfrom chainer_chemistry.utils import save_json, load_json\n\n\n# --- Prediction ---\ntraindir = '/kaggle/input/bengaliaicv19-trainedmodels/'\ndata_type = 'test'\ntest_preds_list = []\n\nfor i in range(4):\n    # --- prepare data ---\n    indices = [i]\n    test_images = prepare_image(\n        datadir, featherdir, data_type=data_type, submission=submission, indices=indices)\n    n_dataset = len(test_images)\n    print(f'n_dataset={n_dataset}')\n    # print(f'i={i}, n_dataset={n_dataset}')\n    # test_data_size = 200 if debug else int(n_dataset * 0.9)\n\n    model_preds_list = []\n    for j in range(4):\n        # --- Depends on train configuration ---\n        train_args_dict = load_json(os.path.join(traindir, f'args_{j}.json'))\n        train_args_dict.update({\n            'load_model_path': os.path.join(traindir, f'predictor_{j}.pt'),\n            'device': device,\n            'batch_size': batch_size,\n            'debug': debug,\n        })\n        print(f'j {j} updated train_args_dict {train_args_dict}')\n        test_preds = predict_core(\n                test_images=test_images, n_total=n_total,\n                **train_args_dict)\n\n        model_preds_list.append(test_preds)\n\n    # --- ensemble ---\n    proba0 = torch.mean(torch.stack([test_preds[0] for test_preds in model_preds_list], dim=0), dim=0)\n    proba1 = torch.mean(torch.stack([test_preds[1] for test_preds in model_preds_list], dim=0), dim=0)\n    proba2 = torch.mean(torch.stack([test_preds[2] for test_preds in model_preds_list], dim=0), dim=0)\n    p0 = torch.argmax(proba0, dim=1).cpu().numpy()\n    p1 = torch.argmax(proba1, dim=1).cpu().numpy()\n    p2 = torch.argmax(proba2, dim=1).cpu().numpy()\n    print('p0', p0.shape, 'p1', p1.shape, 'p2', p2.shape)\n\n    test_preds_list.append([p0, p1, p2])\n    if debug:\n        break\n    del test_images\n    gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p0 = np.concatenate([test_preds[0] for test_preds in test_preds_list], axis=0)\np1 = np.concatenate([test_preds[1] for test_preds in test_preds_list], axis=0)\np2 = np.concatenate([test_preds[2] for test_preds in test_preds_list], axis=0)\nprint('concat:', 'p0', p0.shape, 'p1', p1.shape, 'p2', p2.shape)\n\nrow_id = []\ntarget = []\nfor i in tqdm(range(len(p0))):\n    row_id += [f'Test_{i}_grapheme_root', f'Test_{i}_vowel_diacritic',\n               f'Test_{i}_consonant_diacritic']\n    target += [p0[i], p1[i], p2[i]]\nsubmission_df = pd.DataFrame({'row_id': row_id, 'target': target})\nsubmission_df.to_csv('submission.csv', index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Check prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(datadir/'train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":false},"cell_type":"code","source":"pred_df = pd.DataFrame({\n    'grapheme_root': p0,\n    'vowel_diacritic': p1,\n    'consonant_diacritic': p2\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig, axes = plt.subplots(2, 3, figsize=(22, 6))\nplt.title('Label Count')\nsns.countplot(x=\"grapheme_root\",data=train, ax=axes[0, 0])\nsns.countplot(x=\"vowel_diacritic\",data=train, ax=axes[0, 1])\nsns.countplot(x=\"consonant_diacritic\",data=train, ax=axes[0, 2])\nsns.countplot(x=\"grapheme_root\",data=pred_df, ax=axes[1, 0])\nsns.countplot(x=\"vowel_diacritic\",data=pred_df, ax=axes[1, 1])\nsns.countplot(x=\"consonant_diacritic\",data=pred_df, ax=axes[1, 2])\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"train_labels = train[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig, axes = plt.subplots(1, 3, figsize=(22, 6))\nsns.distplot(train_labels[:, 0], ax=axes[0], color='green', kde=False, label='train grapheme')\nsns.distplot(train_labels[:, 1], ax=axes[1], color='green', kde=False, label='train vowel')\nsns.distplot(train_labels[:, 2], ax=axes[2], color='green', kde=False, label='train consonant')\nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"fig, axes = plt.subplots(1, 3, figsize=(22, 6))\nsns.distplot(p0, ax=axes[0], color='orange', kde=False, label='test grapheme')\nsns.distplot(p1, ax=axes[1], color='orange', kde=False, label='test vowel')\nsns.distplot(p2, ax=axes[2], color='orange', kde=False, label='test consonant')\nplt.legend()\nplt.tight_layout()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}