{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":false},"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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"code","source":"\n\nimport os\nimport cv2\nimport random\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport torch\nfrom fastai.vision import *\nimport glob\nprint(os.listdir(\"../input/fastai-pretrained-models\"))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"PATH = \"../input/aptos2019-blindness-detection\"\n!mkdir -p /tmp/.cache/torch/checkpoints/\n!cp ../input/fastai-pretrained-models/resnet101-5d3b4d8f.pth /tmp/.cache/torch/checkpoints/resnet101-5d3b4d8f.pth","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"SIZE=224\n\ntrain_df=pd.read_csv(PATH+'/train.csv')\ntest_df=pd.read_csv(PATH+'/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"train = ImageList.from_df(train_df, path=PATH, cols='id_code', folder=\"train_images\", suffix='.png')\ntest = ImageList.from_df(test_df, path=PATH, cols='id_code', folder=\"test_images\", suffix='.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"def quadratic_kappa(y_hat, y):\n    return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0')","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"def crop_image(img,tol=7):        \n    mask = img>tol\n    return img[np.ix_(mask.any(1),mask.any(0))]\n\ndef open_aptos2019_image(fn, convert_mode, after_open)->Image:\n    image = cv2.imread(fn)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    image = crop_image(image)\n    image = cv2.resize(image, (SIZE, SIZE))\n    image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image , (0,0) , SIZE/10) ,-4 ,128)\n    return Image(pil2tensor(image, np.float32).div_(255))\n\nvision.data.open_image = open_aptos2019_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"from sklearn.metrics import cohen_kappa_score\ndata = (\n    train.split_by_rand_pct(0.2)\n    .label_from_df(cols='diagnosis', label_cls=FloatList)\n    .add_test(test)\n    .transform(get_transforms(), size=SIZE)\n    .databunch(path=Path('.'), bs=32).normalize(imagenet_stats)\n)\ndata.show_batch(rows=3, figsize=(7,6))","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"learn = cnn_learner(data, models.resnet101, metrics=[quadratic_kappa], pretrained=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"learn.fit_one_cycle(6, slice(2.75e-03,2.75e-02))\nlearn.recorder.plot_losses()\nlearn.recorder.plot_metrics()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"learn.save('stage1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"learn.unfreeze()\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"lr = 2.75e-03\nlearn.fit_one_cycle(4,slice(1.5e-06,lr/8),wd=0.05)\n#learn.fit_one_cycle(10, slice(5e-06, lr/8))","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"valid_preds, valid_y = learn.TTA(ds_type=DatasetType.Valid)\ntest_preds, _ = learn.TTA(ds_type=DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"class OptimizedRounder(object):\n    def __init__(self):\n        self.coef_ = 0\n\n    def _kappa_loss(self, coef, X, y):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n\n        ll = cohen_kappa_score(y, X_p, weights='quadratic')\n        return -ll\n\n    def fit(self, X, y):\n        loss_partial = partial(self._kappa_loss, X=X, y=y)\n        initial_coef = [0.5, 1.5, 2.5, 3.5]\n        self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\n\n    def predict(self, X, coef):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n        return X_p\n\n    def coefficients(self):\n        return self.coef_['x']","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"optR = OptimizedRounder()\noptR.fit(valid_preds, valid_y)\ncoefficients = optR.coefficients()\n\nvalid_predictions = optR.predict(valid_preds, coefficients)[:,0].astype(int)\ntest_predictions = optR.predict(test_preds, coefficients)[:,0].astype(int)\n\nvalid_score = cohen_kappa_score(valid_y.numpy().astype(int), valid_predictions, weights=\"quadratic\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"valid_score = cohen_kappa_score(valid_y.numpy().astype(int), valid_predictions, weights=\"quadratic\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"print(\"coefficients:\", coefficients)\nprint(\"validation score:\", valid_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.diagnosis = test_predictions\ntest_df.to_csv(\"submission.csv\", index=None)\ntest_df.head()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}