<?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 napat thumvanit on Medium]]></title>
        <description><![CDATA[Stories by napat thumvanit on Medium]]></description>
        <link>https://medium.com/@barnrang?source=rss-1ba63b5beca5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zop2gsMPgQfAP9RC.</url>
            <title>Stories by napat thumvanit on Medium</title>
            <link>https://medium.com/@barnrang?source=rss-1ba63b5beca5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:15:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barnrang/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[Re-implementation of the Prototypical Network for Few-Shot Learning using Tensorflow 2.0 + Keras]]></title>
            <link>https://medium.com/@barnrang/re-implementation-of-the-prototypical-network-for-few-shot-learning-using-tensorflow-2-0-keras-b2adac8e49e0?source=rss-1ba63b5beca5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2adac8e49e0</guid>
            <category><![CDATA[literature-review]]></category>
            <category><![CDATA[few-shot-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[napat thumvanit]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 15:21:18 GMT</pubDate>
            <atom:updated>2020-07-30T11:54:26.995Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about the implementation based on the paper <em>Prototypical Networks for Few-shot Learning (NIPS 2017)</em></p><p>Inspired by human, In machine learning, researchers start giving attention to a new field named “Few-shot learning”. In traditional deep learning, to adapt the model to new data, we need to train on a whole large sum of data or using transfer learning to reduce the load and get faster results. On the other hand, human can learn or recognize new things within a glance or a “few shot” and here it raised a new problem definition.</p><h3>Problem Definition</h3><p>The difference here from the normal classification task is rather than learning to adapt to data, instead, we encourage our model to learn to quickly learn to adapt to new data. It might be confusing with words so let’s take a look into the actual data used in this study.</p><h4>Omniglot</h4><p>Omniglot is a dataset comprised of 1623 categories of the alphabet both real and handmade. There are 20 samples in each category. You might guess, but this is an almost impossible task for a normal classifier. [add image] Instead, we evaluate the performance on this dataset by the following task, <strong>N-way K-shot</strong></p><p>To illustrate, let’s take a look at 5-way 5-shot task. In this case, we pick random 5 classes from the dataset and 5 samples per each class as <strong>support set </strong>to the model (so the model knows which image corresponding to which class). Then from the same 5 classes, a number of samples are picked up as the <strong>query set</strong>. Hence, accuracy is measured from the query set. In the case of 1-shot, it has the same meaning as a matching game.</p><h4>Mini-Imagenet</h4><p>Mini-Imagenet is a dataset which partially cut from the original gigantic dataset Imagenet. In Mini-Imagenet, there are 100 classes with each class of 600 samples. Because this dataset is far more complex than omniglot, the benchmark was performed on only 5-way 1-shot and 5-way 5-shot.</p><h3>Previous Works</h3><h4>Siamese Network</h4><p>This is a popular architecture for measuring similarity. There is a pair of sister-network that shared weights. The features of a pair image are extracted and using regression to get similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*3JbrP8-bjJcdfy6ezduHBw.png" /><figcaption>Siamese Network for measuring similarity Retrieve: <a href="https://jp.mathworks.com/help/deeplearning/ug/train-a-siamese-network-for-dimensionality-reduction.html">https://jp.mathworks.com/help/deeplearning/ug/train-a-siamese-network-for-dimensionality-reduction.html</a></figcaption></figure><h4>Meta-learning Network</h4><p>Rather than the normal model that “learn to do”, this idea is to encourage the model “to learn to learn”. This idea is like stem-cell, it can diverse to many kinds of cells that are functional in their own task. Same here, the model can diverge from its stem model and adapt to different tasks quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNjfqTZXzQE7S5tV7Do_0Q.png" /><figcaption>Meta-learning, dotted lines are the adaptation to different tasks Retrieve: <a href="https://bair.berkeley.edu/blog/2017/07/18/learning-to-learn/">https://bair.berkeley.edu/blog/2017/07/18/learning-to-learn/</a></figcaption></figure><h4>Matching Network</h4><p>The idea here is to match the similarity of a query image to the candidates. With a similar method, they compared the features and evaluate the most similar image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*ZDHsw0LSaxUwk6AaneIgsg.png" /><figcaption>Matching Network for one-shot learning Retrieve: <a href="https://blog.acolyer.org/2017/01/03/matching-networks-for-one-shot-learning/">https://blog.acolyer.org/2017/01/03/matching-networks-for-one-shot-learning/</a></figcaption></figure><h3>Prototypical Network</h3><h4>Idea</h4><p>The prototypical network objective is to learn the metric on the embedding space which represents the similarity by distance (which can be L2 or cosine). This method can easily adapt to general k-shot by using the mean of k samples as the center of the cluster. The embedding is done by a simple convolution neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*DaFqHy7IjOEaME61EDNwDw.png" /><figcaption>Prototypical Network, map images to embedding space Retrieve from: <a href="https://arxiv.org/abs/1703.05175">https://arxiv.org/abs/1703.05175</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0YguhDywYF_ABnS_0sMMQ.png" /><figcaption>The probability of a class is proportional to the distance to the center of the class</figcaption></figure><h4>Algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SZuBvr-Kvyd09bf6tRYvQ.png" /><figcaption>Algorithm for the training process Retrieve from: <a href="https://arxiv.org/abs/1703.05175">https://arxiv.org/abs/1703.05175</a></figcaption></figure><p>Look intimidating but actually much simple than many papers out there. Here we have Nc as the number of classes (way), Ns as the number of support samples per class (shot), and Nq for the number of queries per class.</p><ol><li>Extracted the features from the convolution layer for all of the support samples.</li><li>Find the mean of the cluster for each class on the feature space and take them as the class center.</li><li>Extracted the features from the convolution layer for all of the query samples. Then calculate the logits as the negative of the distance to each class center. (Therefore, the closer it is to a class center, it is likely to be that class)</li><li>For each query sample, evaluate the probability of each class using softmax on the logit calculated in 3.</li><li>To train the model, use cross-entropy loss and backpropagation.</li></ol><h4>Architecture</h4><p>The model architecture is comprised of 4 convolutional blocks. Each block is a stack of 64-filter 3 x 3 convolution, batch normalization layer, ReLU, and 2 x 2 max-pooling layer. Finally, the output is flattened into a 2-d array.</p><h4>Implementation</h4><p>The convolutional layers can be implemented using Sequential module by keras</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a325417ecc4461ecbfa37eb5ec1003/href">https://medium.com/media/d5a325417ecc4461ecbfa37eb5ec1003/href</a></iframe><p>When implementing the model, we need to deal with the case where the input contained multiple shots per class. To easily calculate the center of the cluster, we take the input as a 5-d tensor (num_class, num_shot, width, height, channel). Thanks to the power of people, we can input 5-d tensor into the convolutional layers using TimeDistributed . Combining the convolutional layers with the TimeDistributed and we can extract the features for both of the samples and queries into a 3-d (num_class, num_shot or num_query, embedding_dim).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b522923ed4e296b2f0bfcb65457b79e7/href">https://medium.com/media/b522923ed4e296b2f0bfcb65457b79e7/href</a></iframe><p>As the algorithm suggests, we should compute the center for each class on the sample features then the output tensor dimension will change from 3-d (num_class, num_shot, embedding_dim )to 2-d (num_class, embedding_dim). For the query, we just need to flatten the tensor into 2-d (num_class * num_query, embedding_dim). I introduced 2 helper function and used the Lambda layer to introduce native TensorFlow calculation into Keras model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/929fbef65aabe1f3f41ae8c1a55fa3a0/href">https://medium.com/media/929fbef65aabe1f3f41ae8c1a55fa3a0/href</a></iframe><p>Lastly, we need to compute all pair distance of the query feature vs class center. In Scipy, it is convenient to use the function cdist (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html</a>). Here in Tensorflow, I implemented the function which computes the pair distance and then the softmax probability. In the end, we build the model combining all pipelines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/699e241db38cdded769b0e2104fc2402/href">https://medium.com/media/699e241db38cdded769b0e2104fc2402/href</a></iframe><p>At this point, we need to implement the data loader which generating the inputs, samples and queries, and targets as onehot vectors. For further detail, please take a look at my github code. The data loader code is referred from the following blog <a href="https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly">https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly</a></p><h4>Experiment</h4><h4>Omniglot</h4><p>An image can be rotated into 4 different classes. Therefore, there are 1623 * 4 = 6492 classes in total. The data was split into 4800 and 1692 classes of training and testing (no validation check).</p><p>As the paper mentioned, they found that training on higher way, for example, for 20-way validation they trained the model on 60-way instead, increase the performance of the model. Also, they claimed that training on the same number of shots turns out to be better. Therefore, I followed the paper training procedure.</p><p>I trained and evaluated on 4 tasks are 20-ways 1-shot, 20-ways 5-shots, 5-ways 1-shot, 5-ways 5-shots. The performance was desirable even slightly different from the reported results.</p><pre>20-ways 1-shot  95.4% (paper 96.0%)<br>20-ways 5-shot  98.2% (paper 98.9%)<br>5-ways 1-shot   98.5% (paper 98.8%)<br>5-ways 5-shot   99.5% (paper 99.7%)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*45P-RpBi7GPoQixRcIFCSA.png" /><figcaption>Plot the features space using 2-d PCA</figcaption></figure><p>To observe slightly into the feature space, I plotted the feature applied 2-d PCA. The different colors represent different classes and we can see nice clusters.</p><h4>Mini-imagenet</h4><p>For the Mini-imagenet, I downloaded the images from the following link <a href="https://drive.google.com/file/d/0B3Irx3uQNoBMQ1FlNXJsZUdYWEE/view">https://drive.google.com/file/d/0B3Irx3uQNoBMQ1FlNXJsZUdYWEE/view</a></p><p>To split the train, validation, and test, I followed the csv file that was suggested here <a href="https://github.com/jakesnell/prototypical-networks/tree/master/data/miniImagenet/splits/ravi">https://github.com/jakesnell/prototypical-networks/tree/master/data/miniImagenet/splits/ravi</a>. Please check out my repository if you want to do an experiment on this.</p><p>For this dataset, I have done the experiment on 1-shot 5 ways and 5-shot 5 ways with augmented number of ways (30-ways) during training. Here I found that using the model trained on 1-shot perform better than model trained on 5-shot when running evaluation on 5-shot</p><pre>1-shots 5-ways 48.77% (paper: 49.42%)<br>5-shots 5-ways 66.68% (paper: 68.20%)</pre><h3>Prototypical Network as Clustering</h3><p>From the previous section, we can see that the images are formed into clusters. The distance function that is used for density clustering should be in the class of Bregman divergence, or a distance function which exists strictly convex function F such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5CSIruLJCpbaicbsU1UvA.png" /><figcaption>Bregman divergence class distance</figcaption></figure><p>Where for Euclidean distance, F=‖x‖². The author also mentioned that using Euclidean distance on Matching Network performed better than cosine distance which is not in this class.</p><h3><strong>The End</strong></h3><p>As far as I can remember, this paper came out when the few-shot learning starts to draw attention beginning with a general concept Model-Agnostic Meta-Learning (MAML) that shows a remarkable result on omniglot and miniimagenet; in addition, to other fields such as reinforcement learning! This paper, prototypical network, came later and show a superior performance to MAML on those datasets, though this idea might not be as flexible as MAML. However, due to its simplicity with nice theoretical support made this paper was accepted to NIPS 2017.</p><h3>Full code</h3><p><a href="https://github.com/barnrang/Prototypical-network-keras-reimplementation">barnrang/Prototypical-network-keras-reimplementation</a></p><h3>Reference</h3><p>[1] Jake Snell and Kevin Swersky and Richard S. Zemel (2017). Prototypical Networks for Few-shot LearningCoRR, abs/1703.05175. <a href="https://arxiv.org/abs/1703.05175">https://arxiv.org/abs/1703.05175</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2adac8e49e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>