{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import shutil\nimport cv2\nimport re\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.metrics import error_rate","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path('/kaggle/input/Kannada-MNIST')\ntrain = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\ntest  =pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\nsub = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')\ndig = pd.read_csv('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"outpath = '/kaggle/'\nos.listdir(outpath)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating the output folder for storing train and test images\n\nshutil.os.mkdir(outpath + \"output\")\nshutil.os.mkdir(outpath + \"output/train\")\nshutil.os.mkdir(outpath + \"output/test\")\nshutil.os.mkdir(outpath + \"output/model\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape); print(test.shape); print(dig.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.isna().sum().sum());print(test.isna().sum().sum());print(dig.isna().sum().sum())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train.groupby('label').describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Function to save the images to re-use in fastai\ndef save_images(outpath,df):\n    for index, row in df.iterrows():\n        pixels=np.asarray(row['pixel0':'pixel783'])\n        img=pixels.reshape((28,28))\n        pathname=os.path.join(outpath,'image_'+str(row['label'])+'_'+str(index)+'.jpg')\n        cv2.imwrite(pathname,img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"outpath = '/kaggle/output/train'\nsave_images(outpath,train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sample_image = open_image('/kaggle/output/train/image_5_39645.jpg')\n#sample_image.show(figsize=(4,4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_img =  Path(outpath)\nfnames = get_image_files(path_img)\nfnames[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pat = r'/image_(\\d+)_'\ndata = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transforms(), size=224, bs=bs, num_workers=4).normalize(imagenet_stats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=5, figsize=(15,8))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(data.classes)\nlen(data.classes),data.c","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir -p /tmp/.cache/torch/checkpoints\n!cp /kaggle/input/resnet34/resnet34.pth /tmp/.cache/torch/checkpoints/resnet34-333f7ec4.pth\n!cp /kaggle/input/resnet50/resnet50.pth /tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn1 = cnn_learner(data, models.resnet34, metrics=[error_rate, accuracy], model_dir = '/kaggle/output/model')\nlearn2 = cnn_learner(data, models.resnet50, metrics=[error_rate, accuracy], model_dir = '/kaggle/output/model')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn1.fit_one_cycle(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn1.save('stage11')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#interp = ClassificationInterpretation.from_learner(learn1)\n#interp.most_confused(min_val=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn1.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn1.lr_find()\n#learn1.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn1.fit_one_cycle(8, max_lr=slice(3e-6,3e-4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#interp = ClassificationInterpretation.from_learner(learn1)\n#interp.most_confused(min_val=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn1.save('stage21')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn1.fit_one_cycle(6,3e-5)\n#learn1.save('stage31')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn2.fit_one_cycle(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn2.save('stage12')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#interp = ClassificationInterpretation.from_learner(learn2)\n#interp.most_confused(min_val=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn2.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn2.lr_find()\n#learn2.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn2.fit_one_cycle(8, max_lr=slice(3e-6,3e-4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#interp = ClassificationInterpretation.from_learner(learn2)\n#interp.most_confused(min_val=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn2.save('stage22')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn2.fit_one_cycle(6,3e-5)\n#learn2.save('stage32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit = pd.DataFrame(columns=['id','label'])\nsubmit['id'] = test['id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for index, row in test.iterrows():\n    pixels=np.asarray(row['pixel0':'pixel783'])\n    arr=pixels.reshape((28,28))/255\n    arr = np.stack([arr]*3,axis=0)\n    img = Image(FloatTensor(arr))\n    submit.at[index, 'label'] = int((learn1.predict(img)[1] + learn2.predict(img)[1])/2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit.to_csv('submission.csv',index=False)","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":1}