{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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":"from fastai import *\nfrom fastai.vision import *\nimport imageio","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path('../input/Kannada-MNIST')\ntrain = pd.read_csv('../input/Kannada-MNIST/train.csv')\ntest  =pd.read_csv('../input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Preprocessing**"},{"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.01,random_state=7,stratify=data_y)","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)","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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Making the Learner**"},{"metadata":{"trusted":true},"cell_type":"code","source":"tfms = get_transforms(do_flip=False )\n\ndata = (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":"data.show_batch(3,figsize=(6,6))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir -p /tmp/.cache/torch/checkpoints\n!cp /kaggle/input/fastai-pretrained-models/resnet50-19c8e357.pth /tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth\n\nlearn = cnn_learner(data, models.resnet50, metrics=[error_rate, accuracy], model_dir = Path('../kaggle/working'),path = Path(\".\"))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Fitting the model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(4)","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 = slice(2e-05)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(5,lr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-2')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(10,lr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-3')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.load('stage-3')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Getting the Predictions**"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_csv = pd.read_csv('../input/Kannada-MNIST/test.csv')\ntest_csv.drop('id',axis = 'columns',inplace = True)\nsub_df = pd.DataFrame(columns=['id','label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = np.array(test_csv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_img(data):\n    t1 = data.reshape(28,28)/255\n    t1 = np.stack([t1]*3,axis=0)\n    img = Image(FloatTensor(t1))\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastprogress import progress_bar","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mb=progress_bar(range(test_data.shape[0]))\nfor i in mb:\n    timg=test_data[i]\n    img = get_img(timg)\n    sub_df.loc[i]=[i+1,int(learn.predict(img)[1])]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decr(ido):\n    return ido-1\nsub_df['id'] = sub_df['id'].map(decr)\nsub_df.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}