{"cells":[{"metadata":{},"cell_type":"markdown","source":"I saw [this kernel](https://www.kaggle.com/ratthachat/aptos-simple-preprocessing-decoloring-cropping) and learned about Ben Graham's Preprocessing.  \nIn this kernel, I try apply training Resnet50 by fast.ai.  \nI learned how to train fast.ai by [this kernel](https://www.kaggle.com/tanlikesmath/intro-aptos-diabetic-retinopathy-eda-starter).  \nThank you Neuron Engineer and ilovescience!!"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n\nimport os\nimport cv2\nimport random\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom sklearn.metrics import cohen_kappa_score\n\nimport torch\nfrom fastai.vision import *","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SEED = 1234\nSIZE = 224\n\nPATH = \"../input/aptos2019-blindness-detection\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nos.listdir('../input/densenet201')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\nseed_everything(SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir -p /tmp/.cache/torch/checkpoints/\n!cp ../input/densenet201/densenet201-c1103571.pth /tmp/.cache/torch/checkpoints/densenet201-c1103571.pth","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(PATH+\"/train.csv\")\nsub = pd.read_csv(PATH+\"/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = ImageList.from_df(train_df, path=PATH, cols='id_code', folder=\"train_images\", suffix='.png')\ntest = ImageList.from_df(sub, path=PATH, cols='id_code', folder=\"test_images\", suffix='.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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":true},"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":true},"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state = SEED)\n\nmodel_name = 'densenet201'\nbs = 64\npredictions = torch.from_numpy(np.zeros((len(sub))))\nfor fold, (train_index, val_index) in tqdm(enumerate(skf.split(train_df[\"id_code\"], train_df[\"diagnosis\"]))):\n    print(fold)\n    filename = model_name + \"fold_\" + str(fold)+\".pkl\"\n    print(\"Fold:\", filename)\n    print(\"TRAIN:\", train_index, \"VALIDATE:\", val_index)\n    \n    data_fold = (ImageList.from_df(train_df,\n                                   PATH,\n                                   folder='train_images'\n                                   ,cols=\"id_code\",suffix='.png')\n        .split_by_idxs(train_index, val_index)\n        .label_from_df(cols='diagnosis', label_cls=FloatList)\n        .transform(get_transforms(), size=SIZE)\n        .databunch(bs=bs).normalize(imagenet_stats)\n    )\n    \n    learn = cnn_learner(data_fold, models.densenet201, metrics=[quadratic_kappa], pretrained=True)\n    #learn.lr_find()\n    #learn.recorder.plot(suggestion=True)\n    learn.fit_one_cycle(5, 1e-2)        \n    learn.data.add_test(ImageList.from_df(sub ,PATH ,folder='test_images',suffix='.png'))\n    test_predsx, _ = learn.get_preds(ds_type=DatasetType.Test)\n    if (fold == 0):\n        test_preds = test_predsx\n    else:\n        test_preds = test_predsx + test_preds\n    \n    if (fold == 2):\n        valid_preds, valid_y = learn.get_preds(ds_type=DatasetType.Valid) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ref: https://www.kaggle.com/abhishek/optimizer-for-quadratic-weighted-kappa\n# thank you Abhishek Thakur!!\nclass 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":true},"cell_type":"code","source":"test_preds = test_preds/5\noptR = 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":true},"cell_type":"code","source":"valid_score = cohen_kappa_score(valid_y.numpy().astype(int), valid_predictions, weights=\"quadratic\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"coefficients:\", coefficients)\nprint(\"validation score:\", valid_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.diagnosis = test_predictions\nsub.to_csv(\"submission.csv\", index=None)\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.diagnosis.hist();","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Unfortunately, my local and public score down after added this preprocessing.  \nI may have some mistakes.  \nI'll try to learn more."}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}