<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shibsankar Das on Medium]]></title>
        <description><![CDATA[Stories by Shibsankar Das on Medium]]></description>
        <link>https://medium.com/@shibsankar?source=rss-b8693b1a332e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FFgU2s1V7zusEMy-zhIciA.jpeg</url>
            <title>Stories by Shibsankar Das on Medium</title>
            <link>https://medium.com/@shibsankar?source=rss-b8693b1a332e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:25:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shibsankar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generative AI: Building an Image Caption Generator from scratch using Tensorflow]]></title>
            <link>https://medium.com/@shibsankar/generative-ai-building-an-image-caption-generator-from-scratch-using-tensorflow-e296ba961646?source=rss-b8693b1a332e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e296ba961646</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Shibsankar Das]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 10:15:37 GMT</pubDate>
            <atom:updated>2023-02-26T10:15:37.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGnrxFYs7CTtUHjILoi41g.png" /></figure><p>In recent times Generative AI has shown tremendous growth. With the release of Generative AI platforms like ChatGPT, AI has shown its ultimate power. The success of ChatGPT is not something that came up all of a sudden. The seed was sawn with the invention of Deep Learning and LSTM architecture. So, before understanding how a Large Language Model works, it’s important to understand how a simple Image Caption Generator model works. In this article, we will discuss one of the use cases of LSTM and how it’s used to solve a simple Generative AI use case.</p><p>With the advancement of Deep Learning in the past few decades, Neural Networks have opened doors to solving many complex problems. Particularly with the popularity of CNN, LSTM has shown a lot of promise in image and text data. Image Caption generation earlier seemed impossible for a machine to understand an image now seems feasible.</p><p>Image captioning is the task of generating descriptive and relevant sentences for a given image. This task has two sub-task:</p><ol><li>Understanding the context of the given image.</li><li>Represent that understanding in the form of textual description.</li></ol><p>As an example, for the following image, the model has to generate a caption something like</p><p><em>“Two Dogs are playing in the open field</em>” or “<em>Two Dogs are running on grass</em>”</p><p>As you find in this example, many interpretations of an image might exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*zQgWtMHYLHFa7EEN" /><figcaption>Two Dogs are playing catch in a summertime meadow, Source: <a href="https://www.istockphoto.com/photo/catch-me-gm175441170-20476027?utm_source=unsplash&amp;utm_medium=affiliate&amp;utm_campaign=srp_photos_top&amp;utm_content=https%3A%2F%2Funsplash.com%2Fs%2Fphotos%2Fdog-in-field&amp;utm_term=dog%20in%20field%3A%3A%3A">iStockPhoto</a></figcaption></figure><p>The field of Image Captioning has evolved a lot in the last decade. In 2010, Ali Farhadi et al.’s paper “<strong>Every Picture Tells a Story: Generating Sentences from Images</strong>” was one of the most successful approaches to solving Image Captioning. In this paper, they have proposed to learn an association of image and caption by projecting both image and caption into a triplet representation space <strong><em>&lt;Object, Action, Scene&gt;</em></strong> that they call <strong><em>‘The meaning space”</em></strong>. They used Markov Random Field to learn the joint probability distribution of image and text. Then in 2015, the paper <strong><em>“From Captions to Visual Concepts and Back”</em></strong> from Microsoft Research used the Re-ranking of generated sentences as a novel approach. This research was benchmarked on the MS-COCO dataset.</p><p>Inspired by the success of CNN and the Sequence to Sequence model, in 2015, the paper <strong>“Show and Tell: a Neural Image Caption Generator”</strong> by Oriol et. al. from Google was a breakthrough in the field of Image Captioning. The proposed architecture used an encoder-decoder framework to generate image captions. This paper proposed an architecture that replaces the encoder RNN of the Sequence to Sequence model with a Deep Convolution Neural Network (CNN). This article will primarily follow “Show and Tell” architecture as a reference. Afterwards, there were many papers published in this field, one of them to mention is <strong><em>“Show, Attend and Tell: Neural Image Caption Generation with Visual Attention”</em></strong> where researchers have added attention layers.</p><p>This field of research requires an understanding of both Computer Vision and Natural Language Processing(NLP). Computer Vision is to understand the context of an Image whereas the Language model is to convert the image context into meaningful sentences.</p><p>CNN has been one of the most popular neural network algorithms for computer vision applications. CNN has convincingly shown that it can produce a rich representation of an image by embedding it to a fixed-length vector so that this representation can be used for solving downstream business problems. So, for the Image Caption generator, CNN is used to capture visual features from Images, CNN helps to understand the context of the image, and LSTM is used to convert image patterns into sentences. In the next section, we will discuss Convolution Neural Networks in general and their specificity for the Image Captioning task.</p><h3>Convolution Neural Network</h3><p>A Convolution Neural Network is a class of Deep Neural Network algorithms that can learn visual patterns from an image. The core of a Convolution Neural Network or ConvNet is a technique called Convolution. Convolution is a mathematical function that works based on matrix multiplication. Specifically, an image (represented as a matrix) is multiplied with a 2D array of weights, called a filter or kernel. The filter is usually a 2D matrix much smaller in size compared to the input image. During the process of Convolution, the filter is applied throughout the image by sliding across the image. Each time a dot product between the patch of the image and the filter results in a scalar value. The convolution resulted in a feature map that is capable of capturing a specific type of feature from the image. As an example, a particular filter could be learning patterns regarding the eyes of a Cat or a Dog.</p><p>The role of Convolution is to reduce the form factor of an image through a series of hidden layers without compromising on the important features present in the image and create a feature map that can be useful to predict business outcomes. A CNN is successful in learning spatial and temporal patterns from an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kHCaWmZ_n_A2i4-a" /><figcaption>Fig 2: Generic architecture of a Convolution Neural Network, Source: <a href="https://www.mathworks.com/discovery/convolutional-neural-network-matlab.html">MathWorks</a></figcaption></figure><p>Figure 2 depicts a simple ConvNet architecture that was used for image classification tasks. You will find the input image is passed through a series of Convolution, ReLU, and Pooling layers. After that, it has a fully connected layer before applying softmax at the output layer.</p><p>There are many out-of-the-box ConvNet architectures available that have shown promising results in solving many complex Machine Learning problems. You will find pre-trained model weights for these architectures that were trained on an image classification task. Some of these architectures are:</p><ol><li>AlexNet</li><li>VGGNet</li><li>ResNet</li><li>Inception</li><li>MobileNet</li><li>EfficientNet</li></ol><p>For the Image Caption Generator, we will use InceptionV3 as the base pre-trained computer vision model to extract visual features from input images. Following is the architecture of InceptionV3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*D3IRV6wrYIv5tFsb" /><figcaption>Fig 3: Architecture of Inception-V3, Source: <a href="https://cloud.google.com/tpu/docs/inception-v3-advanced">Google</a></figcaption></figure><h3>Long Short Term Memory</h3><p>Working with text data is completely different from working with image data. One of the most important properties of text data is that it follows a sequence. A sentence is comprised of a sequence of words and this sequence is constructed by following the Grammar. Recurrent Neural Network was one of the most successful algorithms to capture these phenomena and has been very successful in capturing patterns from a sequence. Especially Long Short-Term Memory, called LSTM (a variation of Recurrent Neural Network), became very popular to build a Language model and became one of the top choices for building any language model. The beauty of an LSTM is that it’s successful in memorizing a sequence even if the sequence length is very long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TZSPs16sIMADi270" /><figcaption>Fig 4: Architecture of Sequence to Sequence model using LSTM</figcaption></figure><p>The architecture in Figure 4 illustrates the way a Sequence to Sequence model works. A Sequence to Sequence architecture is widely used for the task of Neural Machine Translation where the model translates text from one language to another. The architecture has an Encoder and a Decoder network. The Encoder encodes the text in the source language to an intermediate representation (called embedding) then the Decoder generates the equivalent text in the target language. For Image Captioning the Decoder is replaced by a CNN Network. So, instead of generating a representation for the source text, the Decoder generates a representation for an image.</p><h3>Beam Search</h3><p>As mentioned earlier, the Image Caption Generator uses an LSTM-based Recurrent Neural Network that generates a caption that explains the given image. These captions are a meaningful sequence of words that follows vocabulary and grammar. In the domain of Natural Language Processing, there are many tasks like Text Sequence Generator, Neural Machine Translation, Text Summarization, etc. that use a deep neural network to generate a sequence of words. It’s sometimes computationally expensive to generate the best possible output sequence from all possible combinations of output sequences.</p><p>To generate such word sequences, the final output layer of the deep neural network has n number of neurons where n is equal to the size of the vocabulary. The output layer has a softmax layer that generates a probability distribution over each word in the vocabulary that represents the likelihood of that word being the next word in the sequence. Then the decoder searches for the best likely output sequence from all the possible output sequences based on their likelihood. The search time increases exponentially with the size of the vocabulary. For many real-life problems where the size of the vocabulary is in the order of millions, the search for the best possible output sequence becomes intractable.</p><p>Two of the most commonly used search techniques are Greedy Search and Beam Search. In the case of Greedy search, the decoder picks the best word at each stage based on the highest likelihood. This method could be computationally efficient but the quality of the generated sequence might not be optimal. The generation of the next word is dependent on the previous sequence fragment chosen. So, often this method fails to select the sequence that has the highest joint probability and lands into sub-optimal sequences.</p><p>Whereas, Beam Search is an approximate search that often works better than Greedy Search. The Beam Search selects the most likely k number of partial sequence fragments at each stage. The following image depicts the process of Beam Search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2fc9GCOSJuPwBAz" /><figcaption>Fig 5: Illustration of Beam Search</figcaption></figure><p>In the example, for beam size = 3, vocabulary size = 1000, the decoder will select the most likely 3 words (based on their probability) from the vocabulary of 1000 words which is [“a”, “an” or “the”]. At the next stage, while selecting the second word for the sequence, the decoder will compute the probability distribution over 1000 words given “a” as the first word. Similarly, the decoder will compute the probability of 1000 words given “an” as the first word. So, the decoder will computer 3*1000 = 3000 probabilities and select the top 3-word sequences which are [“a cat”, “a dog”, “the dog”]. A similar process continues for subsequent stages until the full sequence is generated.</p><p>From a computational perspective, the decoder instantiates 3 (as Beam size is 3) copies of the network to evaluate partial sequence fragments. For the next stage, those 3 networks can be efficiently utilized to evaluate probabilities of <em>3*1000 = 3000</em> probabilities and then select the top 3 most likely partial sequence fragments.</p><h3>Challenges of building Image caption Generator</h3><p>This task is more difficult than many well-studied problems like Image Classification, Object Detection. Because the generated caption not only has to describe the objects present in the image but also has to explain how each object is related to the other. There is no one correct interpretation of an image, the context of an image might be described in many different ways. So, due to the nature of this problem, it’s difficult for a model to generate the most appropriate interpretation of a given image. Moreover, this semantic knowledge has to be expressed in a natural language. So, we have to build a language model along with a computer vision model that has visual understanding.</p><p>The primary channel in building an Image Caption Generator is to deal with cross-domain interaction. It’s a fundamental problem that connects Computer Vision with Natural Language Processing. We have seen many scenarios where Computer Vision or Natural Language Processing have shown tremendous success individually. But getting both qualitative and quantitative results in such a multi-domain environment is sometimes extremely difficult and requires a high amount of labelled data.</p><h3><strong>How does an Image caption Generator work</strong>?</h3><p>An Image Caption Generator has two connected components, an Encoder, and a Decoder. The Encoder is a Deep Convolution Network that transforms the given image data into a representation in high-dimensional vector space. The Decoder is a Recurrent Neural Network that takes the Image representation as an input and generation caption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GHF_Jvr-w8xVri9B" /><figcaption>Fig 6: Architecture of Image Caption Generator model</figcaption></figure><p>The Convolution Network is a Pre-trained CNN that was trained on the ImageNet dataset. This CNN was pre-trained for an image classification task and is capable of producing a rich representation of a given image. The underlying architecture could be any of the most popular image classification architectures like VGG16, VGG19, ResNet, Inception V3, or Xception architecture. You can also use any custom convolution architecture that can project an image to a high dimensional vector space in a way that images with similar visual features are projected close to each other whereas images with dissimilar visual features are projected away from each other. The final layer of the Convolution Network provides a representation of the image in high-dimensional vector space. So, the Convolution Layer transforms the given image into an N-dimensional (as an example 1000 — dimensional) vector.</p><p>The Decoder Network is a Generative Network that generates caption-given image representation as input. The underlying architecture was inspired by the sequence-to-sequence architecture that is used for the Neural Machine Translation task. The Sequence Model takes the image representation (in the form of a vector) as input and generates a textual description. The sequence model uses LSTM/GRU units as the underlying building block.</p><p>The primary objective of the formulation is to directly optimize the log-likelihood of the correct sentence given the image as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2vPgYrJpb2sPhZ4f" /></figure><p>where 𝞱 is the trainable parameter, I is the input image and, S is the correct transcription for the image I.</p><p>So, using the Markov Chain rule, we can define the likelihood of S given I as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pICeXlFJaMyXezgl" /></figure><p>where N is the length of the sentence S.</p><p>During training time, (S, I) pairs are used as input instances and the sum of log-likelihood is optimized using stochastic gradient descent. Thus, the RNN captures <em>P(St | I, S0, S1, …, St-1)</em></p><p>The LSTM is trained to predict the next word from the vocabulary after it has seen the image representation as well as all the preceding words.</p><p>During the inference, it’s preferred to use Beam Search to generate a sentence. As discussed earlier, this process iteratively considers a set of k best partial sequence fragments. In the paper, researchers have used 20 as the Beam size. It was experimentally shown that by using a Beam size of 1 (which is the case of Greedy Search) the qualitative performance was degraded.</p><h3>How to get started</h3><p>To get started in building the Image Caption Generator, the first step is to collect the dataset. Some of the most popular and widely used datasets for this task are:</p><ol><li>Flickr8k: have 8k examples in total</li><li>Flickr30k: have 30k examples in total</li><li>MSCOCO: have ~160k examples in total</li></ol><p>You can choose from other available datasets, the dataset must have a significant amount of examples of an image, and caption pairs. The next step is to select which pre-trained computer vision architecture to use to extract visual features from an image. Some of the most successful out-of-box architectures are:</p><ol><li>VGG16</li><li>VGG19</li><li>ResNet</li><li>Inception V3</li><li>Xception</li></ol><p>For the implementation, we will use InceptionV3 as the underlying architecture. Next, we can use a pre-trained word embedding model that will boost the performance of the language model. We can use transfer learning to initiate the weights of the language model.</p><h3>Real-life applications of Image caption Generator</h3><p>One of the highly motivated use cases of Image Captioning is that this research could be extremely useful to a Visually Impaired person as a Hearing aid. In Social media, automated image caption is widely used to show the caption of an image when the image failed to load in an edge device. This could be very useful for people using the internet with very limited bandwidth. Image Captioning could be useful for many medical images to understand problems in the healthcare domain. Automated Subtitle creation of live video streams could be a very interesting use case and could be very useful for security surveillance.</p><h3>Frameworks &amp; Tools</h3><p>For the implementation following frameworks or library is used:</p><ul><li>Tensorflow</li><li>Opencv</li><li>NLTK</li><li>Sklearn</li></ul><p>Apart from these, other standard libraries are also used.</p><h3>Data loading and Preprocessing</h3><h3>Image and Caption Dataset</h3><p>For this implementation, we will be using the Flickr8k dataset. You can request the dataset by submitting a Dataset Request Form using <a href="https://forms.illinois.edu/sec/1713398">this link</a></p><p>An example of image caption pair from the flickr8k dataset. The dataset contains multiple captions for one image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*6svfTK1LeyQiPwp6" /><figcaption>Source: <a href="https://forms.illinois.edu/sec/1713398">Flickr8k Dataset</a></figcaption></figure><p>Caption Text for the Image shown:</p><p><strong><em>A black dog and a spotted dog are fighting</em></strong></p><p><strong><em>A black dog and a tri-coloured dog playing with each other on the road.</em></strong></p><p><strong><em>A black dog and a white dog with brown spots are staring at each other in the street.</em></strong></p><p><strong><em>Two dogs of different breeds looking at each other on the road.</em></strong></p><p><strong><em>Two dogs on the pavement were moving toward each other.</em></strong></p><p>The dataset has 6000 samples for training and 1000 samples each for dev and test.</p><p>Size of Training Data: 6000</p><p>Size of Dev Data: 1000</p><p>Size of Test Data: 1000</p><p>The directory structure of the dataset:</p><pre>Root<br>|---- Flicker8k_Dataset  [ contains all the images ]<br>|---- Flickr8k_text<br> |---- Flickr_8k.token.txt [ contains captions for all images. <br>|    each line has image_id, caption_number, caption_text ]<br> |---- Flickr_8k.trainImages.txt [ contains captions for training images. <br>|    each line has image_id, caption_number, caption_text ]<br> |---- Flickr_8k.devImages.txt [ contains captions for dev images. <br>|    each line has image_id, caption_number, caption_text ]<br> |---- Flickr_8k.testImages.txt [ contains captions for test images. <br>|    each line has image_id, caption_number, caption_text ]Prepare Image Data</pre><p>We will be using Inception-V3 to extract visual features from images. To do that first we will read and convert images to inception-v3 acceptable format. The dimension of the inception-v3 input tensor is <em>[299*299*3]</em>. So, each image is converted to a <em>299* 299</em>-dimensional RGB image. Then those image matrices are scaled from -1 to +1 during pre-processing. We will extract features from the last convolution layer. The shape of the output layer is 8x8x2048.</p><pre>def preprocess_image(image_src):<br>    img = tf.io.read_file(image_src)<br>    img = tf.image.decode_jpeg(img, channels=3)<br>    img = tf.image.resize(img, (299, 299))<br>    img = tf.keras.applications.inception_v3.preprocess_input(img)<br>    return img</pre><h3>Prepare Text Data</h3><p>The captions are pre-processed before being used in tokenization. Standard NLP pre-processing techniques are applied that include the removal of non-ASCII characters, lemmatization, removal of numerical values, etc. After pre-processing, a &lt;start&gt; token is added at the beginning to mark the start of the caption, and a &lt;end&gt; token is added to mark the end of the caption. Then captions are tokenized and converted to token sequences. To save space and latency we will limit the vocabulary to the top 10000 words based on their frequency of occurrence. Paddings are added to each sequence to make all the sequences equal to the longest length.</p><pre>def preprocess_txt(x):<br>    try:<br>        tk_x = x.lower()<br>        # clean punctuation<br>        tk_x = re.sub(r&#39;[^\w\s]&#39; ,&#39;&#39;, tk_x)<br>        # list of characters which needs to be replaced with space<br>        space_replace_chars = [&#39;?&#39;, &#39;:&#39;, &#39;,&#39;, &#39;&quot;&#39;, &#39;[&#39;, &#39;]&#39;, &#39;~&#39;, &#39;*&#39;, &#39;;&#39;, &#39;!&#39;, &#39;?&#39;, &#39;(&#39;, &#39;)&#39;, &#39;{&#39;, &#39;}&#39;, &#39;@&#39;, &#39;$&#39;, &#39;#&#39;, &#39;.&#39;, &#39;-&#39;, &#39;/&#39;]<br>        tk_x = tk_x.translate({ord(x): &#39; &#39; for x in space_replace_chars})<br>        non_space_replace_chars = [&quot;&#39;&quot;]<br>        tk_x = tk_x.translate({ord(x): &#39;&#39; for x in non_space_replace_chars})<br>        # remove non-ASCII chars<br>        tk_x = &#39;&#39;.join([c if ord(c) &lt; 128 else &#39;&#39; for c in tk_x])<br>        # replace all consecutive spaces with one space<br>        tk_x = re.sub(&#39;\s+&#39;, &#39; &#39;, tk_x).strip()<br>        # tokenize the words<br>        tk_x = tk_x.split()<br>        # lemmatization<br>        tk_x = [lemma.lemmatize(token) for token in tk_x]<br>        # remove numerical values<br>        tk_x = [token for token in tk_x if token.isalpha()]<br>        # join whole token<br>        tk_x = &#39; &#39;.join(tk_x)<br>        return tk_x.strip().lower()<br>    except:<br>        return &quot;&quot;</pre><pre>all_caption[&#39;caption_text&#39;] = all_caption[&#39;caption_text&#39;].apply(preprocess_txt)<br>all_caption[&#39;caption_text&#39;] = all_caption[&#39;caption_text&#39;].apply( lambda x : &#39;&lt;start&gt; &#39; + str(x) + &#39; &lt;end&gt;&#39;)<br># Choose the top 10000 words from the vocabulary<br>text_corpus = all_caption[&#39;caption_text&#39;].tolist()<br>top_k = 10000<br>tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,<br>                                                  oov_token=&quot;&lt;unk&gt;&quot;,<br>                                                  filters=&#39;!&quot;#$%&amp;()*+.,-/:;=?@[\]^_`{|}~ &#39;)<br>tokenizer.fit_on_texts(text_corpus)<br>caption_sequences = tokenizer.texts_to_sequences(text_corpus)<br>caption_vectors = tf.keras.preprocessing.sequence.pad_sequences(caption_sequences, padding=&#39;post&#39;)</pre><h3>Prepare Training Data</h3><p>Once Image and Text data are pre-processed independently, (image, source caption, target caption) triplets are generated which will be used during the training of the model. As we have discussed earlier, an LSTM cell generates the next possible word (called target caption word) after observing the image representation and all the previous words that were already generated (called source caption).</p><p>So, for the caption “Two dogs on the pavement moving toward each other” the following triplets are generated.</p><pre>image_representation, &lt;start&gt; , two<br>Image_representation, &lt;start&gt; two, dogs<br>Image_representation, &lt;start&gt; two dogs, on<br>Image_representation, &lt;start&gt; two dogs on, the<br>Image_representation, &lt;start&gt;, two dogs on the, pavement<br>Image_representation, &lt;start&gt;, two dogs on the pavement, moving<br>Image_representation, &lt;start&gt;, two dogs on the pavement moving, toward<br>Image_representation, &lt;start&gt;, two dogs on the pavement moving toward, each<br>Image_representation, &lt;start&gt;, two dogs on the pavement moving toward each, other<br>Image_representation, &lt;start&gt;, two dogs on the pavement moving toward each other, &lt;end&gt;</pre><p>The following code is used to generate an image representation, source caption, and target caption triplets.</p><pre>def prepare_training_data(image_caption_pairs_dict, tokenizer, max_length, vocab_size):<br>    image_data = list()<br>    caption_source = list()<br>    caption_target = list()<br>    for image_id, captions_list in image_caption_pairs_dict.items():<br>        image_src = os.path.join(image_dataset_src, image_id + &#39;.jpg&#39;)<br>        processed_image = preprocess_image(image_src)<br>        for caption in captions_list:<br>            text_sequence = tokenizer.texts_to_sequences([caption])[0]<br>            for i in range(1, len(text_sequence)):<br>                source_sequence = text_sequence[:i]<br>                target_sequence = text_sequence[i]<br>                source_sequence = tf.keras.preprocessing.sequence.pad_sequences([source_sequence], maxlen = max_length)[0]<br>                target_sequence = tf.keras.utils.to_categorical([target_sequence], num_classes = vocab_size)[0]<br>                image_data.append(processed_image)<br>                caption_source.append(source_sequence)<br>                caption_target.append(target_sequence)<br>    return np.array(image_data), np.array(caption_source), np.array(caption_target)</pre><h3>How to implement the model</h3><p>As discussed earlier, the model consisted of an Encoder and a Decoder network. The encoder uses the InceptionV3 model. So, the model is initialized with weights trained on the imagenet dataset. A series of fully connected layers are followed after the InceptionV3 layer. The model architecture is inspired by the architecture proposed in the Show and Tell paper.</p><p>One can extract features for all images beforehand and directly provide the features as input to the encoder-decoder model.</p><pre>pretrained_image_model = tf.keras.applications.InceptionV3(weights=&#39;imagenet&#39;)<br>image_input_tensor = pretrained_image_model.input<br>image_model_output = pretrained_image_model.layers[-1].output</pre><h4>Image Encoder Model</h4><pre>class ImageEncoderModel(tf.keras.Model):</pre><pre>def __init__(self):<br>        super(ImageEncoderModel, self).__init__()<br>        self.cnn_model = tf.keras.Model(inputs = image_input_tensor, outputs = image_model_output)<br>        self.dropout = tf.keras.layers.Dropout(0.5)<br>        self.fc1 = tf.keras.layers.Dense(512 , activation = tf.nn.relu)<br>        self.fc2 = tf.keras.layers.Dense(256 , activation = tf.nn.relu)</pre><pre>def call(self, x, training = False):<br>        x = self.cnn_model(x)<br>        if training:<br>            x = self.dropout(x, training = training)<br>        x = self.fc1(x)<br>        x = self.fc2(x)<br>        return x</pre><p>The caption sequence model architecture is very similar to the Sequence to Sequence architecture used in Neural Machine Translation.</p><h4>Caption Sequence Model</h4><pre>class CaptionSequenceModel(tf.keras.Model):  <br>    <br>    def __init__(self, embedding_dim, vocab_size):<br>        super(CaptionSequenceModel, self).__init__()<br>        self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)<br>        self.lstm1 = tf.keras.layers.LSTM(512 , return_sequences=True)<br>        self.lstm2 = tf.keras.layers.LSTM(256 , return_sequences=False)<br>        self.dropout = tf.keras.layers.Dropout(0.5)</pre><pre>def call(self, x, training = False):<br>        # x shape after passing through embedding == (batch_size, 1, embedding_dim)<br>        x = self.embedding(x)<br>        if training:<br>            x = self.dropout(x, training = training)<br>        x = self.lstm1(x)<br>        if training:<br>            x = self.dropout(x, training = training)<br>        x = self.lstm2(x)<br>        return x</pre><h4>Combine the Image Encoder and Text Sequence model and create the final model</h4><pre>def build_model(vocab_size , embeddings_dim, max_length, training = False):<br>    text_inputs_tensor = tf.keras.layers.Input(shape=(max_length,))<br>    encoder_model = ImageEncoderModel()(image_input_tensor, training = training)<br>    sequence_model = CaptionSequenceModel(embeddings_dim, vocab_size)(text_inputs_tensor, training = training)<br>    decoder1 = tf.keras.layers.add([encoder_model , sequence_model])<br>    decoder2 = tf.keras.layers.Dense(256 , activation=&#39;relu&#39;)(decoder1)<br>    decoder3 = tf.keras.layers.Dense(512 , activation=&#39;relu&#39;)(decoder2)<br>    outputs = tf.keras.layers.Dense(vocab_size , activation=&#39;softmax&#39;)(decoder3)<br>    # combine both image and text model<br>    final_model = tf.keras.models.Model([image_input_tensor , text_inputs_tensor] , outputs)<br>    final_model.compile(loss=&#39;categorical_crossentropy&#39; , optimizer = &#39;adam&#39;)<br>    return final_model</pre><h3>How to train the model</h3><p>To train the model, training triplets are generated using the function discussed earlier. Tensorflow Dataset pipeline is generated to feed models with training batches. Intermediate model weights are saved using checkpoint manager.</p><pre>batch_size = 100<br>buffer_size = 20<br>embedding_dim = 512<br>epochs = 10<br>vocab_size = len(tokenizer.word_index) + 1<br>max_len = fn_max_length(text_corpus)<br>print(&#39;vocab size&#39; , vocab_size)<br>print(&#39;max len:&#39;, max_len)<br>is_training = True<br>model = build_model(vocab_size , embedding_dim, max_len, is_training)</pre><pre>imageX, textX, trainY = prepare_training_data(caption_dict, tokenizer, max_len, vocab_size)</pre><pre>checkpoint_path = &quot;./checkpoints/train&quot;<br>ckpt = tf.train.Checkpoint(model = model)<br>ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)<br>start_epoch = 0<br>if ckpt_manager.latest_checkpoint:<br>    start_epoch = int(ckpt_manager.latest_checkpoint.split(&#39;-&#39;)[-1])<br>    # restoring the latest checkpoint in checkpoint_path<br>    ckpt.restore(ckpt_manager.latest_checkpoint)<br>    <br>trainX = tf.data.Dataset.from_tensor_slices((imageX, textX))<br>trainy_tensor = tf.data.Dataset.from_tensor_slices((trainY))</pre><pre>dataset = tf.data.Dataset.zip((trainX, trainy_tensor))<br>dataset = dataset.shuffle(buffer_size).batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE)</pre><pre>for epoch in range(start_epoch, epochs):<br>    print(&#39;Epoch : &#39;, epoch)<br>    for (batch, (X, y)) in enumerate(dataset):    <br>        model.fit(X, <br>                  y, <br>                  epochs = 1,  <br>                  shuffle=True, <br>                  verbose = 2)<br>        ckpt_manager.save()</pre><h3>How to evaluate the model</h3><p>To evaluate the performance of the model, the BLEU score is used. BLEU stands for Bilingual Evaluation Understudy. It’s a metric used to evaluate text sequence generation problems like neural machine translation, text summarization, captioning, etc. It’s a metric used to evaluate a generated sentence to a reference sentence. It ranges from 0 to +1 where 0 is a perfect mismatch and +1 is a perfect match.</p><h3>Best practices</h3><p>This section will highlight some of the best practices that are followed by industry experts to maximize the outcome of an image caption generator.</p><ul><li>Text normalization in the Beam Search decoder will be useful to reduce length bias.</li><li>Although one can use any custom convolution architecture to extract visual features from an image, it’s advisable to use one of the state-of-the-art architectures like VGG-16, mobilenet, or InceptionV3. Because these architectures have shown promising results in solving many computer vision tasks.</li><li>One can use a pre-trained model to initialize the embedding layer of the LSTM network. The pre-trained embedding that was trained on a bigger text corpus could be useful to perform better on less frequent words.</li><li>The choice of the size of embeddings could play a vital role in model performance. If the size of the embeddings is too big then the embeddings representation could be very sparse whereas too low embeddings size will suffer from information loss.</li></ul><h3>Final Thoughts</h3><p>In this article, we have discussed the evolution of Image Captioning over the last decade. We have discussed the required model architecture to implement an Image Caption Generator and explained the implementation. The Best practices could be useful to build a production-ready system. As further reading, we encourage you to follow the resources mentioned in the references.</p><h3>References</h3><ol><li><a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53">https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53</a></li><li><a href="https://machinelearningmastery.com/beam-search-decoder-natural-language-processing">https://machinelearningmastery.com/beam-search-decoder-natural-language-processing</a></li><li>Show and Tell: <a href="https://arxiv.org/pdf/1411.4555.pdf">https://arxiv.org/pdf/1411.4555.pdf</a></li><li>From Captions to Visual Concepts and Back: <a href="https://arxiv.org/pdf/1411.4952.pdf">https://arxiv.org/pdf/1411.4952.pdf</a></li><li>Show, Attend and Tell: <a href="https://arxiv.org/pdf/1502.03044.pdf">https://arxiv.org/pdf/1502.03044.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e296ba961646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Synthetic Images from textual description using GANs]]></title>
            <link>https://medium.com/data-science/generating-synthetic-images-from-textual-description-using-gans-e5963bae0df4?source=rss-b8693b1a332e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5963bae0df4</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[text-to-image-synthesis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[adversarial-network]]></category>
            <dc:creator><![CDATA[Shibsankar Das]]></dc:creator>
            <pubDate>Sat, 16 Nov 2019 18:45:16 GMT</pubDate>
            <atom:updated>2019-11-18T07:53:16.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*q-cml4JR3i_5-m1BKEU0_A.gif" /></figure><p>Automatic synthesis of realistic images is extremely difficult task and even the state-of-the-art AI/ML algorithm suffer to fulfil this expectation. In this story I will talk about how to generate realistic images from textual description which describes the image. If you are a fan of Generative Adversarial Network [GAN] then you are at the right place.</p><p>GAN was introduced back in 2014 by Ian Goodfellow and since then this topic itself became very popular in research community and we saw plenty of papers been published within few years. Deep Convolutional-GAN [DC-GAN] was one of them. Today topic is around DC-GAN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3tAV90aTZmKYNyrehwOKQ.png" /></figure><p>Can you guess whether this image is of a real cute baby or it’s imagined by GAN?</p><p>This image is actually generated by GAN. This work was done by <a href="https://arxiv.org/pdf/1812.04948.pdf">Karras et al. from NVIDIA, the paper is called StyleGAN</a>. The objective of this paper is to generate very high resolution image of human faces. You can visit the website <a href="https://thispersondoesnotexist.com/">https://thispersondoesnotexist.com</a> and each visit to this website will generate random image of human face. Since inception GAN went through lot of evolution in a very quick time and today we are at a stage to generate images which are indistinguishable from real image. GAN models are really good at generating random images but it’s extremely difficult to control GAN to generate image of our interest. In this topic I will discuss about how to generate image from a textual description which describes the image in details.</p><p><strong>Topic of Discussion: </strong>I will talk about a GAN formulation which takes as input a textual description and generate an rgb image which was described in the textual input. As an example, given</p><blockquote>“this flower has a lot of small round pink petals”</blockquote><p>as input will generate an image of flower having round pink petal as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkvN7KY5kr02lNpODeuR9g.png" /></figure><p><strong>How does Vanilla GAN works: </strong>Before moving forward let us have a quick look at how does Vanilla GAN works.</p><blockquote><strong><em>If you are already aware of Vanilla GAN, you can skip this section.</em></strong></blockquote><p>GAN comprises of two independent networks. One is called <strong>Generator</strong> and the other one is called <strong>Discriminator. </strong>Generator generates synthetic samples given a random noise [sampled from latent space] and the Discriminator is a binary classifier which discriminates between whether the input sample is real [output a scalar value 1] or fake [output scalar value 0]. <em>Samples generated by Generator is termed as fake sample.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*2Sk3Cy-wyad3zbIdajFcZg.png" /></figure><p>The beauty of this formulation is the adversarial nature between Generator and Discriminator. Discriminator wants to do it’s job in best possible way, when a fake sample [which are generated by Generator] is given to a Discriminator, it wants to call it out as fake but the Generator wants to generate samples in a way so that the Discriminator makes a mistake in calling it out as a real one. In some sense, <em>the Generator is trying to fool the Discriminator.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*YbdHOGGYbBFeQLwm1H21qA.png" /></figure><p>Let us have a quick look at the objective function and how does the optimization is done. It’s a min-max optimization formulation where Generator wants to minimize the objective function whereas Discriminator wants to maximize the same objective function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*zpikubN5h90-O2kldO6qKw.png" /></figure><p>Discriminator wants to drive the likelihood of D(G(z)) to 0. Hence it wants to maximize (1-D(G(z))) whereas the Generator wants to force the likelihood of D(G(z)) to 1 so that Discriminator makes a mistake in calling out generated sample as real. Hence Generator wants to minimize (1-D(G(z)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*5OytSMrtL9RNW0Zp4sloZQ.png" /></figure><p>This min-max formulation of the objective function has a global optimum when data distribution and model distribution is same which means if the optimization function converges to global minimum then the model had learnt the underlying data distribution present in input training dataset. Follow <a href="https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf">GAN</a> paper for better understanding.</p><p><strong>Text-to-Image formulation: </strong>In our formulation, instead of only noise as input to Generator, the textual description is first transformed into a text embedding, concatenated with noise vector and then given as input to Generator. As an example, the textual description has been transformed into a 256 dimensional embedding and concatenated with 100 dimensional noise vector [which was sampled from a Normal distribution]. This formulation will help Generator to generate images aligned with input description instead of generating random images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*zg8FF31tbWaM-igt0V8L9Q.png" /></figure><p>For Discriminator, instead of having only image as input, a pair of image and text embeddings are sent as input. Output signals are either 0 or 1. Earlier Discriminator’s responsibility was just to predict whether given image is real or fake. Now, Discriminator has one more additional responsibility. Along with identifying the given image is read or fake, it also predicts the likelihood of whether the given image and text aligned with each other. This formulation force Generator to not only generate images which looks real but also to generate images which are aligned with input textual description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*mR7iWx3jE16p9eLZbdKG3Q.png" /></figure><p>To fulfil the purpose of the 2-fold responsibility of Discriminator, during training time, a series of different (image, text) pairs are given as input as follows:</p><ol><li>Pair of (Real Image, Real Caption) as input and target variable is set to 1</li><li>Pair of (Wrong Image, Real Caption) as input and target variable is set to 0</li><li>Pair of (Fake Image, Real Caption) as input and target variable is set to 0</li></ol><p>A very interesting thing to notice here, when the target variable for (Fake Image, Real Caption) pair is 0 from Discriminator perspective. It’s set to 1 for Generator loss because Generator wants Discriminator to call it out as real image.</p><p><strong>Dataset: </strong>A very popular open-source dataset has been used for this solution. It’s called <a href="https://www.robots.ox.ac.uk/~vgg/data/flowers/102/">Oxford flowers-102 dataset</a> which has approx 8k images of 102 different categories and each image has 10 different captions describing the image. People can write captions in all different ways, this dataset is a nice example of that and covers a very wide variety of variation of captions for each image. This rich dataset helps us to learn better text embedding and helps to address the problem of variability in expressing same intent in different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*8R3iHpt0PqBsUkYvRrWJew.png" /></figure><p><strong>How text embeddings are learnt: </strong>There are several unsupervised way of learning text embeddings. A very successful way of learning text embeddings is <a href="https://arxiv.org/pdf/1506.06726.pdf">Skip-Thought Vectors</a>. This kind of pre-trained vectors can be leveraged for multiple purposes to solve downstream applications. Another popular way to learn text embeddings is called Triplet Loss. For Triplet Loss formulation, 2 captions of same image is selected, one of them is considered as anchor whereas the other one is considered as positive. A random caption from different category is considered as negative. You can refer to my previous story to know more about Triplet Loss.</p><p><a href="https://towardsdatascience.com/image-similarity-using-triplet-loss-3744c0f67973">Image similarity using Triplet Loss</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Syx4G925sJd7Wj8VId3t9A.png" /></figure><p>You can refer to following git repository as a reference to Triplet Loss implementation.</p><p><a href="https://github.com/sanku-lib/image_triplet_loss">sanku-lib/image_triplet_loss</a></p><p><strong>Results: </strong>As you see in following, even if text are written in all different format the model is able to interpret the intent and accordingly generating images. As the model was trained on images of flower, giving as input like “I want a black cat having white stripes” will generate a random image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*dbi-qKxIgYnLvMx7lwtTNQ.png" /></figure><p><strong>Conclusion: </strong>This works provides a very good direction to the future of Generative Adversarial Networks. The research community had made good progress in controlling what kind of image to generate by GAN. As research make more progress in this domain, You can expect much better results in near future.</p><p><strong>References:</strong></p><p>1. <a href="https://thispersondoesnotexist.com/">https://thispersondoesnotexist.com/</a></p><p>2. Generative Adversarial Nets [<a href="https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf">https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf</a>]</p><p>3. Generative Adversarial Text to Image Synthesis [<a href="https://arxiv.org/pdf/1605.05396.pdf">https://arxiv.org/pdf/1605.05396.pdf</a>]</p><p>4. Unsupervised Representation Learning With Deep Convolutional Generative Adversarial Networks [<a href="https://arxiv.org/pdf/1511.06434.pdf">https://arxiv.org/pdf/1511.06434.pdf</a>]</p><p>5. Skip-Thought Vectors [<a href="https://arxiv.org/pdf/1506.06726.pdf">https://arxiv.org/pdf/1506.06726.pdf</a>]</p><p>6. A Style-Based Generator Architecture for Generative Adversarial Networks [<a href="https://arxiv.org/pdf/1812.04948.pdf">https://arxiv.org/pdf/1812.04948.pdf</a>]</p><p>7. <a href="https://github.com/reedscot/icml2016">https://github.com/reedscot/icml2016</a></p><p>8. <a href="https://github.com/paarthneekhara/text-to-image">https://github.com/paarthneekhara/text-to-image</a></p><p><a href="https://github.com/ryankiros/skip-thoughts">9. https://github.com/ryankiros/skip-thoughts</a></p><p><a href="https://github.com/carpedm20/DCGAN-tensorflow">10. https://github.com/carpedm20/DCGAN-tensorflow</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5963bae0df4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generating-synthetic-images-from-textual-description-using-gans-e5963bae0df4">Generating Synthetic Images from textual description using GANs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instance Selection: The myth behind Data Sampling]]></title>
            <link>https://medium.com/data-science/instance-selection-the-myth-behind-data-sampling-d3556ea2e37d?source=rss-b8693b1a332e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3556ea2e37d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[instance-selection]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shibsankar Das]]></dc:creator>
            <pubDate>Sun, 28 Jul 2019 17:51:04 GMT</pubDate>
            <atom:updated>2019-07-28T18:29:08.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KT14xwCvjY9WhppHNupobg.png" /></figure><p>One of the most common and most challenging issues in any Big Data system is to select stratified samples in a way that it’s representative of characteristics of the overall data population. From data annotation to the selection of evaluation dataset, Data sampling is key to success behind every Data Science solution. Efficient sampling is a critical requirement also because it is assumed that the machine learning models trained on this sampled set and the insights generated hold true for the broader set.</p><blockquote><strong>Instance selection is the concept of selecting a subset from the population by maintaining the underlying distribution intact so that the sampled data is representative of the characteristics of the overall data population.</strong></blockquote><p>Let’s consider you have a population of ~10 Billion unlabelled data points. To solve the kind of problems you have, it might require a supervised approach. Now, the question is <em>How to annotate all of these data points? </em>It’s going to take an enormous amount of time with the help of a lot of human experts unless you figure out a way to automate the annotation process. Even if we manage to have label for all the data, training a Machine Learning model on a very high volume of data is sometimes not feasible due to resource constraint and might consume a very high amount of time to train which also leads to an infeasible state. At the same time, a large volume of data might be similar to each other. Hence introducing redundancy in the pattern. This kind of redundant data doesn’t help much in the learning process of the model. We can reduce the dataset by a substantial amount to decrease training time and increase performance by carefully analyzing all dimensions present in the dataset.</p><p>In reality, the way to handle this situation is to calculate the amount of data can be annotated within the available time and available resources and select that many samples out of the population in a way that the sample follows the same underlying distribution of population data. There are 2 ways to achieve this objective:</p><ol><li>Quantitative Sampling</li><li>Data-driven Sampling [Instance Selection]</li></ol><p>2 of the primary purposes behind training a Machine Learning model is to either learn a decision boundary between a number of classes/clusters or learn the input data distribution. Statistically speaking, for these cases, the learning would be similar as long the underlying data distribution is unchanged between population and sampled data.</p><ol><li><strong>Quantitative Sampling: </strong>This sampling technique requires an extensive amount of domain knowledge and an in-depth understanding of the data. The strategy differs based on the type of data whether it’s text data, image data or audio data or video data, etc.</li></ol><p>i. <strong>Uniqueness: </strong>The first step in sampling is to find out the unique data points. Uniqueness can be defined in several ways. In case of text data, if 2 documents have the exact same set of words in the same order they can be considered as duplicate or in case of image data, if the Euclidean distance between 2 image data (of the same size) is less than an epsilon then those can be considered as duplicate. Find out all duplicate data points and only one of those will represent others from duplicates.</p><p>ii. <strong>Pattern: </strong>This step is highly tricky and requires domain knowledge. Mostly manually or through a semi-automated process, we need to identify a set of patterns/structure from the data. If we have a time-series data, maybe a pattern is periodic. Maybe we can find out a pattern is being repeated every month. Then we need to select candidates spread across each month in a year but downsampling data of individual months.</p><p>In case of text data, after removing stopwords, we can replace each word by their corresponding “part of speech” as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvwL4t6mdAP2o9qk6dOioA.png" /><figcaption>POS tag of text document</figcaption></figure><p>The POS tag sequence can be considered as a structure for a given text and go for deduplication of data based on POS tag sequence. But we need to ensure the vocabulary of words is being maintained in the sample space.</p><p><strong>2. Data-driven Sampling: </strong>Instance Selection begins by first sampling the data along all dimensions of importance. One of the ways to go about Data-driven Sampling is to first learn the distributed embeddings representation of data in a supervised or an unsupervised way and then follow a greedy algorithm for candidate selection where the idea is to select one data point as representative of all the other data points which lies within delta-ball distance. As depicted in the following picture, each light green or light red circle is a sphere of delta-radius and only one data points from the sphere is selected as representative of the sphere. There are different studies related to the choice of delta. One can choose a smaller delta around centroid and boundary region whereas relatively bigger delta value for other regions. Bigger the delta means more sparse representation. This choice of the delta will ensure a dense population in centroid and boundary region whereas resulting in sparse population around the intermediate region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM96yam4vJdY8znlK-IDjQ.png" /><figcaption>Visualization of delta-ball sphere</figcaption></figure><p>In case of text data, word2vec, fasttext or Glove embeddings can be leveraged whereas, in case of image data, a low latency classifier model can be trained to obtain distributed embeddings representation.</p><p><strong>Conclusion: </strong>From Data Collection to Model Maintenance, at every step of a data science product life-cycle, selection of relevant data points plays a vital role to decide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQ4VZtERW0Efv3m1dLawNg.png" /></figure><p>i. What all data points to be used for annotation by a human expert.</p><p>ii. What all data points to be used for Model training.</p><p>iii. How to sample Evaluation dataset to measure the performance of a trained model.</p><p>iv. What all data points in history require re-run of an updated model so that we re-run model only on selected instances which has a high probability of jumping around the neighbor cluster.</p><p><strong>Git:</strong> Helper code is available <a href="https://github.com/sanku-lib/instance_selection.git">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3556ea2e37d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/instance-selection-the-myth-behind-data-sampling-d3556ea2e37d">Instance Selection: The myth behind Data Sampling</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image similarity using Triplet Loss]]></title>
            <link>https://medium.com/data-science/image-similarity-using-triplet-loss-3744c0f67973?source=rss-b8693b1a332e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3744c0f67973</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[triplet-loss]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[siamese-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shibsankar Das]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 21:15:35 GMT</pubDate>
            <atom:updated>2021-03-25T08:48:48.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tI-bi90-QHf4W5oUcXFZRQ.png" /></figure><p>Have you ever trained a Machine Learning model to solve a classification problem? If yes, what was the number of classes? maybe 10 to 200? or 1000? Does the same model work when the number of classes is in the order of millions? If the answer is No, this article is for you.</p><p>Several real-world applications in the industry, ranging from Face Recognition to Object Detection, POS Tagger to Document ranking in NLP, are formulated as a multi-class classification problem. A typical softmax-based deep network wouldn’t help when the number of classes in the output layer is too high because of the sparseness of the network. Rather, this kind of problem can be formulated in a different way. The idea is to learn distributed embeddings representation of data points in a way that in the high dimensional vector space, contextually similar data points are projected in the near-by region whereas dissimilar data points are projected far away from each other.</p><p>Triplet Loss architecture helps us to learn distributed embedding by the notion of similarity and dissimilarity. It’s a kind of neural network architecture where multiple parallel networks are trained that share weights among each other. During prediction time, input data is passed through one network to compute distributed embeddings representation of input data.</p><p>In this article, we will discuss how to train Triplet Loss and how to use the trained model during prediction.</p><p><strong>Training Data Preparation:</strong></p><p>For Triplet Loss, the objective is to build triplets &lt;anchor, positive, negative&gt; consisting of an anchor image, a positive image (which is similar to the anchor image), and a negative image (which is dissimilar to the anchor image). There are different ways to define similar and dissimilar images. If you have a dataset having multiple labels as the target class, Then images of the same class can be considered as similar, and images across different classes can be considered as dissimilar.</p><p>I have a dataset of Geological images having 6 different classes. To generate triplets, first, 2 classes are selected randomly. Then, two images are selected from one class and one image is selected from the other one. Now, images of the same classes are considered similar, so one of them is used as an anchor and the other one as positive whereas images from the other class is considered a negative image.</p><p>Likewise, for every batch, a set of n number of triplets are selected.</p><p><strong>Loss function:</strong></p><p>The cost function for Triplet Loss is as follows:</p><p><strong>L(a, p, n) = max(0, D(a, p) — D(a, n) + margin)</strong></p><p>where <strong>D(x, y):</strong> the distance between the learned vector representation of x and y. As a distance metric L2 distance or (1 - cosine similarity) can be used. The objective of this function is to keep the distance between the anchor and positive smaller than the distance between the anchor and negative.</p><p><strong>Model Architecture:</strong></p><p>The idea is to have 3 identical networks having the same neural net architecture and they should share weights. I repeat all the networks should share underlying weight vectors. [Please refer to github repository to know how to share weights between networks in tensorflow implementation]. The last layer of the Deep Network has D-number of neurons to learn D-dimensional vector representation.</p><p>Anchor, Positive and Negative images are passed through their respective network and during backpropagation weight vectors are updated using shared architecture. During prediction time, any one network is used to compute the vector representation of input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d32ww1XWWX2x3-GVYrwaeg.png" /><figcaption>Triplet Loss architecture</figcaption></figure><p>Following is the tensorboard visualization of the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68epheerjje1SdDCsO985w.png" /><figcaption>tensorboard visualization of the computation graph</figcaption></figure><p><strong>Model Learning:</strong></p><p>The model not only learned to formulate clusters for different classes at the same time, but it’s also successful in projecting similar-looking images into their neighborhood region. In the case of classification architecture, the model tries to learn a decision boundary between a pair of classes, but the model doesn’t take care of the integrity between similar and dissimilar images within a class.</p><p>To have a sense of how good is the learning of the trained model, I have randomly selected 20% of images and plotted those images in 2D space after doing dimensionality reduction on high dimensional vector space representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCEAqf6If2xxHYA_QVWs-g.jpeg" /><figcaption>Plot of data points in 2D space</figcaption></figure><p><strong>Results:</strong></p><p>Following is a snapshot of how the model is performing. I have randomly chosen 20 query images from the corpus of test images. And for each query image, plotted top 10 most probable images which are similar in terms of cosine similarity on high dimensional vector space representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8_bS-45eqlhDsXBeNHRCg.png" /></figure><p><strong>Conclusion:</strong></p><p>Triplet Loss architecture helps us to solve several problems having a very high number of classes. Let’s say you want to build a Face recognition system, where you have a database of 1 million human faces, pre-compute D dimensional vectors for each face. Now, given a human face image [as test image] compute the cosine similarity with all 1 million pre-computed vectors, and whatever image has the highest similarity will be the selected candidate. If the test image is nothing but noise, the highest similarity would be very low and will fall below a threshold parameter.</p><p>Computing cosine similarity with every image in the corpus would be very computationally inefficient. At the same time, it might require a huge amount of physical memory to store the vector representation of corpus images.</p><p>faiss, an open-source framework developed by facebook-research, helps to build an index of corpus-based on available memory and provides several methods to find out similar images comparatively faster.</p><p><strong>Git repository:</strong></p><p>Clone the git repository: <a href="https://github.com/sanku-lib/triplet_loss.git">https://github.com/sanku-lib/triplet_loss.git</a></p><p><strong>Further Reading:</strong></p><p><a href="https://neptune.ai/blog/content-based-image-retrieval-with-siamese-networks">Implementing Content-Based Image Retrieval with Siamese Networks in PyTorch</a></p><p><strong>References:</strong></p><p>[1] <a href="https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf">https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf</a></p><p>[2] <a href="https://arxiv.org/pdf/1503.03832.pdf">https://arxiv.org/pdf/1503.03832.pdf</a></p><p>[3] <a href="https://arxiv.org/pdf/1702.08734.pdf">https://arxiv.org/pdf/1702.08734.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3744c0f67973" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-similarity-using-triplet-loss-3744c0f67973">Image similarity using Triplet Loss</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>