{"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":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv(\"/kaggle/input/Kannada-MNIST/sample_submission.csv\")\n\nsample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = train.iloc[:, 1:].values.reshape(train.shape[0],28, 28).astype( 'float32' )/255.0\n# images=np.stack((images,)*3, axis=-1).astype('float32')\nimages=images.reshape(train.shape[0],28, 28,1)\n\nimages_test = test.iloc[:, 1:].values.reshape(test.shape[0],28, 28).astype( 'float32' )/255.0\n# images_test=np.stack((images_test,)*3, axis=-1).astype('float32')\nimages_test=images_test.reshape(test.shape[0],28, 28,1)\nlabel = train.iloc[:,0].astype('int').values\nids_test = test.iloc[:,0].values\nplt.imshow(images[0].reshape(28,28),cmap='gray')\nplt.title(label[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images.shape,images_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(images_test[0].reshape(28,28),cmap = 'gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nimages_train, images_validation,label_train,label_validation = train_test_split(images,label,test_size=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = train.iloc[:,0].unique()\nclasses","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\nlabel_train = to_categorical(label_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_validation = to_categorical(label_validation)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_train,label_validation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.python.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.layers import Dense,Conv2D, MaxPooling2D, Flatten,BatchNormalization,Dropout\nfrom tensorflow.keras.models import Sequential","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(28, 28, 1), padding='same', activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.4))\n\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(10, activation='sigmoid'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau,ModelCheckpoint\nearlystop = EarlyStopping(patience=10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\ncallbacks = [earlystop, learning_rate_reduction,ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam\nmodel.compile(\nloss=\"categorical_crossentropy\",\noptimizer=Adam(lr=0.001),\nmetrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(images_train,label_train, validation_data=(images_validation,label_validation),batch_size=64, epochs=50,callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_prediction = model.predict(images_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_labels = []\nfor i in range(len(test_prediction)):\n    test_labels.append(np.argmax(test_prediction[i]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(sample_submission)):\n    sample_submission.iloc[i,1]=test_labels[i]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.argmax(model.predict(images_test[2].reshape(1,28,28,1)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv(\"submission.csv\",index=False)","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}