<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/image-classification-on-small-datasets-with-keras/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://tensorflow.rstudio.com/blog/keras-image-classification-on-small-datasets.html"> TensorFlow for R</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p><a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank"><img align="right" src="https://i0.wp.com/images.manning.com/720/960/resize/book/7/9e4c694-85cf-4063-9fad-eab693da11ff/Allaire-DLwithR-MEAP-HI.png?w=70&ssl=1" data-recalc-dims="1"></a></p>
<h4>Deep Learning with R</h4>
<p>This post is an excerpt from Chapter 5 of François Chollet’s and J.J. Allaire’s book, <a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank">Deep Learning with R</a> (Manning Publications). Use the code <strong>fccallaire</strong> for a 42% discount on the book at <a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank">manning.com</a>.</p>
<div>
</div>
</div>
<div>
<h2>Training a convnet with a small dataset</h2>
<p>Having to train an image-classification model using very little data is a common situation, which you’ll likely encounter in practice if you ever do computer vision in a professional context. A “few” samples can mean anywhere from a few hundred to a few tens of thousands of images. As a practical example, we’ll focus on classifying images as dogs or cats, in a dataset containing 4,000 pictures of cats and dogs (2,000 cats, 2,000 dogs). We’ll use 2,000 pictures for training – 1,000 for validation, and 1,000 for testing.</p>
<p>In Chapter 5 of the <a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank">Deep Learning with R</a> book we review three techniques for tackling this problem. The first of these is training a small model from scratch on what little data you have (which achieves an accuracy of 82%). Subsequently we use <em>feature extraction with a pretrained network</em> (resulting in an accuracy of 90% to 96%) and <em>fine-tuning a pretrained network</em> (with a final accuracy of 97%). In this post we’ll cover only the second and third techniques.</p>
<div>
<h3>The relevance of deep learning for small-data problems</h3>
<p>You’ll sometimes hear that deep learning only works when lots of data is available. This is valid in part: one fundamental characteristic of deep learning is that it can find interesting features in the training data on its own, without any need for manual feature engineering, and this can only be achieved when lots of training examples are available. This is especially true for problems where the input samples are very high-dimensional, like images.</p>
<p>But what constitutes lots of samples is relative – relative to the size and depth of the network you’re trying to train, for starters. It isn’t possible to train a convnet to solve a complex problem with just a few tens of samples, but a few hundred can potentially suffice if the model is small and well regularized and the task is simple. Because convnets learn local, translation-invariant features, they’re highly data efficient on perceptual problems. Training a convnet from scratch on a very small image dataset will still yield reasonable results despite a relative lack of data, without the need for any custom feature engineering. You’ll see this in action in this section.</p>
<p>What’s more, deep-learning models are by nature highly repurposable: you can take, say, an image-classification or speech-to-text model trained on a large-scale dataset and reuse it on a significantly different problem with only minor changes. Specifically, in the case of computer vision, many pretrained models (usually trained on the ImageNet dataset) are now publicly available for download and can be used to bootstrap powerful vision models out of very little data. That’s what you’ll do in the next section. Let’s start by getting your hands on the data.</p>
</div>
</div>
<div>
<h2>Downloading the data</h2>
<p>The Dogs vs. Cats dataset that you’ll use isn’t packaged with Keras. It was made available by Kaggle as part of a computer-vision competition in late 2013, back when convnets weren’t mainstream. You can download the original dataset from <a rel="nofollow" href="https://www.kaggle.com/c/dogs-vs-cats/data" target="_blank">https://www.kaggle.com/c/dogs-vs-cats/data</a> (you’ll need to create a Kaggle account if you don’t already have one – don’t worry, the process is painless).</p>
<p>The pictures are medium-resolution color JPEGs. Here are some examples:</p>
<div>
<img src="https://i1.wp.com/tensorflow.rstudio.com/blog/images/keras-pretrained-convnet/cats_vs_dogs_samples.jpg?w=456&ssl=1" data-recalc-dims="1">
</div>
<p>Unsurprisingly, the dogs-versus-cats Kaggle competition in 2013 was won by entrants who used convnets. The best entries achieved up to 95% accuracy. Below you’ll end up with a 97% accuracy, even though you’ll train your models on less than 10% of the data that was available to the competitors.</p>
<p>This dataset contains 25,000 images of dogs and cats (12,500 from each class) and is 543 MB (compressed). After downloading and uncompressing it, you’ll create a new dataset containing three subsets: a training set with 1,000 samples of each class, a validation set with 500 samples of each class, and a test set with 500 samples of each class.</p>
<p>Following is the code to do this:</p>
<div>
<pre><code>original_dataset_dir &lt;-<span> &quot;~/Downloads/kaggle_original_data&quot;</span>

base_dir &lt;-<span> &quot;~/Downloads/cats_and_dogs_small&quot;</span>
<span>dir.create</span>(base_dir)

train_dir &lt;-<span> </span><span>file.path</span>(base_dir, <span>&quot;train&quot;</span>)
<span>dir.create</span>(train_dir)
validation_dir &lt;-<span> </span><span>file.path</span>(base_dir, <span>&quot;validation&quot;</span>)
<span>dir.create</span>(validation_dir)
test_dir &lt;-<span> </span><span>file.path</span>(base_dir, <span>&quot;test&quot;</span>)
<span>dir.create</span>(test_dir)

train_cats_dir &lt;-<span> </span><span>file.path</span>(train_dir, <span>&quot;cats&quot;</span>)
<span>dir.create</span>(train_cats_dir)

train_dogs_dir &lt;-<span> </span><span>file.path</span>(train_dir, <span>&quot;dogs&quot;</span>)
<span>dir.create</span>(train_dogs_dir)

validation_cats_dir &lt;-<span> </span><span>file.path</span>(validation_dir, <span>&quot;cats&quot;</span>)
<span>dir.create</span>(validation_cats_dir)

validation_dogs_dir &lt;-<span> </span><span>file.path</span>(validation_dir, <span>&quot;dogs&quot;</span>)
<span>dir.create</span>(validation_dogs_dir)

test_cats_dir &lt;-<span> </span><span>file.path</span>(test_dir, <span>&quot;cats&quot;</span>)
<span>dir.create</span>(test_cats_dir)

test_dogs_dir &lt;-<span> </span><span>file.path</span>(test_dir, <span>&quot;dogs&quot;</span>)
<span>dir.create</span>(test_dogs_dir)

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;cat.&quot;</span>, <span>1</span><span>:</span><span>1000</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames), 
          <span>file.path</span>(train_cats_dir)) 

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;cat.&quot;</span>, <span>1001</span><span>:</span><span>1500</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames), 
          <span>file.path</span>(validation_cats_dir))

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;cat.&quot;</span>, <span>1501</span><span>:</span><span>2000</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames),
          <span>file.path</span>(test_cats_dir))

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;dog.&quot;</span>, <span>1</span><span>:</span><span>1000</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames),
          <span>file.path</span>(train_dogs_dir))

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;dog.&quot;</span>, <span>1001</span><span>:</span><span>1500</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames),
          <span>file.path</span>(validation_dogs_dir)) 

fnames &lt;-<span> </span><span>paste0</span>(<span>&quot;dog.&quot;</span>, <span>1501</span><span>:</span><span>2000</span>, <span>&quot;.jpg&quot;</span>)
<span>file.copy</span>(<span>file.path</span>(original_dataset_dir, fnames),
          <span>file.path</span>(test_dogs_dir))</code></pre>
</div>
</div>
<div>
<h2>Using a pretrained convnet</h2>
<p>A common and highly effective approach to deep learning on small image datasets is to use a pretrained network. A <em>pretrained network</em> is a saved network that was previously trained on a large dataset, typically on a large-scale image-classification task. If this original dataset is large enough and general enough, then the spatial hierarchy of features learned by the pretrained network can effectively act as a generic model of the visual world, and hence its features can prove useful for many different computer-vision problems, even though these new problems may involve completely different classes than those of the original task. For instance, you might train a network on ImageNet (where classes are mostly animals and everyday objects) and then repurpose this trained network for something as remote as identifying furniture items in images. Such portability of learned features across different problems is a key advantage of deep learning compared to many older, shallow-learning approaches, and it makes deep learning very effective for small-data problems.</p>
<p>In this case, let’s consider a large convnet trained on the ImageNet dataset (1.4 million labeled images and 1,000 different classes). ImageNet contains many animal classes, including different species of cats and dogs, and you can thus expect to perform well on the dogs-versus-cats classification problem.</p>
<p>You’ll use the <a rel="nofollow" href="https://arxiv.org/abs/1409.1556" target="_blank">VGG16 architecture</a>, developed by Karen Simonyan and Andrew Zisserman in 2014; it’s a simple and widely used convnet architecture for ImageNet. Although it’s an older model, far from the current state of the art and somewhat heavier than many other recent models, I chose it because its architecture is similar to what you’re already familiar with and is easy to understand without introducing any new concepts. This may be your first encounter with one of these cutesy model names – VGG, ResNet, Inception, Inception-ResNet, Xception, and so on; you’ll get used to them, because they will come up frequently if you keep doing deep learning for computer vision.</p>
<p>There are two ways to use a pretrained network: <em>feature extraction</em> and <em>fine-tuning</em>. We’ll cover both of them. Let’s start with feature extraction.</p>
<div>
<h3>Feature extraction</h3>
<p>Feature extraction consists of using the representations learned by a previous network to extract interesting features from new samples. These features are then run through a new classifier, which is trained from scratch.</p>
<p>As you saw previously, convnets used for image classification comprise two parts: they start with a series of pooling and convolution layers, and they end with a densely connected classifier. The first part is called the <em>convolutional base</em> of the model. In the case of convnets, feature extraction consists of taking the convolutional base of a previously trained network, running the new data through it, and training a new classifier on top of the output.</p>
<div>
<img src="https://i0.wp.com/tensorflow.rstudio.com/blog/images/keras-pretrained-convnet/swapping_fc_classifier.png?w=456&ssl=1" data-recalc-dims="1">
</div>
<p>Why only reuse the convolutional base? Could you reuse the densely connected classifier as well? In general, doing so should be avoided. The reason is that the representations learned by the convolutional base are likely to be more generic and therefore more reusable: the feature maps of a convnet are presence maps of generic concepts over a picture, which is likely to be useful regardless of the computer-vision problem at hand. But the representations learned by the classifier will necessarily be specific to the set of classes on which the model was trained – they will only contain information about the presence probability of this or that class in the entire picture. Additionally, representations found in densely connected layers no longer contain any information about <em>where</em> objects are located in the input image: these layers get rid of the notion of space, whereas the object location is still described by convolutional feature maps. For problems where object location matters, densely connected features are largely useless.</p>
<p>Note that the level of generality (and therefore reusability) of the representations extracted by specific convolution layers depends on the depth of the layer in the model. Layers that come earlier in the model extract local, highly generic feature maps (such as visual edges, colors, and textures), whereas layers that are higher up extract more-abstract concepts (such as “cat ear” or “dog eye”). So if your new dataset differs a lot from the dataset on which the original model was trained, you may be better off using only the first few layers of the model to do feature extraction, rather than using the entire convolutional base.</p>
<p>In this case, because the ImageNet class set contains multiple dog and cat classes, it’s likely to be beneficial to reuse the information contained in the densely connected layers of the original model. But we’ll choose not to, in order to cover the more general case where the class set of the new problem doesn’t overlap the class set of the original model.</p>
<p>Let’s put this in practice by using the convolutional base of the VGG16 network, trained on ImageNet, to extract interesting features from cat and dog images, and then train a dogs-versus-cats classifier on top of these features.</p>
<p>The VGG16 model, among others, comes prepackaged with Keras. Here’s the list of image-classification models (all pretrained on the ImageNet dataset) that are available as part of Keras:</p>
<ul>
<li>Xception</li>
<li>Inception V3</li>
<li>ResNet50</li>
<li>VGG16</li>
<li>VGG19</li>
<li>MobileNet</li>
</ul>
<p>Let’s instantiate the VGG16 model.</p>
<div>
<pre><code><span>library</span>(keras)

conv_base &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/application_vgg.html" target="_blank">application_vgg16</a></span>(
  <span>weights =</span> <span>&quot;imagenet&quot;</span>,
  <span>include_top =</span> <span>FALSE</span>,
  <span>input_shape =</span> <span>c</span>(<span>150</span>, <span>150</span>, <span>3</span>)
)</code></pre>
</div>
<p>You pass three arguments to the function:</p>
<ul>
<li>
<code>weights</code> specifies the weight checkpoint from which to initialize the model.</li>
<li>
<code>include_top</code> refers to including (or not) the densely connected classifier on top of the network. By default, this densely connected classifier corresponds to the 1,000 classes from ImageNet. Because you intend to use your own densely connected classifier (with only two classes: <code>cat</code> and <code>dog</code>), you don’t need to include it.</li>
<li>
<code>input_shape</code> is the shape of the image tensors that you’ll feed to the network. This argument is purely optional: if you don’t pass it, the network will be able to process inputs of any size.</li>
</ul>
<p>Here’s the detail of the architecture of the VGG16 convolutional base. It’s similar to the simple convnets you’re already familiar with:</p>
<div>
<pre><code><span>summary</span>(conv_base)</code></pre>
</div>
<pre><code>Layer (type)                     Output Shape          Param #  
================================================================
input_1 (InputLayer)             (None, 150, 150, 3)   0       
________________________________________________________________
block1_conv1 (Convolution2D)     (None, 150, 150, 64)  1792     
________________________________________________________________
block1_conv2 (Convolution2D)     (None, 150, 150, 64)  36928    
________________________________________________________________
block1_pool (MaxPooling2D)       (None, 75, 75, 64)    0        
________________________________________________________________
block2_conv1 (Convolution2D)     (None, 75, 75, 128)   73856    
________________________________________________________________
block2_conv2 (Convolution2D)     (None, 75, 75, 128)   147584   
________________________________________________________________
block2_pool (MaxPooling2D)       (None, 37, 37, 128)   0        
________________________________________________________________
block3_conv1 (Convolution2D)     (None, 37, 37, 256)   295168   
________________________________________________________________
block3_conv2 (Convolution2D)     (None, 37, 37, 256)   590080   
________________________________________________________________
block3_conv3 (Convolution2D)     (None, 37, 37, 256)   590080   
________________________________________________________________
block3_pool (MaxPooling2D)       (None, 18, 18, 256)   0        
________________________________________________________________
block4_conv1 (Convolution2D)     (None, 18, 18, 512)   1180160  
________________________________________________________________
block4_conv2 (Convolution2D)     (None, 18, 18, 512)   2359808  
________________________________________________________________
block4_conv3 (Convolution2D)     (None, 18, 18, 512)   2359808  
________________________________________________________________
block4_pool (MaxPooling2D)       (None, 9, 9, 512)     0        
________________________________________________________________
block5_conv1 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_conv2 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_conv3 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_pool (MaxPooling2D)       (None, 4, 4, 512)     0        
================================================================
Total params: 14,714,688
Trainable params: 14,714,688
Non-trainable params: 0</code></pre>
<p>The final feature map has shape <code>(4, 4, 512)</code>. That’s the feature on top of which you’ll stick a densely connected classifier.</p>
<p>At this point, there are two ways you could proceed:</p>
<ul>
<li>
<p>Running the convolutional base over your dataset, recording its output to an array on disk, and then using this data as input to a standalone, densely connected classifier similar to those you saw in part 1 of this book. This solution is fast and cheap to run, because it only requires running the convolutional base once for every input image, and the convolutional base is by far the most expensive part of the pipeline. But for the same reason, this technique won’t allow you to use data augmentation.</p>
</li>
<li>
<p>Extending the model you have (<code>conv_base</code>) by adding dense layers on top, and running the whole thing end to end on the input data. This will allow you to use data augmentation, because every input image goes through the convolutional base every time it’s seen by the model. But for the same reason, this technique is far more expensive than the first.</p>
</li>
</ul>
<p>In this post we’ll cover the second technique in detail (in the book we cover both). Note that this technique is so expensive that you should only attempt it if you have access to a GPU – it’s absolutely intractable on a CPU.</p>
</div>
<div>
<h3>Feature extraction with data augmentation</h3>
<p>Because models behave just like layers, you can add a model (like <code>conv_base</code>) to a sequential model just like you would add a layer.</p>
<div>
<pre><code>model &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/keras_model_sequential.html" target="_blank">keras_model_sequential</a></span>() <span>%>%</span><span> </span>
<span> </span>conv_base <span>%>%</span><span> </span>
<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_flatten.html" target="_blank">layer_flatten</a></span>() <span>%>%</span><span> </span>
<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_dense.html" target="_blank">layer_dense</a></span>(<span>units =</span> <span>256</span>, <span>activation =</span> <span>&quot;relu&quot;</span>) <span>%>%</span><span> </span>
<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/layer_dense.html" target="_blank">layer_dense</a></span>(<span>units =</span> <span>1</span>, <span>activation =</span> <span>&quot;sigmoid&quot;</span>)</code></pre>
</div>
<p>This is what the model looks like now:</p>
<div>
<pre><code><span>summary</span>(model)</code></pre>
</div>
<pre><code>Layer (type)                     Output Shape          Param #  
================================================================
vgg16 (Model)                    (None, 4, 4, 512)     14714688                                     
________________________________________________________________
flatten_1 (Flatten)              (None, 8192)          0        
________________________________________________________________
dense_1 (Dense)                  (None, 256)           2097408  
________________________________________________________________
dense_2 (Dense)                  (None, 1)             257      
================================================================
Total params: 16,812,353
Trainable params: 16,812,353
Non-trainable params: 0</code></pre>
<p>As you can see, the convolutional base of VGG16 has 14,714,688 parameters, which is very large. The classifier you’re adding on top has 2 million parameters.</p>
<p>Before you compile and train the model, it’s very important to freeze the convolutional base. <em>Freezing</em> a layer or set of layers means preventing their weights from being updated during training. If you don’t do this, then the representations that were previously learned by the convolutional base will be modified during training. Because the dense layers on top are randomly initialized, very large weight updates would be propagated through the network, effectively destroying the representations previously learned.</p>
<p>In Keras, you freeze a network using the <code><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/freeze_weights.html" target="_blank">freeze_weights()</a></code> function:</p>
<div>
<pre><code><span>length</span>(model<span>$</span>trainable_weights)</code></pre>
</div>
<pre><code>[1] 30</code></pre>
<div>
<pre><code><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/freeze_weights.html" target="_blank">freeze_weights</a></span>(conv_base)
<span>length</span>(model<span>$</span>trainable_weights)</code></pre>
</div>
<pre><code>[1] 4</code></pre>
<p>With this setup, only the weights from the two dense layers that you added will be trained. That’s a total of four weight tensors: two per layer (the main weight matrix and the bias vector). Note that in order for these changes to take effect, you must first compile the model. If you ever modify weight trainability after compilation, you should then recompile the model, or these changes will be ignored.</p>
<div>
<h4>Using data augmentation</h4>
<p>Overfitting is caused by having too few samples to learn from, rendering you unable to train a model that can generalize to new data. Given infinite data, your model would be exposed to every possible aspect of the data distribution at hand: you would never overfit. Data augmentation takes the approach of generating more training data from existing training samples, by <em>augmenting</em> the samples via a number of random transformations that yield believable-looking images. The goal is that at training time, your model will never see the exact same picture twice. This helps expose the model to more aspects of the data and generalize better.</p>
<p>In Keras, this can be done by configuring a number of random transformations to be performed on the images read by an <code><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/image_data_generator.html" target="_blank">image_data_generator()</a></code>. For example:</p>
<div>
<pre><code>train_datagen =<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/image_data_generator.html" target="_blank">image_data_generator</a></span>(
  <span>rescale =</span> <span>1</span><span>/</span><span>255</span>,
  <span>rotation_range =</span> <span>40</span>,
  <span>width_shift_range =</span> <span>0.2</span>,
  <span>height_shift_range =</span> <span>0.2</span>,
  <span>shear_range =</span> <span>0.2</span>,
  <span>zoom_range =</span> <span>0.2</span>,
  <span>horizontal_flip =</span> <span>TRUE</span>,
  <span>fill_mode =</span> <span>&quot;nearest&quot;</span>
)</code></pre>
</div>
<p>These are just a few of the options available (for more, see the Keras documentation). Let’s quickly go over this code:</p>
<ul>
<li>
<code>rotation_range</code> is a value in degrees (0–180), a range within which to randomly rotate pictures.</li>
<li>
<code>width_shift</code> and <code>height_shift</code> are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally.</li>
<li>
<code>shear_range</code> is for randomly applying shearing transformations.</li>
<li>
<code>zoom_range</code> is for randomly zooming inside pictures.</li>
<li>
<code>horizontal_flip</code> is for randomly flipping half the images horizontally – relevant when there are no assumptions of horizontal asymmetry (for example, real-world pictures).</li>
<li>
<code>fill_mode</code> is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift.</li>
</ul>
<p>Now we can train our model using the image data generator:</p>
<div>
<pre><code><span># Note that the validation data shouldn't be augmented!</span>
test_datagen &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/image_data_generator.html" target="_blank">image_data_generator</a></span>(<span>rescale =</span> <span>1</span><span>/</span><span>255</span>)  

train_generator &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/flow_images_from_directory.html" target="_blank">flow_images_from_directory</a></span>(
  train_dir,                  <span># Target directory </span>
  train_datagen,              <span># Data generator</span>
  <span>target_size =</span> <span>c</span>(<span>150</span>, <span>150</span>),  <span># Resizes all images to 150 × 150</span>
  <span>batch_size =</span> <span>20</span>,
  <span>class_mode =</span> <span>&quot;binary&quot;</span>       <span># binary_crossentropy loss for binary labels</span>
)

validation_generator &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/flow_images_from_directory.html" target="_blank">flow_images_from_directory</a></span>(
  validation_dir,
  test_datagen,
  <span>target_size =</span> <span>c</span>(<span>150</span>, <span>150</span>),
  <span>batch_size =</span> <span>20</span>,
  <span>class_mode =</span> <span>&quot;binary&quot;</span>
)

model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/compile.html" target="_blank">compile</a></span>(
  <span>loss =</span> <span>&quot;binary_crossentropy&quot;</span>,
  <span>optimizer =</span> <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/optimizer_rmsprop.html" target="_blank">optimizer_rmsprop</a></span>(<span>lr =</span> <span>2e-5</span>),
  <span>metrics =</span> <span>c</span>(<span>&quot;accuracy&quot;</span>)
)

history &lt;-<span> </span>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit_generator.html" target="_blank">fit_generator</a></span>(
  train_generator,
  <span>steps_per_epoch =</span> <span>100</span>,
  <span>epochs =</span> <span>30</span>,
  <span>validation_data =</span> validation_generator,
  <span>validation_steps =</span> <span>50</span>
)</code></pre>
</div>
<p>Let’s plot the results. As you can see, you reach a validation accuracy of about 96%.</p>
<div>
<img src="https://i2.wp.com/tensorflow.rstudio.com/blog/images/keras-pretrained-convnet/5-3_metrics_plot_feature_extraction_with_augmentation-r.png?w=456&ssl=1" data-recalc-dims="1">
</div>
</div>
</div>
<div>
<h3>Fine-tuning</h3>
<p>Another widely used technique for model reuse, complementary to feature extraction, is <em>fine-tuning</em> Fine-tuning consists of unfreezing a few of the top layers of a frozen model base used for feature extraction, and jointly training both the newly added part of the model (in this case, the fully connected classifier) and these top layers. This is called <em>fine-tuning</em> because it slightly adjusts the more abstract representations of the model being reused, in order to make them more relevant for the problem at hand.</p>
<div>
<img src="https://i1.wp.com/tensorflow.rstudio.com/blog/images/keras-pretrained-convnet/vgg16_fine_tuning.png?w=350&ssl=1" data-recalc-dims="1">
</div>
<p>I stated earlier that it’s necessary to freeze the convolution base of VGG16 in order to be able to train a randomly initialized classifier on top. For the same reason, it’s only possible to fine-tune the top layers of the convolutional base once the classifier on top has already been trained. If the classifier isn’t already trained, then the error signal propagating through the network during training will be too large, and the representations previously learned by the layers being fine-tuned will be destroyed. Thus the steps for fine-tuning a network are as follows:</p>
<ul>
<li>Add your custom network on top of an already-trained base network.</li>
<li>Freeze the base network.</li>
<li>Train the part you added.</li>
<li>Unfreeze some layers in the base network.</li>
<li>Jointly train both these layers and the part you added.</li>
</ul>
<p>You already completed the first three steps when doing feature extraction. Let’s proceed with step 4: you’ll unfreeze your <code>conv_base</code> and then freeze individual layers inside it.</p>
<p>As a reminder, this is what your convolutional base looks like:</p>
<div>
<pre><code><span>summary</span>(conv_base)</code></pre>
</div>
<pre><code>Layer (type)                     Output Shape          Param #  
================================================================
input_1 (InputLayer)             (None, 150, 150, 3)   0        
________________________________________________________________
block1_conv1 (Convolution2D)     (None, 150, 150, 64)  1792     
________________________________________________________________
block1_conv2 (Convolution2D)     (None, 150, 150, 64)  36928    
________________________________________________________________
block1_pool (MaxPooling2D)       (None, 75, 75, 64)    0        
________________________________________________________________
block2_conv1 (Convolution2D)     (None, 75, 75, 128)   73856    
________________________________________________________________
block2_conv2 (Convolution2D)     (None, 75, 75, 128)   147584   
________________________________________________________________
block2_pool (MaxPooling2D)       (None, 37, 37, 128)   0        
________________________________________________________________
block3_conv1 (Convolution2D)     (None, 37, 37, 256)   295168   
________________________________________________________________
block3_conv2 (Convolution2D)     (None, 37, 37, 256)   590080   
________________________________________________________________
block3_conv3 (Convolution2D)     (None, 37, 37, 256)   590080   
________________________________________________________________
block3_pool (MaxPooling2D)       (None, 18, 18, 256)   0        
________________________________________________________________
block4_conv1 (Convolution2D)     (None, 18, 18, 512)   1180160  
________________________________________________________________
block4_conv2 (Convolution2D)     (None, 18, 18, 512)   2359808  
________________________________________________________________
block4_conv3 (Convolution2D)     (None, 18, 18, 512)   2359808  
________________________________________________________________
block4_pool (MaxPooling2D)       (None, 9, 9, 512)     0        
________________________________________________________________
block5_conv1 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_conv2 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_conv3 (Convolution2D)     (None, 9, 9, 512)     2359808  
________________________________________________________________
block5_pool (MaxPooling2D)       (None, 4, 4, 512)     0        
================================================================
Total params: 14714688</code></pre>
<p>You’ll fine-tune the last three convolutional layers, which means all layers up to <code>block4_pool</code> should be frozen, and the layers <code>block5_conv1</code>, <code>block5_conv2</code>, and <code>block5_conv3</code> should be trainable.</p>
<p>Why not fine-tune more layers? Why not fine-tune the entire convolutional base? You could. But you need to consider the following:</p>
<ul>
<li>Earlier layers in the convolutional base encode more-generic, reusable features, whereas layers higher up encode more-specialized features. It’s more useful to fine-tune the more specialized features, because these are the ones that need to be repurposed on your new problem. There would be fast-decreasing returns in fine-tuning lower layers.</li>
<li>The more parameters you’re training, the more you’re at risk of overfitting. The convolutional base has 15 million parameters, so it would be risky to attempt to train it on your small dataset.</li>
</ul>
<p>Thus, in this situation, it’s a good strategy to fine-tune only the top two or three layers in the convolutional base. Let’s set this up, starting from where you left off in the previous example.</p>
<div>
<pre><code><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/freeze_weights.html" target="_blank">unfreeze_weights</a></span>(conv_base, <span>from =</span> <span>&quot;block5_conv1&quot;</span>)</code></pre>
</div>
<p>Now you can begin fine-tuning the network. You’ll do this with the RMSProp optimizer, using a very low learning rate. The reason for using a low learning rate is that you want to limit the magnitude of the modifications you make to the representations of the three layers you’re fine-tuning. Updates that are too large may harm these representations.</p>
<div>
<pre><code>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/compile.html" target="_blank">compile</a></span>(
  <span>loss =</span> <span>&quot;binary_crossentropy&quot;</span>,
  <span>optimizer =</span> <span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/optimizer_rmsprop.html" target="_blank">optimizer_rmsprop</a></span>(<span>lr =</span> <span>1e-5</span>),
  <span>metrics =</span> <span>c</span>(<span>&quot;accuracy&quot;</span>)
)

history &lt;-<span> </span>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/fit_generator.html" target="_blank">fit_generator</a></span>(
  train_generator,
  <span>steps_per_epoch =</span> <span>100</span>,
  <span>epochs =</span> <span>100</span>,
  <span>validation_data =</span> validation_generator,
  <span>validation_steps =</span> <span>50</span>
)</code></pre>
</div>
<p>Let’s plot our results:</p>
<div>
<img src="https://i0.wp.com/tensorflow.rstudio.com/blog/images/keras-pretrained-convnet/5-3_metrics_plot_fine_tuning-r.png?w=456&ssl=1" data-recalc-dims="1">
</div>
<p>You’re seeing a nice 1% absolute improvement in accuracy, from about 96% to above 97%.</p>
<p>Note that the loss curve doesn’t show any real improvement (in fact, it’s deteriorating). You may wonder, how could accuracy stay stable or improve if the loss isn’t decreasing? The answer is simple: what you display is an average of pointwise loss values; but what matters for accuracy is the distribution of the loss values, not their average, because accuracy is the result of a binary thresholding of the class probability predicted by the model. The model may still be improving even if this isn’t reflected in the average loss.</p>
<p>You can now finally evaluate this model on the test data:</p>
<div>
<pre><code>test_generator &lt;-<span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/flow_images_from_directory.html" target="_blank">flow_images_from_directory</a></span>(
  test_dir,
  test_datagen,
  <span>target_size =</span> <span>c</span>(<span>150</span>, <span>150</span>),
  <span>batch_size =</span> <span>20</span>,
  <span>class_mode =</span> <span>&quot;binary&quot;</span>
)</code></pre>
</div>
<div>
<pre><code>model <span>%>%</span><span> </span><span><a rel="nofollow" href="https://tensorflow.rstudio.com/keras/reference/evaluate_generator.html" target="_blank">evaluate_generator</a></span>(test_generator, <span>steps =</span> <span>50</span>)</code></pre>
</div>
<pre><code>$loss
[1] 0.2840393

$acc
[1] 0.972</code></pre>
<p>Here you get a test accuracy of 97.2%. In the original Kaggle competition around this dataset, this would have been one of the top results. But using modern deep-learning techniques, you managed to reach this result using only a small fraction of the training data available (about 10%). There is a huge difference between being able to train on 20,000 samples compared to 2,000 samples!</p>
</div>
</div>
<div>
<h2>Take-aways: using convnets with small datasets</h2>
<p>Here’s what you should take away from the exercises in the past two sections:</p>
<ul>
<li>Convnets are the best type of machine-learning models for computer-vision tasks. It’s possible to train one from scratch even on a very small dataset, with decent results.</li>
<li>On a small dataset, overfitting will be the main issue. Data augmentation is a powerful way to fight overfitting when you’re working with image data.</li>
<li>It’s easy to reuse an existing convnet on a new dataset via feature extraction. This is a valuable technique for working with small image datasets.</li>
<li>As a complement to feature extraction, you can use fine-tuning, which adapts to a new problem some of the representations previously learned by an existing model. This pushes performance a bit further.</li>
</ul>
<p>Now you have a solid set of tools for dealing with image-classification problems – in particular with small datasets.</p>

<div>
<p><a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank"><img align="right" src="https://i0.wp.com/images.manning.com/720/960/resize/book/7/9e4c694-85cf-4063-9fad-eab693da11ff/Allaire-DLwithR-MEAP-HI.png?w=70&ssl=1" data-recalc-dims="1"></a></p>
<h4>Deep Learning with R</h4>
<p>This post is an excerpt from Chapter 5 of François Chollet’s and J.J. Allaire’s book, <a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank">Deep Learning with R</a> (Manning Publications). Use the code <strong>fccallaire</strong> for a 42% discount on the book at <a rel="nofollow" href="https://www.manning.com/books/deep-learning-with-r" target="_blank">manning.com</a>.</p>
<div>
</div>
</div>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://tensorflow.rstudio.com/blog/keras-image-classification-on-small-datasets.html"> TensorFlow for R</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/WmTI5VgYTMo" height="1"></a></div>