{"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\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Every thing i have learnt so far.\n\n( not everything LoL)\n\n\nPlease Comment the improvements because i am unable to push the accuracy further."},{"metadata":{},"cell_type":"markdown","source":"FInd the location above of package installed then move to working dir and then refresh the working dir and then download and updload the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install ../input/efficientnet-pytorch070py3noneanywhl/efficientnet_pytorch-0.7.0-py3-none-any.whl","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nimport torchvision\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, DataLoader\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport os\nfrom torch.optim import Adam\nfrom torch.optim import Adam\nfrom PIL import Image\nimport torch.nn as nn \nfrom skimage import io\nfrom torch.autograd import Variable\nfrom skimage.transform import rescale, resize, downscale_local_mean\nimport numpy as np\nfrom albumentations import (\n    HorizontalFlip, VerticalFlip,ToGray, ElasticTransform,IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,\n    Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,\n    IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop,\n    IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize\n)\nfrom albumentations.pytorch import ToTensorV2\n# from efficientnet_pytorch import EfficientNet\nfrom tqdm.notebook import  tqdm\nimport torchvision.models as models\nfrom sklearn import metrics","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_path = '../input/cassava-leaf-disease-classification/train_images/'\ntest_data_path = '../input/cassava-leaf-disease-classification/test_images/'\nsample_sub_path =  '../input/cassava-leaf-disease-classification/sample_submission.csv'\ndf = pd.read_csv(sample_sub_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class DatasetLoader(Dataset):\n    \"\"\"Face Landmarks dataset.\"\"\"\n\n    def __init__(self, csv_file, root_dir, transform=None,test=False):\n        \"\"\"\n        Args:\n            csv_file (string): Path to the csv file with annotations.\n            root_dir (string): Directory with all the images.\n            transform (callable, optional): Optional transform to be applied\n                on a sample.\n        \"\"\"\n        self.images_name_and_label = pd.read_csv(csv_file)\n        self.root_dir = root_dir\n        self.transform = transform\n\n    def __len__(self):\n        return self.images_name_and_label.shape[0]\n\n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n\n        img_name = os.path.join(self.root_dir,\n                                self.images_name_and_label.iloc[idx, 0])\n        image = Image.open(img_name).convert('RGB')\n#         image = resize(image,(150,150)).convert('RGB')\n        image = np.array(image)\n        \n        label = torch.tensor(self.images_name_and_label.iloc[idx, 1])\n        \n        if self.transform:\n            image = self.transform(image=image)\n\n        return (image,label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE = 512\ntransformer=Compose([\n    RandomResizedCrop(IMG_SIZE, IMG_SIZE),\n#     CenterCrop(height=10,width=10,p=0.3),\n    CoarseDropout(p=0.3),\n    HorizontalFlip(p=0.5),\n    VerticalFlip(p=0.5),\n    RandomRotate90(p=0.5),\n    Transpose(p=0.3),\n    GaussNoise(p=0.5),\n    RandomBrightnessContrast(p=0.5),\n    ToGray(p=0.1),\n    ElasticTransform(p=0.3),\n    GridDistortion(p=0.3),\n    ShiftScaleRotate(p=0.3),\n    HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n    RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),\n    CoarseDropout(p=0.5),\n    Cutout(p=0.5),\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(p=1.0)\n],p=1.0)\n\ntest_valid_tranformer=Compose([\n    RandomResizedCrop(IMG_SIZE, IMG_SIZE),\n    HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n    HorizontalFlip(p=0.5),\n    VerticalFlip(p=0.5),\n    HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5),\n    RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5),\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(p=1.0)\n],p=1.0)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"dataset = DatasetLoader(\n    csv_file='../input/cassava-leaf-disease-classification/train.csv',\n    root_dir=train_data_path,\n    transform=transformer\n    )\n\ntest_dataset = DatasetLoader(\n    csv_file='../input/cassava-leaf-disease-classification/sample_submission.csv',\n    root_dir=test_data_path,\n    transform=test_valid_tranformer\n    )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"`"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_loader = DataLoader(dataset=dataset,batch_size=1,shuffle=True)\n\ntest_loader = DataLoader(dataset=test_dataset,batch_size=1,shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_epochs=0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch.nn.functional as F\n\ndef linear_combination(x, y, epsilon):\n    return epsilon * x + (1 - epsilon) * y\n\n\ndef reduce_loss(loss, reduction='mean'):\n    return loss.mean() if reduction == 'mean' else loss.sum() if reduction == 'sum' else loss\n\n\nclass LabelSmoothingCrossEntropy(nn.Module):\n    def __init__(self, epsilon: float = 0.1, reduction='mean'):\n        super().__init__()\n        self.epsilon = epsilon\n        self.reduction = reduction\n\n    def forward(self, preds, target):\n        n = preds.size()[-1]\n        log_preds = F.log_softmax(preds, dim=-1)\n        loss = reduce_loss(-log_preds.sum(dim=-1), self.reduction)\n        nll = F.nll_loss(log_preds, target, reduction=self.reduction)\n        return linear_combination(loss / n, nll, self.epsilon)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class CassavaNet(nn.Module):\n    def __init__(self):\n        super().__init__()\n        backbone = models.resnet50()\n        n_features = backbone.fc.in_features\n        self.backbone = nn.Sequential(*backbone.children())[:-2]\n        self.classifier = nn.Linear(n_features, 5)\n        self.pool = nn.AdaptiveAvgPool2d((1, 1))\n        \n\n    def forward_features(self, x):\n        x = self.backbone(x)\n        return x\n\n    def forward(self, x):\n        feats = self.backbone(x)\n        x = self.pool(feats).view(x.size(0), -1)\n        x = self.classifier(x)\n        return x, feats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = CassavaNet()\nmodel.load_state_dict(torch.load('../input/res50-img-cutmix-89/2cosine7cut_mix_noaug_resnet-50_512_420_300_512_1.pth'))\n\nmodel.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Optmizer and loss function\noptimizer=Adam(model.parameters(),lr=1e-7,weight_decay=0.001)\nloss_function=LabelSmoothingCrossEntropy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_accuracy=0.0\n\nfor epoch in range(num_epochs):\n    model.train()\n    train_accuracy=0.0\n    train_loss=0.0\n    \n    tk = tqdm(train_loader, total=len(train_loader), position=0, leave=True)\n    all_prediction = []\n    all_label = []\n    \n    for i,(image,label) in tqdm(enumerate(tk)):\n        images= image['image'].to(device)\n        images= images.to(device)\n        labels= label.to(device)\n            \n        optimizer.zero_grad()\n        \n        outputs,_=model(images.float())\n        \n        loss=loss_function(outputs,labels)\n        loss.backward()\n        optimizer.step()\n        \n        \n        train_loss+= loss.cpu().data*images.size(0)\n        _,prediction=torch.max(outputs.data,1)\n            \n        all_prediction.extend(prediction.data.cpu().data.numpy())\n        all_label.extend(labels.data.cpu().data.numpy())\n        \n        train_accuracy+=int(torch.sum(prediction==labels.data))\n        \n    train_accuracy=train_accuracy/len(train_loader)\n    train_loss=train_loss/len(train_loader)\n        \n    print('Epoch: '+str(epoch)+' Train Loss: '+str(train_loss)+' Train Accuracy: '+str(train_accuracy) + \"acc \",str(metrics.accuracy_score(all_prediction,all_label)))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.eval()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob\ntest_files = glob.glob(\"/kaggle/input/cassava-leaf-disease-classification/test_images/*\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = pd.DataFrame()\nimageIds = []\nlabels = []\ntest_pred = []\nmodel.eval()\ntk2 = tqdm(test_loader, total=len(test_loader), position=0, leave=True)\n\nwith torch.no_grad():\n\n    for i, data in enumerate(tk2):\n        image, _ = data\n        image = image['image']\n        image = image.to(device)\n\n        pred,_ = model(image.float())\n        pred = pred.argmax(1).cpu().detach().numpy().astype('int')\n\n        test_pred.extend(pred)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['label'] = test_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I have read many of other notebooks and what they \nsuggest like cutmix or labelsmoothing \ni did but i am not able to achieve accuracy they have achived \n### any suggesetions for me ?"},{"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}