{"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_minor":4,"nbformat":4,"cells":[{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n#import os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-06-16T16:16:18.767827Z","iopub.execute_input":"2021-06-16T16:16:18.768136Z","iopub.status.idle":"2021-06-16T16:16:18.775617Z","shell.execute_reply.started":"2021-06-16T16:16:18.768064Z","shell.execute_reply":"2021-06-16T16:16:18.77495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"EDA","metadata":{}},{"cell_type":"code","source":"# Loading libraries\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 cv2\nfrom PIL import Image\nfrom matplotlib import cm\n\nimport os\nprint(os.listdir(\"../input/\"))","metadata":{"execution":{"iopub.status.busy":"2021-06-16T16:16:18.779019Z","iopub.execute_input":"2021-06-16T16:16:18.779227Z","iopub.status.idle":"2021-06-16T16:16:19.010451Z","shell.execute_reply.started":"2021-06-16T16:16:18.779207Z","shell.execute_reply":"2021-06-16T16:16:19.009933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pixel_status = pd.read_csv('../input/recursion-cellular-image-classification/pixel_stats.csv')\ntrain_df = pd.read_csv('../input/recursion-cellular-image-classification/train.csv')\ntest_df = pd.read_csv('../input/recursion-cellular-image-classification/test.csv')\n\ntrain_controls = pd.read_csv('../input/recursion-cellular-image-classification/train_controls.csv')\ntest_controls = pd.read_csv('../input/recursion-cellular-image-classification/test_controls.csv')\n\nsub = pd.read_csv('../input/recursion-cellular-image-classification/sample_submission.csv')\n\nprint('Dimensions: \\n pixel_status: %s'\\\n     '\\n train_df: %s \\n test_df: %s' \\\n      '\\n train_controls: %s \\n test_controls: %s' \\\n      '\\n submission: %s' % (pixel_status.shape, train_df.shape, \n                            test_df.shape, train_controls.shape,\n                            test_controls.shape, sub.shape))","metadata":{"execution":{"iopub.status.busy":"2021-06-16T16:16:19.011352Z","iopub.execute_input":"2021-06-16T16:16:19.011627Z","iopub.status.idle":"2021-06-16T16:16:21.14697Z","shell.execute_reply.started":"2021-06-16T16:16:19.011606Z","shell.execute_reply":"2021-06-16T16:16:21.145891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pixel_status.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-16T16:16:21.148255Z","iopub.execute_input":"2021-06-16T16:16:21.148461Z","iopub.status.idle":"2021-06-16T16:16:21.178274Z","shell.execute_reply.started":"2021-06-16T16:16:21.148439Z","shell.execute_reply":"2021-06-16T16:16:21.177798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_controls.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-16T16:16:21.181356Z","iopub.execute_input":"2021-06-16T16:16:21.181665Z","iopub.status.idle":"2021-06-16T16:16:21.191023Z","shell.execute_reply.started":"2021-06-16T16:16:21.181642Z","shell.execute_reply":"2021-06-16T16:16:21.18999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-16T16:16:21.191994Z","iopub.execute_input":"2021-06-16T16:16:21.1922Z","iopub.status.idle":"2021-06-16T16:16:21.212725Z","shell.execute_reply.started":"2021-06-16T16:16:21.192164Z","shell.execute_reply":"2021-06-16T16:16:21.211871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Image from dataset with index 1\nexp, well, plate = train_df.loc[1,['experiment', 'well', 'plate']]\n\n# List of arrays of different channels(total 6) of the same image\nimg_names = [np.array(Image.open(os.path.join('../input/recursion-cellular-image-classification/train/',\n                                              exp,\n                                              f'Plate{plate}',\n                                              f'{well}_s{1}_w{channel}.png')),\n                      dtype=np.float32) for channel in range(1,7)]\n\n# Сonversion to a six-channel image\nsample = np.stack([img_ar for img_ar in img_names],axis=0)\nsample.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:37.685218Z","iopub.execute_input":"2021-06-16T05:18:37.68569Z","iopub.status.idle":"2021-06-16T05:18:37.840317Z","shell.execute_reply.started":"2021-06-16T05:18:37.685645Z","shell.execute_reply":"2021-06-16T05:18:37.839455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_cell(sample_img):    \n    channels = ['Nuclei', 'Endoplasmic reticuli', 'Actin', 'Nucleoli', 'Mitochondria', 'Golgi apparatus']\n    cmaps = ['gist_ncar','terrain', 'gnuplot' ,'rainbow','PiYG', 'gist_earth']\n\n    fig=plt.figure(figsize=(20, 15))\n    for i in range(1,6+1):\n        fig.add_subplot(1, 6, i)\n        plt.imshow(sample_img[i-1, :, :,],cmap=cmaps[i-1]);\n        plt.axis('off');\n        plt.title(f'{channels[i-1]}')\n    fig.suptitle(\"Single image channels\", y=0.65, fontsize=15)\n    plt.show()\n    \n## Let's looking on image channels\nplot_cell(sample)","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:37.841754Z","iopub.execute_input":"2021-06-16T05:18:37.842066Z","iopub.status.idle":"2021-06-16T05:18:38.448684Z","shell.execute_reply.started":"2021-06-16T05:18:37.842036Z","shell.execute_reply":"2021-06-16T05:18:38.447316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Datagenerator","metadata":{}},{"cell_type":"code","source":"# Loading libraries\nimport sys\n\npackage_path = '../input/efficientnet/efficientnet-pytorch/EfficientNet-PyTorch/'\nsys.path.append(package_path)","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:38.450451Z","iopub.execute_input":"2021-06-16T05:18:38.450885Z","iopub.status.idle":"2021-06-16T05:18:38.456372Z","shell.execute_reply.started":"2021-06-16T05:18:38.450839Z","shell.execute_reply":"2021-06-16T05:18:38.455256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install efficientnet-pytorch","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:38.458015Z","iopub.execute_input":"2021-06-16T05:18:38.458396Z","iopub.status.idle":"2021-06-16T05:18:48.795656Z","shell.execute_reply.started":"2021-06-16T05:18:38.458337Z","shell.execute_reply":"2021-06-16T05:18:48.794322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading libraries\nimport sys\nfrom efficientnet_pytorch import EfficientNet\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\n\nimport torchvision\nimport torchvision.transforms as transforms","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:48.79716Z","iopub.execute_input":"2021-06-16T05:18:48.79746Z","iopub.status.idle":"2021-06-16T05:18:49.996872Z","shell.execute_reply.started":"2021-06-16T05:18:48.797429Z","shell.execute_reply":"2021-06-16T05:18:49.995763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CellDataset(Dataset):\n    def __init__(self, df, img_dir, site=1, transforms=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.site = site\n        self.transforms = transforms\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, idx):\n        exp, well, plate = self.df.loc[idx,['experiment', 'well', 'plate']].values\n        img_channels = [np.array(Image.open(os.path.join(self.img_dir,\n                                             exp,\n                                             f'Plate{plate}',\n                                             f'{well}_s{self.site}_w{channel}.png')), \n                                          dtype=np.float32) for channel in range(1,7)]\n        \n        one_img = np.stack([channel for channel in img_channels],axis=2)\n        \n        if self.transforms is not None:\n            one_img = self.transforms(one_img)\n        if self.img_dir == '../input/recursion-cellular-image-classification/train/':\n            return one_img, self.df.loc[idx,['sirna']].astype('int32').values   \n        else:\n            return one_img","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:49.99825Z","iopub.execute_input":"2021-06-16T05:18:49.998556Z","iopub.status.idle":"2021-06-16T05:18:50.009295Z","shell.execute_reply.started":"2021-06-16T05:18:49.998528Z","shell.execute_reply":"2021-06-16T05:18:50.008018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augmentations for data\naug = transforms.Compose([\n      # transforms.ToPILImage(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.485, 0.456, 0.456, 0.406, 0.406],\n                                 std=[0.229, 0.229, 0.225, 0.225, 0.224, 0.224])\n])\n\n# Dataset & data loaders\ndataset = CellDataset(df=train_df, img_dir='../input/recursion-cellular-image-classification/train/', transforms=aug)\ntrain_loader = DataLoader(dataset=dataset, batch_size=15, shuffle=True)\n\ntest_dataset = CellDataset(df=test_df, img_dir='../input/recursion-cellular-image-classification/test/', transforms=aug)\ntest_loader = DataLoader(dataset=test_dataset, batch_size=15, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:50.011417Z","iopub.execute_input":"2021-06-16T05:18:50.01176Z","iopub.status.idle":"2021-06-16T05:18:50.024024Z","shell.execute_reply.started":"2021-06-16T05:18:50.011725Z","shell.execute_reply":"2021-06-16T05:18:50.022919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Data checking","metadata":{}},{"cell_type":"code","source":"#train_loader checking\ndata, target = next(iter(train_loader))\nprint(data.shape, target.shape)","metadata":{"execution":{"iopub.status.busy":"2021-06-16T05:18:50.025336Z","iopub.execute_input":"2021-06-16T05:18:50.025897Z","iopub.status.idle":"2021-06-16T05:18:50.39304Z","shell.execute_reply.started":"2021-06-16T05:18:50.025784Z","shell.execute_reply":"2021-06-16T05:18:50.390293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}