{"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\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\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#This is the directory for all the test images.\ntest_path = f'/kaggle/input/cassava-leaf-disease-classification/test_images/'\n\n#This is the sample submission so we can use the same headers to save time.\ntest_df = pd.read_csv(\"../input/cassava-leaf-disease-classification/sample_submission.csv\")\n\ntest_data = pd.DataFrame()\ntest_data['image_id'] = list(os.listdir('../input/cassava-leaf-disease-classification/test_images/'))\ntest_data[\"label\"] = \"NA\"\ndisplay(test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torchvision\nfrom torchvision import transforms\n\n#The bare minimum transform we need for our network to work is to transform the images - which are currently stored in numpy arrays - into tensors.\ndef test_transform():\n    transforms.Compose([\n        transforms.ToTensor(),\n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nimport cv2\n\n# All classes for NN will need an __init__ function, a __len__ function, and a __getitem__ function.\nclass DataCreation(Dataset):\n    #__init__ creates the structure for our class\n    def __init__(self, data, transforms = test_transform()):\n        super().__init__()\n\n        self.transform = transforms\n        self.image_id = data[\"image_id\"]\n        self.label = data[\"label\"]\n\n    def __len__(self):\n        return len(self.image_id)\n    \n    #__getitem__ does most of the work we care about. In this case in reads in the row id using self, then using that row id it finds the...\n    #...corresponding label, and the image - using the previously discussed file_path and appends the image_id.\n    def __getitem__(self,idx : int):\n        image_id = self.image_id[idx]\n        label = self.label[idx]\n        image = cv2.imread(test_path + image_id, cv2.IMREAD_COLOR)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n        image /= 255.0\n        \n        #This is almost always the case where we have a transform set, but to avoid future errors we will include it in an if statement.\n        if self.transform:\n            #First we send our batch of images to the transform function, which outputs it as a tensor.\n            augmented = self.transform(image=image)\n            image = augmented[\"image\"]\n\n        #Return 2 outputs. Note, when you assign this function to 2 variables, it will assign them in this order.\n        return label, image\n\n\n#Call the DataCreation function on our training data, making sure to pass each item through the transformer.\ntest_dataset = DataCreation(test_data, test_transform())\n#Batch multiple items from the DataCreation function ready for passing to the network.\ntest_loader = DataLoader(test_dataset, batch_size = 4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\n#If GPU is available, use it, otherwise use CPU.\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nPATH = '../input/diseasemodel/Diseasemodel.pth'\nmodel = torch.load(PATH)\nmodel.eval()\nprint(model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\n\nfor image in test_loader:\n    image = image[1].to(device)\n    image = image.permute(0,3,2,1)\n    y_hat = model(image)\n    y_hat = np.array(torch.argmax(y_hat, dim= 1).cpu())\n    label = y_hat[0]\n    predictions.append(label)\n    \ntest_data[\"label\"] = predictions\ndisplay(test_data)\ntest_data.to_csv(\"submission.csv\", index = False)\n","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}