{"cells":[{"metadata":{},"cell_type":"markdown","source":"### A Hello World example of Computer Vision"},{"metadata":{},"cell_type":"markdown","source":"#### Import all the required libraries (Keras)"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # numeric python\nimport pandas as pd # data management\nimport seaborn as sbn # data visualisation\nimport matplotlib.pyplot as pplt\n%matplotlib inline\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Dropout\nfrom keras.layers import Conv2D, MaxPool2D, Flatten\nfrom keras.regularizers import l2\nfrom keras.utils import np_utils","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Helper functions"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Print Data\n# int: pos  indicates the position of item in the array\ndef printData(item):\n    digit = item\n    pplt.imshow(digit [:,:,0],cmap=pplt.cm.binary)\n    pplt.show()\n    \n# Plots the Loss vs Accuracy Chart\n# obj: history \ndef plotChart(history):\n    history_dict = history.history\n    history_dict.keys()# look witch keys exist\n    loss_values = history_dict['loss']\n    acc_values = history_dict['accuracy']\n    epochs = range(1, len(loss_values)+1)\n    pplt.plot(epochs,loss_values,'r', label='training loss')\n    pplt.plot(epochs,acc_values,'g',label='accuracy')\n    pplt.title('loss and accuracy')\n    pplt.xlabel('epochs')\n    pplt.ylabel('loss vs. accuracy')\n    pplt.legend()\n    pplt.show\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"#### Read the MNIST Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv(\"../input/digit-recognizer/sample_submission.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Print the training data set"},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Label the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# seperate the first column as Output-Data\nYTrain = train[\"label\"] \n# cut the 'label' column from training-data\nXTrain = train.drop(labels = [\"label\"],axis = 1)  \ndel train\ng = sbn.countplot(YTrain) \nYTrain.value_counts()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Normalize and shape the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalisation to [0..1] instead of [0..255]\nXTrain = XTrain / 255.0 \ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# keras needs a shape (height,weight,channel)\n# whith channel=1=greyscale, =3=rgb\nXTrain = XTrain.values.reshape(-1,28,28,1) # -1 means all samples\nprint(XTrain.shape)\ntest = test.values.reshape(-1,28,28,1)\n# the lables as \"one-hot\"-coding \nYTrain = np_utils.to_categorical(YTrain, num_classes = 10)\nprint(YTrain)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Print some traning data using the helper function"},{"metadata":{"trusted":true},"cell_type":"code","source":"# like to see the first digit\nprintData(XTrain[0])\n# like to see the last digit\nprintData(XTrain[41999])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating a CNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"# trying the CNN-model\nCNN = Sequential()\n\n\nCNN.add(Conv2D(32, kernel_size=(3, 3),\n                 activation='relu',\n                 input_shape=(28,28,1)))\nCNN.add(Conv2D(64, (3, 3), activation='relu'))\nCNN.add(MaxPool2D(pool_size=(2, 2)))\nCNN.add(Dropout(0.25))\nCNN.add(Flatten())\nCNN.add(Dense(128, activation='relu'))\nCNN.add(Dropout(0.5))\nCNN.add(Dense(10, activation='softmax'))\n# Summary\nCNN.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Compiliation\nCNN.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fitting the model\nhistory=CNN.fit(XTrain,YTrain,epochs=5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Plot the loss/ accuracy chart"},{"metadata":{"trusted":true},"cell_type":"code","source":"plotChart(history)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Testing our model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# prediction\nresults = CNN.predict(test) \n# index with the maximum probability\nresults = np.argmax(results,axis = 1) \nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Print out test data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Print test data\nprintData(test[100])\nprint(\"Prediction result:\", results[100])\n\n\nprintData(test[220])\nprint(\"Prediction result:\", results[220])","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}