{"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 numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D,MaxPool2D, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_file = \"../input/digit-recognizer/train.csv\"\ntest_file = \"../input/digit-recognizer/test.csv\"\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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(raw_data[:, 1:], raw_data[:,0], test_size=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = x_train.reshape(-1, 28, 28, 1)\nx_val = x_val.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = x_train.astype(\"float32\")/255\nx_val = x_val.astype(\"float32\")/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\ny_train[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=16, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(zoom_range=0.1,height_shift_range=0.1,width_shift_range=0.1,rotation_range=10)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer = Adam(lr=1e-4), metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.9 ** x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model.fit_generator(datagen.flow(x_train, y_train, batch_size=16),steps_per_epoch=500,epochs=20,verbose=2,validation_data=(x_val[:400,:], y_val[:400,:]),callbacks=[annealer])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_hat = model.predict(x_test, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = np.argmax(y_hat, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"output_file = \"submission.csv\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"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}