{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-02-21T05:40:38.287338Z","iopub.execute_input":"2022-02-21T05:40:38.288146Z","iopub.status.idle":"2022-02-21T05:40:38.296138Z","shell.execute_reply.started":"2022-02-21T05:40:38.288103Z","shell.execute_reply":"2022-02-21T05:40:38.295534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","metadata":{"execution":{"iopub.status.busy":"2022-02-21T05:40:38.297457Z","iopub.execute_input":"2022-02-21T05:40:38.29787Z","iopub.status.idle":"2022-02-21T05:40:38.306643Z","shell.execute_reply.started":"2022-02-21T05:40:38.297838Z","shell.execute_reply":"2022-02-21T05:40:38.30591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler","metadata":{"execution":{"iopub.status.busy":"2022-02-21T05:40:38.30773Z","iopub.execute_input":"2022-02-21T05:40:38.307937Z","iopub.status.idle":"2022-02-21T05:40:38.31675Z","shell.execute_reply.started":"2022-02-21T05:40:38.307912Z","shell.execute_reply":"2022-02-21T05:40:38.315911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_file = \"/kaggle/input/digit-recognizer/train.csv\"\ntest_file = \"../input/test.csv\"\noutput_file = \"submission.csv\"","metadata":{"execution":{"iopub.status.busy":"2022-02-21T05:40:38.317756Z","iopub.execute_input":"2022-02-21T05:40:38.318541Z","iopub.status.idle":"2022-02-21T05:40:38.325792Z","shell.execute_reply.started":"2022-02-21T05:40:38.318495Z","shell.execute_reply":"2022-02-21T05:40:38.325225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"raw_data = np.loadtxt(train_file, skiprows=1, dtype='int', delimiter=',')\nx_train, x_val, y_train, y_val = train_test_split(\n    raw_data[:,1:], raw_data[:,0], test_size=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-02-21T05:40:38.327474Z","iopub.execute_input":"2022-02-21T05:40:38.327873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(2, 1, figsize=(12,6))\nax[0].plot(x_train[0])\nax[0].set_title('784x1 data')\nax[1].imshow(x_train[0].reshape(28,28), cmap='gray')\nax[1].set_title('28x28 data')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.reshape(-1, 28, 28, 1)\nx_val = x_val.reshape(-1, 28, 28, 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.astype(\"float32\")/255.\nx_val = x_val.astype(\"float32\")/255.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\n#example:\nprint(y_train[0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(filters = 128, kernel_size = (3, 3), activation='tanh', input_shape = (28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2,2)))\nmodel.add(Conv2D(filters = 128, kernel_size = (3, 3), activation='tanh', input_shape = (28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(zoom_range = 0.1,\n                            height_shift_range = 0.1,\n                            width_shift_range = 0.1,\n                            rotation_range = 10)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', metrics=[\"accuracy\"])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.9 ** x)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = model.fit_generator(datagen.flow(x_train, y_train, batch_size=16),\n                           steps_per_epoch=500,\n                           epochs=25, #Increase this when not on Kaggle kernel\n                           verbose=2,  #1 for ETA, 0 for silent\n                           validation_data=(x_val[:400,:], y_val[:400,:]), #For speed\n                           callbacks=[annealer])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_loss, final_acc = model.evaluate(x_val, y_val, verbose=0)\nprint(\"Final loss: {0:.4f}, final accuracy: {1:.4f}\".format(final_loss, final_acc))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(hist.history['loss'], color='b')\nplt.plot(hist.history['val_loss'], color='r')\nplt.show()\nplt.plot(hist.history['accuracy'], color='b')\nplt.plot(hist.history['val_accuracy'], color='r')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_hat = model.predict(x_val)\ny_pred = np.argmax(y_hat, axis=1)\ny_true = np.argmax(y_val, axis=1)\ncm = confusion_matrix(y_true, y_pred)\nprint(cm)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mnist_testset = np.loadtxt(test_file, skiprows=1, dtype='int', delimiter=',')\nx_test = mnist_testset.astype(\"float32\")\nx_test = x_test.reshape(-1, 28, 28, 1)/255.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_hat = model.predict(x_test, batch_size=64)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = np.argmax(y_hat,axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(output_file, 'w') as f :\n    f.write('ImageId,Label\\n')\n    for i in range(len(y_pred)) :\n        f.write(\"\".join([str(i+1),',',str(y_pred[i]),'\\n']))","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}