{"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 5GB 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":"\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.vision import *\nfrom fastai.tabular import *\nimport imageio","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/Kannada-MNIST/train.csv')\ntrain.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tfms = get_transforms(flip_vert=False, max_lighting=0.1, max_zoom=1.05, max_warp=0.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path='../input/Kannada-MNIST'\ntest = pd.read_csv('../input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def to_img_shape(data_X, data_y=[]):\n    data_X = np.array(data_X).reshape(-1,28,28)\n    data_X = np.stack((data_X,)*3, axis=-1)\n    data_y = np.array(data_y)\n    return data_X,data_y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_X, data_y = train.loc[:,'pixel0':'pixel783'], train['label']\n\nfrom sklearn.model_selection import train_test_split\n\ntrain_X, val_X, train_y, val_y = train_test_split(data_X, data_y, test_size=0.1,random_state=42,stratify=data_y)\n\ntest_X = test.loc[:,'pixel0':'pixel783']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_X,train_y = to_img_shape(train_X, train_y)\nval_X,val_y = to_img_shape(val_X,val_y)\ntest_X, _ = to_img_shape(test_X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def save_imgs(path:Path, data, labels):\n    path.mkdir(parents=True,exist_ok=True)\n    for label in np.unique(labels):\n        (path/str(label)).mkdir(parents=True,exist_ok=True)\n    for i in range(len(data)):\n        if(len(labels)!=0):\n            imageio.imsave( str( path/str(labels[i])/(str(i)+'.jpg') ), data[i] )\n        else:\n            imageio.imsave( str( path/(str(i)+'.jpg') ), data[i] )\n\nsave_imgs(Path('/data/train'),train_X,train_y)\nsave_imgs(Path('/data/valid'),val_X,val_y)\nsave_imgs(Path('/data/test'),test_X, [])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#np.random.seed(42)\nsrc = (ImageList.from_folder('/data/')\n       .split_by_folder()\n       .label_from_folder()\n       .add_test_folder()          \n       .transform(tfms, size=64)   \n       .databunch())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"src.show_batch(rows=3, figsize=(12,9))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"arch = models.resnet50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc_02 = partial(accuracy_thresh, thresh=0.2)\nf_score = partial(fbeta, thresh=0.2)\nlearn = cnn_learner(src, arch, metrics=accuracy)","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.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr=1e-02\nlearn.fit_one_cycle(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nlearn152 = cnn_learner(src, models.resnet152, metrics=accuracy)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn152.lr_find()\nlearn152.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = 1e-2\nlearn152.fit_one_cycle(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn152.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds50, _ = learn.get_preds(DatasetType.Test)\n\npreds152, _ = learn152.get_preds(DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ny = torch.argmax(preds50, dim=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = 0.50*preds50  + 0.50*preds152\n\ny = torch.argmax(preds, dim=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num = len(learn.data.test_ds)\nindexes = {}\n\nfor i in range(num):\n    filename = str(learn.data.test_ds.items[i]).split('/')[-1]\n    filename = filename[:-4] # get rid of .jpg\n    indexes[(int)(filename)] = i","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({ 'id': range(0, num),'label': [y[indexes[x]].item() for x in range(0, num)] })\nsubmission.to_csv(path_or_buf =\"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}