{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3" }, "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.5.4" }, "colab": { "name": "classify_images_cats-vs-dogs.ipynb", "provenance": [], "collapsed_sections": [] }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "aZ6fXTzdYqbS", "colab_type": "text" }, "source": [ "#
CS568:Deep Learning
Spring 2020
" ] }, { "cell_type": "markdown", "metadata": { "id": "UYIHpg--Yqbc", "colab_type": "text" }, "source": [ "Mount your Google drive by using this code snippet" ] }, { "cell_type": "code", "metadata": { "id": "FunfJyntYqbj", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "079facca-3a20-4435-f89c-9c78351f9af9" }, "source": [ "from google.colab import drive\n", "drive.mount('/content/drive')" ], "execution_count": 2, "outputs": [ { "output_type": "stream", "text": [ "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "tUQJxmN5Yqb3", "colab_type": "text" }, "source": [ "In this exercise, we will build a neural network model from scratch that is able to distinguish dogs from cats. \n", "\n", "**NOTE:** The 2200 images used in this exercise are excerpted from the [\"Dogs vs. Cats\"](https://www.kaggle.com/c/dogs-vs-cats/data) dataset available on Kaggle, which contains 25,000 images. We use a subset of the full dataset here.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "GJenTzZTYqb-", "colab_type": "text" }, "source": [ "#### 1.1 Load dataset\n", " " ] }, { "cell_type": "code", "metadata": { "id": "bo8kR9KXYqcH", "colab_type": "code", "outputId": "cf79ef14-cd08-49d9-c052-56cb27937327", "colab": { "base_uri": "https://localhost:8080/", "height": 68 } }, "source": [ "from keras.preprocessing.image import ImageDataGenerator\n", "\n", "img_height, img_width = 128, 128\n", "\n", "train_data_dir = '/content/drive/My Drive/CS568-DeepLearning-(Spring2020)/dataset/dogs-vs-cats/train/'\n", "validation_data_dir = '/content/drive/My Drive/CS568-DeepLearning-(Spring2020)/dataset/dogs-vs-cats/val/' \n", "test_data_dir = '/content/drive/My Drive/CS568-DeepLearning-(Spring2020)/dataset/dogs-vs-cats/'\n", "\n", "# normalize the pixel values from [0, 255] to [0, 1] interval\n", "datagen = ImageDataGenerator(rescale=1./255)\n", "\n", "# automagically retrieve images and their classes for train and validation sets\n", "batch_size = 32 # e.g 4, 8, 16, 32, 64\n", "\n", "train_generator = datagen.flow_from_directory(\n", " train_data_dir,\n", " target_size=(img_width, img_height),\n", " color_mode = 'grayscale',\n", " batch_size=batch_size,\n", " class_mode='binary')\n", "\n", "validation_generator = datagen.flow_from_directory(\n", " validation_data_dir,\n", " target_size=(img_width, img_height),\n", " color_mode = 'grayscale',\n", " batch_size=batch_size,\n", " class_mode='binary')\n", "\n", "test_generator = datagen.flow_from_directory(\n", " test_data_dir,\n", " target_size=(img_width, img_height),\n", " color_mode = 'grayscale',\n", " classes = ['test'],\n", " class_mode=None)" ], "execution_count": 9, "outputs": [ { "output_type": "stream", "text": [ "Found 2067 images belonging to 2 classes.\n", "Found 217 images belonging to 2 classes.\n", "Found 100 images belonging to 1 classes.\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "Og2by6k6Yqcd", "colab_type": "code", "outputId": "72585b0f-45c9-4966-f6c4-a0fecc432233", "colab": { "base_uri": "https://localhost:8080/", "height": 1000 } }, "source": [ "from keras.models import Sequential\n", "from keras import layers\n", "from keras.layers import Dropout, Flatten, Dense\n", "from keras.optimizers import SGD\n", "\n", "img_width, img_height = 128, 128\n", "input_dim = 128*128\n", "output_dim = 1\n", "\n", "def lr():\n", " # initialize model\n", " model = Sequential()\n", " # flatten or vectorize input layer images\n", " model.add(Flatten(input_shape=(img_height,img_width,1)))\n", " # add an input layer and output layer with activation function\n", " model.add(Dense(output_dim, input_dim=input_dim, activation='sigmoid')) \n", " return model\n", "\n", "# define model\n", "model = lr()\n", "# define optimizer\n", "sgd = SGD(lr=0.001)\n", "model.compile(optimizer=sgd, loss='mse', metrics=['accuracy'])\n", "# print model information\n", "model.summary()\n", "\n", "\n", "nb_epoch = 100\n", "nb_train_samples = 2000\n", "nb_validation_samples = 200\n", "\n", "import time\n", "start = time.time()\n", "model_info = model.fit_generator(\n", " train_generator,\n", " samples_per_epoch=nb_train_samples,\n", " nb_epoch=nb_epoch,\n", " validation_data=validation_generator,\n", " nb_val_samples=nb_validation_samples)\n", "end = time.time()\n", "print(\"Model took %0.2f seconds to train\"%(end - start))" ], "execution_count": 12, "outputs": [ { "output_type": "stream", "text": [ "Model: \"sequential_7\"\n", "_________________________________________________________________\n", "Layer (type) Output Shape Param # \n", "=================================================================\n", "flatten_7 (Flatten) (None, 16384) 0 \n", "_________________________________________________________________\n", "dense_11 (Dense) (None, 1) 16385 \n", "=================================================================\n", "Total params: 16,385\n", "Trainable params: 16,385\n", "Non-trainable params: 0\n", "_________________________________________________________________\n", "Epoch 1/100\n" ], "name": "stdout" }, { "output_type": "stream", "text": [ "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:39: UserWarning: The semantics of the Keras 2 argument `steps_per_epoch` is not the same as the Keras 1 argument `samples_per_epoch`. `steps_per_epoch` is the number of batches to draw from the generator at each epoch. Basically steps_per_epoch = samples_per_epoch/batch_size. Similarly `nb_val_samples`->`validation_steps` and `val_samples`->`steps` arguments have changed. Update your method calls accordingly.\n", "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:39: UserWarning: Update your `fit_generator` call to the Keras 2 API: `fit_generator(" ] }, "metadata": { "tags": [] } } ] } ] }