{"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)\nimport matplotlib.pyplot as plt\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten, BatchNormalization\nfrom keras.models import Sequential\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import mean_absolute_error\nfrom scipy.stats import zscore\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":"y = np.array(pd.read_csv('../input/digit-recognizer/train.csv')).T[0]\nX = pd.read_csv('../input/digit-recognizer/train.csv').drop('label', axis=1)\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\n\nprint('target shape: ' + str(y.shape))\nprint('train shape:  ' + str(X.shape))\nprint('test shape:   ' + str(test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(y)\nprint(y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.array(X_train).reshape(33600, 28, 28, 1)\nX_test = np.array(X_test).reshape(8400, 28, 28, 1)\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\ntest = np.array(test).reshape(28000, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train/255.0\nX_test = X_test/255.0\ntest = test/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(loss='mean_absolute_error', metrics=['accuracy'], optimizer=Adam())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"idg = ImageDataGenerator()\ntrain_gen = idg.flow(X_train, y_train, batch_size=64)\ntest_gen = idg.flow(X_test, y_test, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"status = model.fit_generator(generator=train_gen, validation_data=test_gen, steps_per_epoch=1000, validation_steps=1000, epochs=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(status.history['loss'], c='blue', label='Train')\nplt.plot(status.history['val_loss'], c='red', label='Validation')\nplt.title('Loss after epochs')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\nplt.plot(status.history['accuracy'], c='blue', label='Train')\nplt.plot(status.history['val_accuracy'], c='red', label='Validation')\nplt.title('Accuracy after epochs')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ID = pd.read_csv(f'../input/digit-recognizer/sample_submission.csv')\nID = np.array(ID['ImageId'])\nlabel = model.predict_classes(test)\nsubmission = pd.DataFrame({'ImageId':ID, 'Label': label})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","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}