{"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 matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.datasets import mnist\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\n# Set seed\nnp.random.seed(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load data and target from MNIST data\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train[\"label\"]\nX_train = train.drop(labels = [\"label\"],axis = 1) \nprint(X_train.shape)\n\ndel train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Reshape training image data into features\nX_train = X_train.values.reshape(-1,28,28,1)\n# Reshape test image data into features\ntest = test.values.reshape(-1,28,28,1)\n# Rescale pixel intensity to between 0 and 1\nX_train = X_train / 255.0\ntest = test / 255.0\n# One-hot encode target\nY_train = to_categorical(Y_train, num_classes = 10)\nnumber_of_classes = Y_train.shape[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed = 42\n\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed) # Splitting our data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Start neural network\nnetwork = Sequential()\n# Add convolutional layer with 32 filters, a 3x3 window, and ReLU activation function\nnetwork.add(Conv2D(filters=32,\n            kernel_size=(3, 3),\n            input_shape=(28, 28, 1),\n            activation='relu'))\n# Add max pooling layer with a 2x2 window\nnetwork.add(MaxPooling2D(pool_size=(2, 2)))\n# Add dropout layer\nnetwork.add(Dropout(0.3))\n# Add convolutional layer with 64 filters, a 3x3 window, and ReLU activation function\nnetwork.add(Conv2D(filters=64,\n            kernel_size=(3, 3),\n            input_shape=(28, 28, 1),\n            activation='relu'))\n# Add max pooling layer with a 2x2 window\nnetwork.add(MaxPooling2D(pool_size=(2, 2)))\n# Add dropout layer\nnetwork.add(Dropout(0.3))\n# Add layer to flatten input\nnetwork.add(Flatten())\n# Add fully connected layer of 128 units with a ReLU activation function\nnetwork.add(Dense(128, activation=\"relu\"))\n# Add dropout layer\nnetwork.add(Dropout(0.3))\n# Add fully connected layer of 128 units with a ReLU activation function\nnetwork.add(Dense(128, activation=\"relu\"))\n# Add dropout layer\nnetwork.add(Dropout(0.3))\n# Add fully connected layer with a softmax activation function\nnetwork.add(Dense(number_of_classes, activation=\"softmax\"))\n# Compile neural network\nnetwork.compile(loss=\"categorical_crossentropy\", # Cross-entropy\n                optimizer=\"adam\", # Root Mean Square Propagation\n                metrics=[\"accuracy\"]) # Accuracy performance metric","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator( \n    rotation_range=10, \n    zoom_range = 0.1, \n    width_shift_range=0.1,  \n    height_shift_range=0.1,  \n    horizontal_flip=False,  \n    vertical_flip=False)  \n\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 10\nbatch_size = 128\n\nhistory = network.fit_generator(datagen.flow(X_train,Y_train, batch_size=128),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 1, steps_per_epoch=X_train.shape[0] // batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best')\n\nax[1].plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results=network.predict(test)\nresults = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"cnn_mnist.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":1}