{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# 2nd attempt at the MNIST challenge. Previously, I tried a WRN, which turned out to be much too complex \n# for the dataset and extremely overfit. This time, a simpler CNN will suffice.\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport keras\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/train.csv')\ndf.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.values.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = df.drop(['label'],1)\nx.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = df['label']\ny.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\nX = x.values.reshape(x.values.shape[0],28,28,1)\nY = to_categorical(y.values,10)\nprint(Y.shape)\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(X,Y,test_size=0.15)\n\nprint(x_train.shape,x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define model\nfrom keras import layers, models\n\nnetwork_input = layers.Input((28,28,1))\nconv1 = layers.Conv2D(16, kernel_size=(4,4))(network_input)\nb1 = layers.BatchNormalization()(conv1)\na1 = layers.Activation('relu')(b1)\nd1 = layers.Dropout(0.1)(a1)\nconv2 = layers.Conv2D(32, kernel_size=(4,4), strides = 2)(d1)\nb2 = layers.BatchNormalization()(conv2)\na2 = layers.Activation('relu')(b2)\nd2 = layers.Dropout(0.1)(a2)\nconv3 = layers.Conv2D(64, kernel_size=(4,4), strides = 2)(d2)\nb3 = layers.BatchNormalization()(conv3)\na3 = layers.Activation('relu')(b3)\ndrop = layers.Dropout(0.2)(a3)\nflat = layers.Flatten()(drop)\noutput = layers.Dense(10, activation='softmax')(flat)\n\nmodel = models.Model(network_input, output)\nmodel.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['acc'])\nmodel.summary()\n\nfrom keras.callbacks import *\ncallbacks = [\n    EarlyStopping(monitor='val_loss', patience=2, verbose=0),\n    ModelCheckpoint('mnist.h5', monitor='val_loss', save_best_only=True, verbose=0),\n]\nmodel.fit(x_train, y_train, batch_size=16, epochs=20, validation_data=(x_test,y_test),callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.load_model('mnist.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load test values and make predictions\npredict_x = pd.read_csv('/kaggle/input/test.csv')\npredict_x = predict_x.values.reshape(predict_x.values.shape[0],28,28,1)\nprint(predict_x.shape)\npredictions = np.argmax(model.predict(predict_x),axis=1)\nprint(predictions.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualize predictions\nimport random\nimport matplotlib.pyplot as plt\nchoice = random.randint(0,predict_x.shape[0])\nplt.imshow(predict_x[choice][:,:,0],cmap='gray')\nprint(\"Prediction: \",predictions[choice])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Encode our data into comma separated values for submission\ntext = [\"ImageId,Label\\n\"]\nfor index, prediction in enumerate(predictions):\n    string = str(index+1)+','+str(prediction)\n    if index != 27999: string += \"\\n\" # We do this to make sure there's not an empty row at the end.\n    text.append(string)\nwith open(\"submission.csv\",\"w+\") as writer:\n    writer.writelines(text)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Aaand we're done!"}],"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}