{"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":"DATA_DIR=\"/kaggle/input/digit-recognizer/\"\n\ntrain=pd.read_csv(os.path.join(DATA_DIR,\"train.csv\"))\ntest=pd.read_csv(os.path.join(DATA_DIR, \"test.csv\"))\nsample=pd.read_csv(os.path.join(DATA_DIR, \"sample_submission.csv\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()\ntest.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_X, val_X, train_Y, val_Y=train_test_split(train.iloc[:,1:], train['label'].values, test_size=0.1, random_state=169)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_X=train_X.to_numpy().reshape((-1,28,28,1))\nval_X=val_X.to_numpy().reshape((-1,28,28,1))\ntest=test.to_numpy().reshape((-1,28,28,1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_rows=28\nnum_cols=28\nb_size = 378\nn_epoch = 10\nn_classes = 10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras_preprocessing.image import ImageDataGenerator\ntrain_datagen=ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255.,\n    width_shift_range=0.10,\n    height_shift_range=0.10\n)\n\ntrain_datagen.fit(train_X)\nval_X=val_X/255.\ntest=test/255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\n\nval_labels=val_Y\ntrain_Y=to_categorical(train_Y, num_classes=n_classes)\nval_Y=to_categorical(val_Y, num_classes=n_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Model, Sequential\nfrom keras.layers import Flatten, Dense, Dropout, Conv2D, MaxPool2D\n\nmodel=Sequential([\n    Conv2D(32,(3,3),activation=\"relu\",input_shape=(num_rows,num_cols,1)),\n    Conv2D(64,(3,3),activation=\"relu\"),\n    MaxPool2D((2,2)),\n    Conv2D(64,(3,3),activation=\"relu\"),\n    MaxPool2D((2,2)),\n    Flatten(),\n    Dense(128, activation=\"relu\"),\n    Dropout(0.25),\n    Dense(n_classes,activation=\"softmax\")])\n\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\",metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit_generator(\n            train_datagen.flow(train_X, train_Y,batch_size=b_size),\n            steps_per_epoch=(train_X.shape[0]//b_size)*1.1,\n            epochs=n_epoch,\n            validation_data=(val_X, val_Y),\n            verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"MNIST_first.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(val_X, val_Y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_predictions=model.predict(val_X)\ntest_predictions=model.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import classification_report\nprint(classification_report(val_labels, np.argmax(val_predictions,axis=1)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\npred=np.argmax(val_predictions, axis=1)\nwrong_indices=np.where(np.argmax(val_predictions,axis=1)!=val_labels)[0]\n\nfor i in range(11):\n    x=1\n    f, axarr=plt.subplots(1,4)\n    for i in wrong_indices[i*4:i*4+4]:\n        axarr[x-1].imshow(val_X[i].reshape(28,28),cmap=\"gray\")\n        axarr[x-1].set_title(\"Predicted: \"+str(pred[i])+\"\\nActual: \"+str(val_labels[i]))\n        x+=1\n    plt.show(block=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample['Label']=np.argmax(test_predictions,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample.to_csv(\"Submissions.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import load_model\n\nmodel=load_model(\"/kaggle/input/trained-models/MNIST_first.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","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}