{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["**This notebook is an exercise in the [Deep Learning for Computer Vision](https://www.kaggle.com/learn/deep-learning-for-computer-vision) course.  You can reference the tutorial at [this link](https://www.kaggle.com/dansbecker/dropout-and-strides-for-larger-models).**\n", "\n", "---\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Introduction\n", "\n", "You've built a model to identify clothing types in the **MNIST for Fashion** dataset.  Now you will make your model bigger, specify larger stride lengths and apply dropout. These changes will make your model faster and more accurate.\n", "\n", "This is a last step in the **[Deep Learning Track](https://www.kaggle.com/learn/deep-learning)**.\n", "\n", "\n", "## Data Preparation\n", "**Run this cell of code.**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [], "source": ["import numpy as np\n", "from sklearn.model_selection import train_test_split\n", "from tensorflow import keras\n", "\n", "# Set up code checking\n", "from learntools.core import binder\n", "binder.bind(globals())\n", "from learntools.deep_learning.exercise_8 import *\n", "print(\"Setup Complete\")\n", "\n", "img_rows, img_cols = 28, 28\n", "num_classes = 10\n", "\n", "def prep_data(raw):\n", "    y = raw[:, 0]\n", "    out_y = keras.utils.to_categorical(y, num_classes)\n", "    \n", "    x = raw[:,1:]\n", "    num_images = raw.shape[0]\n", "    out_x = x.reshape(num_images, img_rows, img_cols, 1)\n", "    out_x = out_x / 255\n", "    return out_x, out_y\n", "\n", "fashion_file = \"../input/fashionmnist/fashion-mnist_train.csv\"\n", "fashion_data = np.loadtxt(fashion_file, skiprows=1, delimiter=',')\n", "x, y = prep_data(fashion_data)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# 1) Increasing Stride Size in A Layer\n", "\n", "Below is a model without strides (or more accurately, with a stride length of 1)\n", "\n", "Run it. Notice it's accuracy and how long it takes per epoch. Then you will change the stride length in one of the layers."]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [], "source": ["from tensorflow.keras.models import Sequential\n", "from tensorflow.keras.layers import Dense, Flatten, Conv2D, Dropout\n", "\n", "batch_size = 16\n", "\n", "fashion_model = Sequential()\n", "fashion_model.add(Conv2D(16, kernel_size=(3, 3),\n", "                 activation='relu',\n", "                 input_shape=(img_rows, img_cols, 1)))\n", "fashion_model.add(Conv2D(16, (3, 3), activation='relu'))\n", "fashion_model.add(Flatten())\n", "fashion_model.add(Dense(128, activation='relu'))\n", "fashion_model.add(Dense(num_classes, activation='softmax'))\n", "\n", "fashion_model.compile(loss=keras.losses.categorical_crossentropy,\n", "              optimizer='adam',\n", "              metrics=['accuracy'])\n", "\n", "fashion_model.fit(x, y,\n", "          batch_size=batch_size,\n", "          epochs=3,\n", "          validation_split = 0.2)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["You have the same code in the cell below, but the model is now called `fashion_model_1`.  Change the specification of `fashion_model_1` so the second convolutional layer has a stride length of 2.\n", "\n", "Run the cell after you have done that. How does the speed and accuracy change compared to the first model you ran above?"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["fashion_model_1 = Sequential()\n", "fashion_model_1.add(Conv2D(16, kernel_size=(3, 3),\n", "                 activation='relu',\n", "                 input_shape=(img_rows, img_cols, 1)))\n", "fashion_model_1.add(Conv2D(16, (3, 3), activation='relu', strides=2))\n", "fashion_model_1.add(Flatten())\n", "fashion_model_1.add(Dense(128, activation='relu'))\n", "fashion_model_1.add(Dense(num_classes, activation='softmax'))\n", "\n", "fashion_model_1.compile(loss=keras.losses.categorical_crossentropy,\n", "              optimizer='adam',\n", "              metrics=['accuracy'])\n", "\n", "fashion_model_1.fit(x, y,\n", "          batch_size=batch_size,\n", "          epochs=3,\n", "          validation_split = 0.2)\n", "\n", "# Check your answer\n", "q_1.check()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["For the solution, uncomment and run the cell below:"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["#q_1.solution()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["You should notice that your model training ran about twice as fast, but the accuracy change was trivial.  \n", "\n", "In addition to being faster to train, this model is also faster at making predictions. This is very important in many scenarios. In practice, you'll need to decide whether that type of speed is important in the applications where you eventually apply deep learning models.\n", "\n", "You could experiment with more layers or more convolutions in each layer. With some fine-tuning, you can build a model that is both faster and more accurate than the original model."]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Congrats\n", "You've finished the Deep Learning course.  You have the tools to create and tune computer vision models.  \n", "\n", "If you feel like playing more with this dataset, you can open up a new code cell to experiment with different models (adding dropout, adding layers, etc.)  Or pick a new project and try out your skills.  \n", "\n", "A few fun datasets you might try include:\n", "- [Written letter recognition](https://www.kaggle.com/olgabelitskaya/classification-of-handwritten-letters)\n", "- [Flower Identification](https://www.kaggle.com/alxmamaev/flowers-recognition)\n", "- [Cats vs Dogs](https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition)\n", "- [10 Monkeys](https://www.kaggle.com/slothkong/10-monkey-species)\n", "- [Predict Bone Age from X-Rays](https://www.kaggle.com/kmader/rsna-bone-age)\n", "\n", "You have learned a lot, and you'll learn it as you practice. Have fun with it!"]}, {"cell_type": "markdown", "metadata": {}, "source": ["---\n", "\n", "\n", "\n", "\n", "*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/161321) to chat with other Learners.*"]}], "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5"}}, "nbformat": 4, "nbformat_minor": 2}