{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"This [great kernel](https://www.kaggle.com/iafoss/pretrained-resnet34-with-rgby-0-448-public-lb#) uses FocalLoss written for PyTorch and has a success with it. In case you'd like to use same loss function in Keras, I've rewritten it here.\n\nThere is [another good implementation of FocalLoss here](https://github.com/mkocabas/focal-loss-keras), but it differs for the one used by lafoss.\nThis kernel is aimed for people who would like to replicate his results step by step in Keras."},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from keras import backend as K\nimport tensorflow as tf\n\ndef KerasFocalLoss(target, input):\n    \n    gamma = 2.\n    input = tf.cast(input, tf.float32)\n    \n    max_val = K.clip(-input, 0, 1)\n    loss = input - input * target + max_val + K.log(K.exp(-max_val) + K.exp(-input - max_val))\n    invprobs = tf.log_sigmoid(-input * (target * 2.0 - 1.0))\n    loss = K.exp(invprobs * gamma) * loss\n    \n    return K.mean(K.sum(loss, axis=1))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c81966a8c4048ff00dbf362c7fd66d7dbc22fb98"},"cell_type":"markdown","source":"# Sanity check\n\nCheck that my Keras implementation returns same values."},{"metadata":{"trusted":true,"_uuid":"28166611ee1edb3fc6ef7d9d607260575e734eac"},"cell_type":"code","source":"import numpy as np\nfrom fastai.conv_learner import *\nfrom fastai.dataset import *\n\n\n# credits: https://www.kaggle.com/iafoss/pretrained-resnet34-with-rgby-0-448-public-lb#\n# credits originally: https://becominghuman.ai/investigating-focal-and-dice-loss-for-the-kaggle-2018-data-science-bowl-65fb9af4f36c\n\nclass FocalLoss(nn.Module):\n    def __init__(self, gamma=2):\n        super().__init__()\n        self.gamma = gamma\n        \n    def forward(self, input, target):\n\n        if not (target.size() == input.size()):\n            raise ValueError(\"Target size ({}) must be the same as input size ({})\"\n                             .format(target.size(), input.size()))\n\n        max_val = (-input).clamp(min=0)\n        loss = input - input * target + max_val + ((-max_val).exp() + (-input - max_val).exp()).log()\n        invprobs = F.logsigmoid(-input * (target * 2.0 - 1.0))\n        loss = (invprobs * self.gamma).exp() * loss\n        \n        return loss.sum(dim=1).mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f9028f56b5bf9a875bd2b02f11cc82eaa4c55b1f"},"cell_type":"code","source":"# define some results\nY_true = np.array([[0, 1, 0, 1, 0], [1, 0, 1, 0, 1]])\nY_pred = np.array([[0.1, 0.2, 0.3, 0.4, 0.5], [0.6, 0.7, 0.8, 0.9, 1]], dtype=np.float32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"269e0e230825b0a6afb76f49c780d8458f356995"},"cell_type":"code","source":"fc = FocalLoss()\n\nprint(fc.forward(torch.from_numpy(Y_pred), torch.from_numpy(Y_true.astype(np.float32))))\nprint(K.eval(KerasFocalLoss(Y_true, Y_pred)))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c2e792a95d59fc0778c1ce11109abc838b0c38ad"},"cell_type":"markdown","source":""}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}