{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"## Importing the Libraries"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2DTranspose,Conv2D, MaxPooling2D\nfrom keras.layers import Dropout, Flatten\nfrom keras.utils import np_utils\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0d5eb9f6bdc7e2af123b4dd7f1a84220758c052c"},"cell_type":"markdown","source":"#### Cleaning the dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/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) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=2)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1afc56a5c69977f9d10128cbad204dbfe6a9a5dd"},"cell_type":"markdown","source":"#### Viewing the image"},{"metadata":{"trusted":true,"_uuid":"11cfb58d124d121da2b3e8a8579c581ef65a50c8"},"cell_type":"code","source":"g = plt.imshow(X_train[10][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"124e8d36582900a1e94ef857c8ad6c1590476ec7"},"cell_type":"markdown","source":"## Training the Model"},{"metadata":{"_uuid":"7d9bcee2fc3b79e3c9dfb5ef7a827592fc8ee7e2"},"cell_type":"markdown","source":"### Using Neural Networks"},{"metadata":{"trusted":true,"_uuid":"d4dfb69c4e0d9ebfb047b50b27dea7228cacfafc"},"cell_type":"code","source":"\ndef baseline_model():\n    model = Sequential()\n    model.add(Conv2D(32, 3, input_shape=(28, 28, 1), activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(64, 3, strides=1, padding='same', activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(128, 3, strides=1, padding='same', activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(128, 3, strides=1, padding='same', activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Flatten())\n    model.add(Dense(1024, \n                activation='relu'))\n    model.add(Dense(1024, \n                activation='relu'))\n    model.add(Dropout(0.5))\n    model.add(Dense(10, \n                activation='softmax'))\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = baseline_model()\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"65b5c1b758c26af07f6beb56fd09df65608d6156"},"cell_type":"code","source":"history = model.fit_generator(\n                            datagen.flow(X_train,Y_train, batch_size=50),\n                            epochs = 8, \n                            validation_data = (X_val,Y_val),\n                            verbose = 1,\n                            steps_per_epoch=X_train.shape[0] // 50\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f425381d835a00a92a6237bce5caf97e90a67bc1"},"cell_type":"code","source":"results = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6e797b92248d2304b4480deddb362fbf580330e7"},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f89071b99beffd9c5175607698b7d6be6a2056e2"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}