{"cells":[{"metadata":{"_execution_state":"idle","_uuid":"72334cb006d02a4bcfc2a2fe622524eba824c6f8","_cell_guid":"f67b9393-8ea1-4e23-b856-2ce149cfe421","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\nnp.random.seed(2)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n\nsns.set(style='white', context='notebook', palette='deep')","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"86061d98eccaa02efe0dab0fa3884e71fcf4c310","_cell_guid":"6d2fb3e6-ab71-4974-b5a2-4af1ebdb99f4"},"cell_type":"markdown","source":"# Als erstes lesen wir uns die Daten ein."},{"metadata":{"_execution_state":"idle","_uuid":"84bbd5ab8d7895bd430d5ecfe2f7ddf77baa7b74","_cell_guid":"5e51d00e-62fd-4141-bf73-50ac4f2da7d0","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":{},"cell_type":"markdown","source":"# Jetzt splitten wir unsere Daten in X und Y-Werte"},{"metadata":{"_execution_state":"idle","_uuid":"1213b979d5ed3e0d13824d17d694c79d2ece92fa","_cell_guid":"86570a36-5c20-460a-9dfd-2070548532a7","trusted":true},"cell_type":"code","source":"Y_train = train[\"label\"]\n\n# Drop 'label' column\nX_train = train.drop(labels = [\"label\"],axis = 1) \n\ndel train ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2954681f25f0dcbe986e6914396cdbce61db591f","_cell_guid":"6812040d-80ad-43d2-a571-275f4f20067b"},"cell_type":"markdown","source":"# Wir normalisieren jetzt unseren Input"},{"metadata":{"_uuid":"0ecf4b52510ab7957d0d4eb646c0aa1ba5986273","_cell_guid":"159d5854-437a-4d0f-bc1e-fc3f7e43d178"},"cell_type":"markdown","source":"bedeutet Werte von 0-1 statt 0-255"},{"metadata":{"_execution_state":"idle","_uuid":"b5d4f8fcf2a967e2c7d57daedf95aa8c5ab7f8cb","_cell_guid":"cdc4340b-6e24-4e12-be99-ac806098ff17","collapsed":true,"trusted":false},"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a66741bf1ac597094f3a3166877008feef27c519","_cell_guid":"7413df94-bcb9-4f75-b174-c127d4445766"},"cell_type":"markdown","source":"Wir reshapen jetzt unseren Input zu einem Vektor. Wir haben jetzt statt 28x28 Bilder einen Vektor mit 784 Datenpunkten "},{"metadata":{"_execution_state":"idle","_uuid":"f0a6ad80dab8e0f2c2e46165ccd9cd82dd162bc3","_cell_guid":"34b6a5f7-8fd2-4387-8ef4-c9dc19584fed","collapsed":true,"trusted":false},"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":{"_uuid":"39b7a31e843bac6b705461bcce89da216b91799e","_cell_guid":"bdb422e2-bdec-444f-97a5-283a1e54bf2c"},"cell_type":"markdown","source":"Jetzt Formen wir unsere Y Label von 0-9 zu Arrays um, die an dem Index der dazugehörigen Zahl eine 1 haben\n\nBsp. 3:\n[0,0,0,1,0,0,0,0,0,0]"},{"metadata":{"_execution_state":"idle","_uuid":"cabefd1478d5c1bdfe57fd6a34395340916a854c","_cell_guid":"4b7f3e78-44dc-4561-b1f0-9429ee024cf4","collapsed":true,"trusted":false},"cell_type":"code","source":"# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\nY_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"6e51c925c6e0f1b936679c9649fef345c853555f","_cell_guid":"3a698301-9759-4279-ae48-fd980f89ea53","collapsed":true,"trusted":false},"cell_type":"code","source":"# Set the random seed\nrandom_seed = 2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Wir teilen jetzt unsere Trainingsdaten in Trainings- und Validationsdaten"},{"metadata":{"_execution_state":"idle","_uuid":"b779ac76d8317647db92d5a88b4098d212d72884","_cell_guid":"dcd25ebb-d845-4d32-9867-082e352b1396","collapsed":true,"trusted":false},"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=random_seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Jetzt kommen wir zum CNN\n# Wir nutzen 4 Convolutionallayer, ein Hiddenlayer (256) und einen Outputlayer mit 10 Neuronen\n# Außerdem nutzen wir neber Pooling und Flattening auch Dropout"},{"metadata":{"_execution_state":"idle","_uuid":"f7991ef6871a26f9fa57acdcd460a69bab53e804","_cell_guid":"1e0f3f88-2ad7-459e-8e02-aecc5f3511ae","collapsed":true,"trusted":false},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"b4c0288622227a3cd05479aa765e324dbb852f34","_cell_guid":"0bd89b79-1a74-40da-af9a-7a76a8b96ff2","collapsed":true,"trusted":false},"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer = 'adam' , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f24df64b223e0177c94025b6767ab19b722c5386","_cell_guid":"241a0f4f-13f5-4b13-be1e-4e3e4a714c06"},"cell_type":"markdown","source":"# Data augmentation "},{"metadata":{"_execution_state":"idle","_uuid":"21d6192c87d92d497c797656474bccd9cefc5647","_cell_guid":"b342befe-1a6f-44bf-8dab-28033a729122","collapsed":true,"trusted":false},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  \n        samplewise_center=False,\n        featurewise_std_normalization=False,\n        samplewise_std_normalization=False,\n        zca_whitening=False,\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\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Jetzt lassen wir unser Modell auf den Trainingsdaten lernen"},{"metadata":{"_execution_state":"idle","_uuid":"cf36b3d029f95b553be02d612e097a9769ee8252","_cell_guid":"b453af8d-9736-43e3-b486-7a1cd7dd8909","collapsed":true,"trusted":false},"cell_type":"code","source":" model.fit(X_train, Y_train, batch_size = 86, epochs = 4, validation_data = (X_val, Y_val), verbose = 2)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0a1834f2a9f2db15dcaba4a84004b9627d714469","_cell_guid":"e758621d-b27b-40ff-a93f-bebd2e0e5243"},"cell_type":"markdown","source":"# Evaluate the model"},{"metadata":{"_uuid":"63698d7d51381b33892ce164b0f21930abb3e937","_cell_guid":"de1c65bd-4a88-4351-9f4b-562e72e7e0fd"},"cell_type":"markdown","source":"## Confusion matrix"},{"metadata":{"_execution_state":"idle","_uuid":"16e161179bf1b51ba66c39b2cead883f1db3a9c7","_cell_guid":"11361e73-8250-4bf5-a353-b0f8ea83e659","trusted":true},"cell_type":"code","source":"def plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\n# Predict the values from the validation dataset\nY_pred = model.predict(X_val)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(Y_val,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","name":"python3","display_name":"Python 3"},"language_info":{"pygments_lexer":"ipython3","mimetype":"text/x-python","nbconvert_exporter":"python","version":"3.6.1","codemirror_mode":{"version":3,"name":"ipython"},"file_extension":".py","name":"python"}},"nbformat":4,"nbformat_minor":1}