{"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 numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport cv2,math,os,glob\nr = plt.imread\ndef p(x):plt.imshow(x);plt.show()\nimport torch\nfrom collections import OrderedDict \nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader, random_split\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\ndef subplotter(img_list,ncols=6,figsize=14,names=None):\n    nrows= math.ceil(len(img_list)/ncols)\n    \n    plt.figure(figsize=(figsize,figsize))\n    for i,img in enumerate(img_list):\n        plt.subplot(nrows,ncols,i+1)\n        plt.imshow(img)\n        if names:plt.title(names[i])\n    plt.show()\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":{"trusted":true},"cell_type":"code","source":"os.getcwd()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir('../input/effb4initals')\nprint(glob.glob('*'))\nw=torch.load('effb4-snapmix-epoch25-val_acc0.92.ckpt')['state_dict']\nload = OrderedDict([( ('.').join(k.split('.')[1:]) ,v) for k, v in w.items()])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir('/kaggle/input/pytorch-image-models/pytorch-image-models-master/')\nimport timm # resnest50d\nmodel = timm.create_model('tf_efficientnet_b4_ns', pretrained=False,num_classes=5).cuda()\nmodel.load_state_dict(load)\nmodel.eval()\n'loaded'\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from albumentations import (\n    HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, \n    CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, \n    OpticalDistortion, GridDistortion, HueSaturationValue,\n    IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur,\n    IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, \n    RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout,\n    CoarseDropout, ShiftScaleRotate, CenterCrop, Resize\n)\nfrom albumentations.pytorch import ToTensorV2, ToTensor\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"input_size=380\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                                     std=[0.229, 0.224, 0.225])\n\n\n# val_augs=transforms.Compose([\n#             transforms.ToPILImage(),\n#             transforms.Resize((input_size,input_size)),\n#             transforms.ToTensor(),\n#             normalize ])\nval_augs = Compose([\n                        Resize(input_size, input_size),\n                          Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n                          ToTensorV2(),\n                          ])\n\nclass TestPlantLoader(Dataset):\n    def __init__(self, img_names, transform=None):\n        self.img_names=img_names\n        self.transform=transform\n        \n    def __len__(self):\n        return len(self.img_names)\n    def __getitem__(self, idx):\n        \n        img_name=self.img_names[idx]\n        image=r(img_name)\n        \n        if self.transform: image = self.transform(image=image)['image']\n        \n        sample = {'image':image,'img_name':img_name}\n        \n        return sample\n\nos.chdir('/kaggle/input/cassava-leaf-disease-classification/')\nimgs = glob.glob('test_images/*') \n\nbatch_size=1\ndataset = TestPlantLoader(imgs,val_augs) \ntest_dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=8)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls=[]\nfor i, batch in enumerate(test_dataloader):\n    x, name = batch['image'],batch['img_name']\n    logits = model(x.cuda())\n    preds = torch.argmax(logits, dim=1)\n    \n    ls.append([name[0].split('/')[-1],preds[0].item()])\n\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.DataFrame.from_records(ls, columns=['image_id', 'label'])\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir('/kaggle/working/')\nsub.to_csv(\"/kaggle/working/submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}