{"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\nimport os\nfor 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-07T03:28:11.118847Z","iopub.execute_input":"2021-06-07T03:28:11.119181Z","iopub.status.idle":"2021-06-07T03:28:14.260175Z","shell.execute_reply.started":"2021-06-07T03:28:11.119074Z","shell.execute_reply":"2021-06-07T03:28:14.259406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.image as mpimg\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import models\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.utils.data as utils\nfrom torchvision import transforms\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:14.261610Z","iopub.execute_input":"2021-06-07T03:28:14.261945Z","iopub.status.idle":"2021-06-07T03:28:15.450765Z","shell.execute_reply.started":"2021-06-07T03:28:14.261910Z","shell.execute_reply":"2021-06-07T03:28:15.449954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = \"../input/aptos2019-blindness-detection/train_images/\"\ntest_dir = \"../input/aptos2019-blindness-detection/test_images/\"\nlabel = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")\nprint(len(label))\nlabel.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:15.452423Z","iopub.execute_input":"2021-06-07T03:28:15.452685Z","iopub.status.idle":"2021-06-07T03:28:15.481936Z","shell.execute_reply.started":"2021-06-07T03:28:15.452658Z","shell.execute_reply":"2021-06-07T03:28:15.481034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mping\nrows=3\ncols=5\nimg_path = train_dir\nfile_list = glob.glob(img_path + '*.png')\nplt.figure(figsize=(16,9))\n\nfor i in range(rows*cols):\n    plt.subplot(rows, cols, i + 1)\n    img = mping.imread(file_list[i])\n    plt.imshow(img)\n    plt.axis('off')\n    print(img.shape)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:15.483562Z","iopub.execute_input":"2021-06-07T03:28:15.483912Z","iopub.status.idle":"2021-06-07T03:28:25.965236Z","shell.execute_reply.started":"2021-06-07T03:28:15.483878Z","shell.execute_reply":"2021-06-07T03:28:25.964507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ImageData(Dataset):\n    def __init__(self, df, data_dir, transform):\n        super().__init__()\n        self.df = df\n        self.data_dir = data_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, index):\n        img_name = self.df.id_code[index] + '.png'\n        label = self.df.diagnosis[index]\n        img_path = os.path.join(self.data_dir, img_name)\n\n        image = mpimg.imread(img_path)\n        image = (image + 1) * 127.5\n        image = image.astype(np.uint8)\n\n        image = self.transform(image)\n        return image, label","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:25.966527Z","iopub.execute_input":"2021-06-07T03:28:25.966901Z","iopub.status.idle":"2021-06-07T03:28:25.975577Z","shell.execute_reply.started":"2021-06-07T03:28:25.966860Z","shell.execute_reply":"2021-06-07T03:28:25.973390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_transform = transforms.Compose([transforms.ToPILImage(mode='RGB'),\n                                  transforms.Resize(265),\n                                  transforms.CenterCrop(224),\n                                  transforms.ToTensor()])\ntrain_data = ImageData(df = label, data_dir = train_dir, transform = data_transform)\ntrain_loader = DataLoader(dataset = train_data, batch_size=32, drop_last=True)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:25.976837Z","iopub.execute_input":"2021-06-07T03:28:25.977196Z","iopub.status.idle":"2021-06-07T03:28:25.987853Z","shell.execute_reply.started":"2021-06-07T03:28:25.977161Z","shell.execute_reply":"2021-06-07T03:28:25.987002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.resnet50()\nmodel.load_state_dict(torch.load(\"../input/resnet50/resnet50.pth\"))","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:25.989140Z","iopub.execute_input":"2021-06-07T03:28:25.989659Z","iopub.status.idle":"2021-06-07T03:28:29.153306Z","shell.execute_reply.started":"2021-06-07T03:28:25.989625Z","shell.execute_reply":"2021-06-07T03:28:29.152250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for param in model.parameters():\n    param.requires_grad = False","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:29.158405Z","iopub.execute_input":"2021-06-07T03:28:29.158738Z","iopub.status.idle":"2021-06-07T03:28:29.168840Z","shell.execute_reply.started":"2021-06-07T03:28:29.158705Z","shell.execute_reply":"2021-06-07T03:28:29.168005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(model)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:29.173725Z","iopub.execute_input":"2021-06-07T03:28:29.175981Z","iopub.status.idle":"2021-06-07T03:28:29.187136Z","shell.execute_reply.started":"2021-06-07T03:28:29.175943Z","shell.execute_reply":"2021-06-07T03:28:29.186038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fc = nn.Linear(2048, 5)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:29.191091Z","iopub.execute_input":"2021-06-07T03:28:29.193067Z","iopub.status.idle":"2021-06-07T03:28:29.198853Z","shell.execute_reply.started":"2021-06-07T03:28:29.193032Z","shell.execute_reply":"2021-06-07T03:28:29.197919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(model)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:29.203239Z","iopub.execute_input":"2021-06-07T03:28:29.205222Z","iopub.status.idle":"2021-06-07T03:28:29.214290Z","shell.execute_reply.started":"2021-06-07T03:28:29.205187Z","shell.execute_reply":"2021-06-07T03:28:29.213182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(\"Using device:\", device)\nmodel = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:29.216713Z","iopub.execute_input":"2021-06-07T03:28:29.217043Z","iopub.status.idle":"2021-06-07T03:28:33.252311Z","shell.execute_reply.started":"2021-06-07T03:28:29.217012Z","shell.execute_reply":"2021-06-07T03:28:33.251443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = optim.Adam(model.parameters(), lr=0.001)\nloss_func = nn.CrossEntropyLoss()","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:33.255369Z","iopub.execute_input":"2021-06-07T03:28:33.255635Z","iopub.status.idle":"2021-06-07T03:28:33.262021Z","shell.execute_reply.started":"2021-06-07T03:28:33.255609Z","shell.execute_reply":"2021-06-07T03:28:33.261246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# %%time\n# # Train model\n# loss_log=[]\n# for epoch in range(25):\n#     model.train()\n#     for ii, (data, target) in enumerate(train_loader):\n#         data, target = data.cuda(), target.cuda()\n#         optimizer.zero_grad()\n#         output = model(data)\n#         loss = loss_func(output, target)\n#         loss.backward()\n#         optimizer.step()\n#         if ii % 1000 == 0:\n#             loss_log.append(loss.item())\n#     print('Epoch: {} - Loss: {:.6f}'.format(epoch + 1, loss.item()))\n\n# PATH = \"./results/resnet50_0606.pth\"\n# torch.save(model.state_dict(), PATH)\n# print(\"Finishing training~~~~\")","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:33.263244Z","iopub.execute_input":"2021-06-07T03:28:33.263772Z","iopub.status.idle":"2021-06-07T03:28:33.271500Z","shell.execute_reply.started":"2021-06-07T03:28:33.263733Z","shell.execute_reply":"2021-06-07T03:28:33.270669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit = pd.read_csv('../input/aptos2019-blindness-detection/sample_submission.csv')\ntest_data = ImageData(df = submit, data_dir = test_dir, transform = data_transform)\ntest_loader = DataLoader(dataset = test_data, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:33.274309Z","iopub.execute_input":"2021-06-07T03:28:33.274613Z","iopub.status.idle":"2021-06-07T03:28:33.291827Z","shell.execute_reply.started":"2021-06-07T03:28:33.274589Z","shell.execute_reply":"2021-06-07T03:28:33.290973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = model\nmodel.load_state_dict(torch.load(\"../input/results/resnet50_0606.pth\"))\nmodel = model.to(device)\n# Prediction\npredict = []\nmodel.eval()\nfor i, (data, _) in enumerate(test_loader):\n    data = data.cuda()\n    output = model(data)\n    output = output.cpu().detach().numpy()\n    predict.append(output[0])","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:28:33.292756Z","iopub.execute_input":"2021-06-07T03:28:33.293012Z","iopub.status.idle":"2021-06-07T03:31:36.840437Z","shell.execute_reply.started":"2021-06-07T03:28:33.292990Z","shell.execute_reply":"2021-06-07T03:31:36.839580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit['diagnosis'] = np.argmax(predict, axis=1)\nsubmit.head(10)\n\nsubmit.to_csv(\"./submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-07T03:31:36.841603Z","iopub.execute_input":"2021-06-07T03:31:36.841915Z","iopub.status.idle":"2021-06-07T03:31:37.066531Z","shell.execute_reply.started":"2021-06-07T03:31:36.841882Z","shell.execute_reply":"2021-06-07T03:31:37.065779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}