{"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%matplotlib inline\n%reload_ext autoreload\n%autoreload 2\n\nfrom fastai.vision.all import *\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\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":"import pandas as pd\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SEED=47\ndef seed_torch(seed=47):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\nseed_torch(seed=SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_to_category_num = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"category_num_to_disease = pd.read_json('/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json', typ=\"series\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_to_category_num.label.value_counts(normalize=True)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_PATH = \"/kaggle/input/cassava-leaf-disease-classification/train_images\"\nTEST_PATH = \"/kaggle/input/cassava-leaf-disease-classification/test_images\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_category_num_from_path(path):\n    img_name = str(path).split('/')[-1]\n    category = int(image_to_category_num[image_to_category_num.image_id == img_name].label)\n    return category","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_image_files_debugging(path):\n    \"\"\"Helper function for faster iteration\"\"\"\n    return get_image_files(path)[:10000]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diseases = DataBlock(blocks=(ImageBlock, CategoryBlock), \n                     get_items=get_image_files,\n                     splitter=RandomSplitter(seed=SEED),\n                     get_y=get_category_num_from_path,\n                     item_tfms=Resize(512),\n                     batch_tfms=[*aug_transforms(), Normalize.from_stats(*imagenet_stats)])\ndls = diseases.dataloaders(TRAIN_PATH, bs=12)                    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dls.show_batch(max_n = 9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install efficientnet_pytorch --quiet\nfrom efficientnet_pytorch import EfficientNet\nmodel = EfficientNet.from_pretrained('efficientnet-b4', num_classes=5)\nmodel.train()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weights = [20, 10, 10, 1.6, 10]\nclass_weights = torch.FloatTensor(weights).cuda()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mixup = MixUp()\nrocauc = RocAuc()\nlearn = Learner(dls, \n                model,\n                metrics=[accuracy, rocauc],\n                loss_func=CrossEntropyLossFlat(weight=class_weights),\n                cbs=[ShowGraphCallback(), \n                     EarlyStoppingCallback(monitor='accuracy', patience=5),\n                     mixup,\n                     ReduceLROnPlateau(monitor=\"accuracy\", patience=3)]\n                )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.freeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.lr_find()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.unfreeze()\nlearn.lr_find()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fine_tune(20, 1e-3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.export(\"B4_fp32_full_weightedloss_mixup_rlrp.pkl\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Models tried:\n1. resnet34: validation loss starts diverging after a couple of epochs. best val_accuracy 0.82, best train_loss 0.34. Train loss keeps going down while valid loss and accuracy stop improving after a while. Can try with mixed precision to see if that helps as regularization.\n1. resnet34 fp16 from_pretrained: using just 5000 images for train/valid and 256 batchsize, trains way faster (1:17 minutes per epoch). best val_acc = 0.82 ... Again seems to hit some limit (12 epochs)\n1. resnet50, fp16, pretrained: 5000 imgs, 0.83 valid accuracy\n1. VGG16, pretrained, 224, fp16: goes up to 0.8575 val accuracy (20 epochs). \n1. VGG16, pretrained, 448, fp16, half examples: Starts learning quickly. Best val acc = 0.8775 \n1. VGG16, pretrained, 448, fp16, full examples: Starts learning quickly. Best val acc = ~0.87, no noticeable improvement....\n1. VGG19, pretrained, 448, fp16, half examples, 10epochs: best acc=0.8835\n1. ResNet101, pretrained, 448, fp16, halfexamples, 10epochs: best acc= 0.878\n"}],"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}