{"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)\nfrom keras.applications import resnet50\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras import layers\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\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":"train_df = pd.read_csv('../input/Kannada-MNIST/train.csv');\ntest_df = pd.read_csv('../input/Kannada-MNIST/test.csv');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def pad_with(vector, pad_width, iaxis, kwargs):\n    pad_value = kwargs.get('padder', 10)\n    vector[:pad_width[0]] = pad_value\n    vector[-pad_width[1]:] = pad_value","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def visualise_img(data):\n    img = np.pad(np.reshape(np.ravel(data),(28,28)),2,pad_with,padder=0)\n    img = img.astype('float32')/255\n    img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n    print(img.shape)\n    plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"visualise_img(train_df.iloc[4,1:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_validation, y_train, y_validation = train_test_split(train_df.iloc[:,1:], train_df.label, test_size=0.2, random_state=42, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def df_to_imageDataset(train):\n    train_data = [];\n    for row in train.itertuples():\n        img = np.pad(np.reshape(np.ravel(row[1:]),(28,28)),2,pad_with,padder=0)\n        img = img.astype('float32')/255\n        img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n        train_data.append(img);\n        \n    return np.array(train_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = df_to_imageDataset(x_train)\nX_val = df_to_imageDataset(x_validation)\ntrain_data.shape, X_val.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"resnet_conv = resnet50.ResNet50(weights=None, include_top=False, input_shape=(32,32,3));","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(resnet_conv)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(1024, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(10, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = OneHotEncoder().fit_transform(np.array(y_train).reshape(-1,1));\ny_val = OneHotEncoder().fit_transform(np.array(y_validation).reshape(-1,1));\npd.DataFrame(labels).head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(x=train_data,y=labels,shuffle=True, batch_size=128,epochs=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate(X_val, y_val, batch_size=16)\nscore","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = df_to_imageDataset(test_df.iloc[:,1:])\ntest_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model.predict(test_data)\nresult","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.argmax(result, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index = 324\nvisualise_img(test_df.iloc[index,1:])\nnp.argmax(result[index])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'id': test_df.id, 'label': np.argmax(result, axis=1)})\n\nmy_submission.to_csv('sample_submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test2_df = pd.read_csv('../input/Kannada-MNIST/Dig-MNIST.csv');\ntest2_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test2_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test2_data = df_to_imageDataset(test2_df.iloc[:,1:])\ntest2_data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = np.argmax(model.predict(test2_data), axis=1)\nresult","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import accuracy_score\nprint('Accuracy = ',accuracy_score(test2_df.label, result, normalize=False)/test2_df.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index = 232\nvisualise_img(test2_df.iloc[index,1:]);\nresult[index]","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":1}