{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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)\nfrom pathlib import Path\nimport fastai\nfrom fastai.vision import *\nimport cv2\nimport torch\nfrom torch.nn import Conv2d\nfrom sklearn.model_selection import train_test_split\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":{"trusted":true},"cell_type":"code","source":"path = Path('../input/recursion-cellular-image-classification')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"tr_df = pd.read_csv(path/'train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_df['site'] = 1\ntr_df_copy = tr_df.copy()\ntr_df_copy['site'] = 2\ntr_df = tr_df.append(tr_df_copy, ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_df.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_img_path(experiment, plate, well, site=1):\n    return experiment + '/' + 'Plate' + str(plate) + '/' + well + '_s{}'.format(site)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_df['path'] = tr_df.apply(lambda row : get_img_path(row.experiment, row.plate, row.well, row.site), axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tr_df['cellline'] = tr_df.apply(lambda row : row.experiment[:-3], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cell_lines = list(tr_df.cellline.unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cell_lines","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class RecursionImageList(ImageList):\n    def open(self, fn:PathOrStr) -> Image:\n        fn = str(fn)\n        imgs = []\n        for channel in [1, 2, 3, 4, 5, 6]:\n            img_path = fn + '_w{}'.format(channel) + '.png'\n            imgs.append(cv2.imread(img_path, cv2.IMREAD_GRAYSCALE))\n        img = cv2.merge(imgs)\n        img = img / 255.0\n        return Image(px=pil2tensor(img, np.float32))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# tr_df_small = tr_df.sample(n=120, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"src = (\n    RecursionImageList.from_df(tr_df, path=path/'train', cols=['path'])\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = tr_df\ntr_df, va_df = train_test_split(df, test_size=0.05, random_state=42, stratify = df.cellline)\nsrc = src.split_by_list(RecursionImageList.from_df(tr_df, path=path/'train', cols=['path']), \n                        RecursionImageList.from_df(va_df, path=path/'train', cols=['path']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# src = src.split_subsets(train_size=0.001, valid_size=0.001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"src = src.label_from_df(cols=['cellline'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = src.transform(size=512).databunch(bs=16, pin_memory=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"precision = Precision(average=\"macro\")\nrecall = Recall(average=\"macro\")\nloss_func = CrossEntropyFlat()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(data, models.resnet18, metrics=[accuracy, error_rate, precision, recall],\n                    loss_func=loss_func,\n                    model_dir='/kaggle/working', pretrained=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.model[0][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# let's make our model work with single channel\ntrained_kernel = learn.model[0][0].weight\nnew_conv = Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\nwith torch.no_grad():\n    new_conv.weight[:,:] = torch.stack([torch.mean(trained_kernel, 1)] * 6, dim=1)\nlearn.model[0][0] = new_conv\nlearn.model.cuda();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !ls ../input/recursion-fast-ai-channel-2-4-resnet50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# learn.load('../input/recursion-fast-ai-channel-2-4-resnet50/stage-05');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# learn.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Find a good learning rate\nlearn.lr_find(start_lr=1.0e-5, end_lr=1e-1, num_it=256)\nlearn.recorder.plot(suggestion=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!nvidia-smi","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit(8, 3e-4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.recorder.plot_losses()\nlearn.recorder.plot_metrics()\nlearn.recorder.plot_lr(show_moms=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-01')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.validate(dl=learn.data.train_dl)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"te_df = pd.read_csv(path/'test.csv')\nte_df['path1'] = te_df.apply(lambda row : get_img_path(row.experiment, row.plate, row.well, site=1), axis=1)\nte_df['path2'] = te_df.apply(lambda row : get_img_path(row.experiment, row.plate, row.well, site=2), axis=1)\nte_df['cellline'] = te_df.apply(lambda row : row.experiment[:-3], axis=1)\ntest_src1 = RecursionImageList.from_df(te_df, path=path/'test', cols=['path1'])\ntest_src2 = RecursionImageList.from_df(te_df, path=path/'test', cols=['path2'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.data.add_test(test_src1)\npreds1, y = learn.get_preds(DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.data.add_test(test_src2)\npreds2,y = learn.get_preds(DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = 0.5 * (preds1 + preds2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"te_df['pred_cellline'] = preds.argmax(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cell_line_dict = dict(enumerate(cell_lines))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cell_line_dict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"1 - (te_df['pred_cellline'].apply(lambda row: cell_line_dict[row]) == te_df['cellline']).mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}