{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Classification: Instant Recognition with Caffe\n", "\n", "In this example we'll classify an image with the bundled CaffeNet model (which is based on the network architecture of Krizhevsky et al. for ImageNet).\n", "\n", "We'll compare CPU and GPU modes and then dig into the model to inspect features and the output." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. Setup\n", "\n", "* First, set up Python, `numpy`, and `matplotlib`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# set up Python environment: numpy for numerical routines, and matplotlib for plotting\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "# display plots in this notebook\n", "%matplotlib inline\n", "\n", "# set display defaults\n", "plt.rcParams['figure.figsize'] = (10, 10) # large images\n", "plt.rcParams['image.interpolation'] = 'nearest' # don't interpolate: show square pixels\n", "plt.rcParams['image.cmap'] = 'gray' # use grayscale output rather than a (potentially misleading) color heatmap" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Load `caffe`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# The caffe module needs to be on the Python path;\n", "# we'll add it here explicitly.\n", "import sys\n", "caffe_root = '../' # this file should be run from {caffe_root}/examples (otherwise change this line)\n", "sys.path.insert(0, caffe_root + 'python')\n", "\n", "import caffe\n", "# If you get \"No module named _caffe\", either you have not built pycaffe or you have the wrong path." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* If needed, download the reference model (\"CaffeNet\", a variant of AlexNet)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import os\n", "if os.path.isfile(caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'):\n", " print 'CaffeNet found.'\n", "else:\n", " print 'Downloading pre-trained CaffeNet model...'\n", " !../scripts/download_model_binary.py ../models/bvlc_reference_caffenet" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. Load net and set up input preprocessing\n", "\n", "* Set Caffe to CPU mode and load the net from disk." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "caffe.set_mode_cpu()\n", "\n", "model_def = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'\n", "model_weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'\n", "\n", "net = caffe.Net(model_def, # defines the structure of the model\n", " model_weights, # contains the trained weights\n", " caffe.TEST) # use test mode (e.g., don't perform dropout)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Set up input preprocessing. (We'll use Caffe's `caffe.io.Transformer` to do this, but this step is independent of other parts of Caffe, so any custom preprocessing code may be used).\n", "\n", " Our default CaffeNet is configured to take images in BGR format. Values are expected to start in the range [0, 255] and then have the mean ImageNet pixel value subtracted from them. In addition, the channel dimension is expected as the first (_outermost_) dimension.\n", " \n", " As matplotlib will load images with values in the range [0, 1] in RGB format with the channel as the _innermost_ dimension, we are arranging for the needed transformations here." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# load the mean ImageNet image (as distributed with Caffe) for subtraction\n", "mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')\n", "mu = mu.mean(1).mean(1) # average over pixels to obtain the mean (BGR) pixel values\n", "print 'mean-subtracted values:', zip('BGR', mu)\n", "\n", "# create transformer for the input called 'data'\n", "transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})\n", "\n", "transformer.set_transpose('data', (2,0,1)) # move image channels to outermost dimension\n", "transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel\n", "transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]\n", "transformer.set_channel_swap('data', (2,1,0)) # swap channels from RGB to BGR" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3. CPU classification\n", "\n", "* Now we're ready to perform classification. Even though we'll only classify one image, we'll set a batch size of 50 to demonstrate batching." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# set the size of the input (we can skip this if we're happy\n", "# with the default; we can also change it later, e.g., for different batch sizes)\n", "net.blobs['data'].reshape(50, # batch size\n", " 3, # 3-channel (BGR) images\n", " 227, 227) # image size is 227x227" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Load an image (that comes with Caffe) and perform the preprocessing we've set up." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "image = caffe.io.load_image(caffe_root + 'examples/images/cat.jpg')\n", "transformed_image = transformer.preprocess('data', image)\n", "plt.imshow(image)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Adorable! Let's classify it!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# copy the image data into the memory allocated for the net\n", "net.blobs['data'].data[...] = transformed_image\n", "\n", "### perform classification\n", "output = net.forward()\n", "\n", "output_prob = output['prob'][0] # the output probability vector for the first image in the batch\n", "\n", "print 'predicted class is:', output_prob.argmax()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The net gives us a vector of probabilities; the most probable class was the 281st one. But is that correct? Let's check the ImageNet labels..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# load ImageNet labels\n", "labels_file = caffe_root + 'data/ilsvrc12/synset_words.txt'\n", "if not os.path.exists(labels_file):\n", " !../data/ilsvrc12/get_ilsvrc_aux.sh\n", " \n", "labels = np.loadtxt(labels_file, str, delimiter='\\t')\n", "\n", "print 'output label:', labels[output_prob.argmax()]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* \"Tabby cat\" is correct! But let's also look at other top (but less confident predictions)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# sort top five predictions from softmax output\n", "top_inds = output_prob.argsort()[::-1][:5] # reverse sort and take five largest items\n", "\n", "print 'probabilities and labels:'\n", "zip(output_prob[top_inds], labels[top_inds])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* We see that less confident predictions are sensible." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4. Switching to GPU mode\n", "\n", "* Let's see how long classification took, and compare it to GPU mode." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%timeit net.forward()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* That's a while, even for a batch of 50 images. Let's switch to GPU mode." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "caffe.set_device(0) # if we have multiple GPUs, pick the first one\n", "caffe.set_mode_gpu()\n", "net.forward() # run once before timing to set up memory\n", "%timeit net.forward()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* That should be much faster!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5. Examining intermediate output\n", "\n", "* A net is not just a black box; let's take a look at some of the parameters and intermediate activations.\n", "\n", "First we'll see how to read out the structure of the net in terms of activation and parameter shapes.\n", "\n", "* For each layer, let's look at the activation shapes, which typically have the form `(batch_size, channel_dim, height, width)`.\n", "\n", " The activations are exposed as an `OrderedDict`, `net.blobs`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# for each layer, show the output shape\n", "for layer_name, blob in net.blobs.iteritems():\n", " print layer_name + '\\t' + str(blob.data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Now look at the parameter shapes. The parameters are exposed as another `OrderedDict`, `net.params`. We need to index the resulting values with either `[0]` for weights or `[1]` for biases.\n", "\n", " The param shapes typically have the form `(output_channels, input_channels, filter_height, filter_width)` (for the weights) and the 1-dimensional shape `(output_channels,)` (for the biases)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for layer_name, param in net.params.iteritems():\n", " print layer_name + '\\t' + str(param[0].data.shape), str(param[1].data.shape)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Since we're dealing with four-dimensional data here, we'll define a helper function for visualizing sets of rectangular heatmaps." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def vis_square(data):\n", " \"\"\"Take an array of shape (n, height, width) or (n, height, width, 3)\n", " and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)\"\"\"\n", " \n", " # normalize data for display\n", " data = (data - data.min()) / (data.max() - data.min())\n", " \n", " # force the number of filters to be square\n", " n = int(np.ceil(np.sqrt(data.shape[0])))\n", " padding = (((0, n ** 2 - data.shape[0]),\n", " (0, 1), (0, 1)) # add some space between filters\n", " + ((0, 0),) * (data.ndim - 3)) # don't pad the last dimension (if there is one)\n", " data = np.pad(data, padding, mode='constant', constant_values=1) # pad with ones (white)\n", " \n", " # tile the filters into an image\n", " data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))\n", " data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])\n", " \n", " plt.imshow(data); plt.axis('off')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* First we'll look at the first layer filters, `conv1`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# the parameters are a list of [weights, biases]\n", "filters = net.params['conv1'][0].data\n", "vis_square(filters.transpose(0, 2, 3, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The first layer output, `conv1` (rectified responses of the filters above, first 36 only)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "feat = net.blobs['conv1'].data[0, :36]\n", "vis_square(feat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The fifth layer after pooling, `pool5`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "feat = net.blobs['pool5'].data[0]\n", "vis_square(feat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The first fully connected layer, `fc6` (rectified)\n", "\n", " We show the output values and the histogram of the positive values" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "feat = net.blobs['fc6'].data[0]\n", "plt.subplot(2, 1, 1)\n", "plt.plot(feat.flat)\n", "plt.subplot(2, 1, 2)\n", "_ = plt.hist(feat.flat[feat.flat > 0], bins=100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The final probability output, `prob`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "feat = net.blobs['prob'].data[0]\n", "plt.figure(figsize=(15, 3))\n", "plt.plot(feat.flat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the cluster of strong predictions; the labels are sorted semantically. The top peaks correspond to the top predicted labels, as shown above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6. Try your own image\n", "\n", "Now we'll grab an image from the web and classify it using the steps above.\n", "\n", "* Try setting `my_image_url` to any JPEG image URL." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# download an image\n", "my_image_url = \"...\" # paste your URL here\n", "# for example:\n", "# my_image_url = \"https://upload.wikimedia.org/wikipedia/commons/b/be/Orang_Utan%2C_Semenggok_Forest_Reserve%2C_Sarawak%2C_Borneo%2C_Malaysia.JPG\"\n", "!wget -O image.jpg $my_image_url\n", "\n", "# transform it and copy it into the net\n", "image = caffe.io.load_image('image.jpg')\n", "net.blobs['data'].data[...] = transformer.preprocess('data', image)\n", "\n", "# perform classification\n", "net.forward()\n", "\n", "# obtain the output probabilities\n", "output_prob = net.blobs['prob'].data[0]\n", "\n", "# sort top five predictions from softmax output\n", "top_inds = output_prob.argsort()[::-1][:5]\n", "\n", "plt.imshow(image)\n", "\n", "print 'probabilities and labels:'\n", "zip(output_prob[top_inds], labels[top_inds])" ] } ], "metadata": { "description": "Instant recognition with a pre-trained model and a tour of the net interface for visualizing features and parameters layer-by-layer.", "example_name": "Image Classification and Filter Visualization", "include_in_docs": true, "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" }, "priority": 1 }, "nbformat": 4, "nbformat_minor": 0 }