<?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 Nguyễn Văn Lĩnh on Medium]]></title>
        <description><![CDATA[Stories by Nguyễn Văn Lĩnh on Medium]]></description>
        <link>https://medium.com/@linh.nguyen.fi?source=rss-e2a125f88e00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Dx3XpsAPzqzxEXIi.</url>
            <title>Stories by Nguyễn Văn Lĩnh on Medium</title>
            <link>https://medium.com/@linh.nguyen.fi?source=rss-e2a125f88e00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:43:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@linh.nguyen.fi/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[Installing multiple CUDA + cuDNN versions in the same machine for Tensorflow and Pytorch]]></title>
            <link>https://medium.com/datatype/installing-multiple-cuda-versions-in-the-same-machine-for-tensorflow-and-pytorch-9ce1f5516e16?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce1f5516e16</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Wed, 05 May 2021 19:51:43 GMT</pubDate>
            <atom:updated>2022-04-08T21:34:24.492Z</atom:updated>
            <content:encoded><![CDATA[<p>This multiple CUDA versions arises when we need to do experiment on different deep learning projects on different Tensorflow, Pytorch versions. Of course, Docker is one of the first solution but it big, Anaconda limits the commercial ability, then we need to do something better.</p><p>On Windows or Linux, the typical CUDA + cuDNN setup is:</p><ul><li>Install latest NVIDIA driver</li><li>Install required CUDA version</li><li>Add installed CUDA folders to the System Path</li><li>Download &amp; extract required cuDNN version and do either copy to CUDA folders or add directly cuDNN folders to the System Path.</li></ul><p>The benefit of Pytorch is it does not require installing the specific version of cuDNN. Now at May 2021, Pytorch requires CUDA 10.2 or 11.1 <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a></p><p>Tensorflow is much more strict on CUDA and cuDNN version specification. According to <a href="https://www.tensorflow.org/install/source#gpu">https://www.tensorflow.org/install/source#gpu</a>, <br>tensorflow-2.4.0 GPU needs cuDNN 8.0 and CUDA 11.0.</p><h3>You need to install latest Nvidia Driver</h3><p>Even the CUDA, cuDNN, and Nvidia driver also need to maintain these compatibility</p><p><a href="https://docs.nvidia.com/deploy/cuda-compatibility/index.html">CUDA Compatibility</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*_MOmRbZuiZypXj6_.png" /><figcaption>NVIDIA driver is the essential requirement for CUDA</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*RMr-naJMkjq6GyL0.png" /><figcaption>New NVIDIA driver (for ex: R450) supports “old” CUDA version but it is not vice versa</figcaption></figure><h4>Latest Nvidia driver on Ubuntu 20.04</h4><p>Firstly, we need to remove all nvidia installation</p><blockquote>sudo apt-get purge *nvidia*<br>sudo apt autoremove</blockquote><p>Check Ubuntu drivers and auto install the recommended latest Nvidia driver</p><blockquote>ubuntu-drivers devices<br>sudo ubuntu-drivers autoinstall</blockquote><h3>Difference CUDA version installation and maintainance</h3><p>Now, when typing nvidia-smi you will see something like that:</p><blockquote>NVIDIA-SMI 460.73.01 Driver Version: 460.73.01 CUDA Version: <strong>11.2</strong></blockquote><p>CUDA version is usually higher than what we need and it is the confusion point.</p><p>In my case now, I need to install CUDA 11.1 for Pytorch and CUDA 11.0 + cuDNN 8.0 for Tensorflow 2.4</p><h4>Download</h4><p>Firstly, I need to download CUDA toolkit 11.0 and 11.1 <strong>run file</strong> (not deb) at</p><p><a href="https://developer.nvidia.com/cuda-toolkit-archive">CUDA Toolkit Archive</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*GN2t0jWeBeyfsxamdNts7g.png" /><figcaption>Need to download the runfile</figcaption></figure><p>Then the download link for Cuda toolkit:</p><pre>wget https://developer.download.nvidia.com/compute/cuda/11.0.3/local_installers/cuda_11.0.3_450.51.06_linux.run</pre><pre>wget <a href="https://developer.download.nvidia.com/compute/cuda/11.1.1/local_installers/cuda_11.1.1_455.32.00_linux.run">https://developer.download.nvidia.com/compute/cuda/11.1.1/local_installers/cuda_11.1.1_455.32.00_linux.run</a></pre><p>I only need install cuDNN 8.0 for Cuda 11.0, all links can be found here:</p><p><a href="https://developer.nvidia.com/rdp/cudnn-archive">cuDNN Archive</a></p><p>Remember to download the .tgz file (no .deb again)</p><pre><a href="https://developer.nvidia.com/compute/machine-learning/cudnn/secure/8.0.5/11.0_20201106/cudnn-11.0-linux-x64-v8.0.5.39.tgz">https://developer.nvidia.com/compute/machine-learning/cudnn/secure/8.0.5/11.0_20201106/cudnn-11.0-linux-x64-v8.0.5.39.tgz</a></pre><h4>Install CUDA toolkit</h4><p>We need to install only the CUDA toolkit to the specific path that name: cuda-11.0 or cuda-11.1 rather than the default cuda already used for driver installation. If everything into the cuda folder, you will high likely face this error:</p><blockquote>NVIDIA-SMI has failed because it couldn’t communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.</blockquote><p>Installation command:</p><p>sudo sh cuda_11.0.3_450.51.06_linux.run --silent --toolkit --toolkitpath=/usr/local/cuda-11.0</p><p>sudo sh <a href="https://developer.download.nvidia.com/compute/cuda/11.1.1/local_installers/cuda_11.1.1_455.32.00_linux.run">cuda_11.1.1_455.32.00_linux.run</a> --silent --toolkit --toolkitpath=/usr/local/cuda-11.1</p><h4>Install cuDNN</h4><p>I only need to install cuDNN 8.0 along with Cuda 11.0. The simplest is just extract the .tgz cudnn file and copy all files in the <em>include</em> and <em>lib64</em> folder from cudnn to cuda 11.0 installed folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*OEi6dHDkFZdfvDd2i3CMYg.png" /></figure><pre>sudo cp cuda/include/cudnn*.h /usr/local/cuda-11.0/include</pre><pre>sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda-11.0/lib64</pre><pre>sudo chmod a+r /usr/local/cuda-11.0/include/cudnn*.h /usr/local/cuda-11.0/lib64/libcudnn*</pre><p>The default paths of cuDNN installation (maybe come along with the nvidia driver installation) are:</p><pre>/usr/include<br>/usr/lib/x86_64-linux-gnu/</pre><h3>Cuda installation to system Path</h3><p>We can do manually adding the corresponding version of the cuda installation to the system PATH and LD_LIBRARY_PATH.</p><p>The best automation way to add a specific version of Cuda path to system Path via .bashrc, is from this link</p><p><a href="https://notesbyair.github.io/blog/cs/2020-05-26-installing-multiple-versions-of-cuda-cudnn/">How to manage multiple versions of Cuda and cuDNN ?</a></p><p>Simply add this to the end of your ~/.bashrc file</p><pre><em># add below to your env bash file.</em><br><br>function _switch_cuda {<br>   v=$1<br>   export PATH=$PATH:/usr/local/cuda-$v/bin<br>   export CUDADIR=/usr/local/cuda-$v<br>   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-$v/lib64<br>   nvcc --version<br>}</pre><p>And call this function to switch to a corresponding cuda version on your bash session</p><pre>_switch_cuda 11.0 <em># change the version of your like to load bash.</em></pre><p>Please remember to switch cuda version before running your source code.</p><h3>Reference:</h3><ul><li><a href="https://stackoverflow.com/questions/67364950/cuda-and-cudnn-version-conflict-against-tensorflow2-4-1">https://stackoverflow.com/questions/67364950/cuda-and-cudnn-version-conflict-against-tensorflow2-4-1</a></li><li><a href="https://notesbyair.github.io/blog/cs/2020-05-26-installing-multiple-versions-of-cuda-cudnn/">https://notesbyair.github.io/blog/cs/2020-05-26-installing-multiple-versions-of-cuda-cudnn/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce1f5516e16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/installing-multiple-cuda-versions-in-the-same-machine-for-tensorflow-and-pytorch-9ce1f5516e16">Installing multiple CUDA + cuDNN versions in the same machine for Tensorflow and Pytorch</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SuperResolution by Unet and customized feature loss]]></title>
            <link>https://medium.com/datatype/superresolution-by-unet-and-customized-feature-loss-79b469aa5bd3?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/79b469aa5bd3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[super-resolution]]></category>
            <category><![CDATA[unet]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 21:23:23 GMT</pubDate>
            <atom:updated>2020-01-15T20:33:47.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>SuperResolution by Unet and customized Resnet style loss</h3><p>Unet is one of the universal deep learning algorithm that can do multiple tasks well-enough and only need to change the input-output setup. Not only image segmentation intensively, people nowadays used it in image sharpening, coloring images, to 3d segmentation …</p><p><em>The basic idea of this DIY deep learning is:</em></p><ul><li>Using Unet for superResolution low quality images.</li><li>Customize loss that inspired from VGG <em>style transfer</em> loss from the fast-ai course.</li><li>My customize loss defined on Resnet that pretrained on Imagnet. My simple argument: VGG is old and Resnet clearly is better architecture for image classification. Thus Resnet should learned better image filters/convolution that useful in image representation for further tasks.</li></ul><p><em>The outline is:</em></p><ul><li>Unet introduction and where we get-in.</li><li>Style transfer with VGG</li><li>VGG vs Resnet and which Resnet layer we get the feature? As no max-pool layer in Resnet.</li><li>Feature losses that inspired from style-transfer.</li><li>Experiment detail and results.</li></ul><h3>Motivation results</h3><p>Using same number of training loop</p><h4>SuperResolution by Unet + Vgg style transfer loss. Model 1</h4><p>Input image size: 96x96, jpg quality = 60 when saving the resized image from the raw image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jz-87JJRLSn9NRU8EC3Qnw.png" /></figure><h4>My proposal: SuperResolution by Unet + Resnet style transfer loss</h4><p>Input image size: 128x128, jpg quality = 40. The prediction image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh5pESj4gcO6TS8pTaZlnQ.png" /></figure><h4>SuperResolution by Unet + Vgg style transfer loss. Model 2</h4><p>Continue training from previous model 1 of 96x96 size. Double training time.</p><p>Input image size: 256x256, jpg quality = 60. The prediction image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIeAf8MBTG0xdvCxe73Png.png" /></figure><h4>Brief conclusion</h4><p>By appropriate setup + a better loss: reduce half of training time and ‘good enough’ to use quality. Only a bit less detail in the cat’ eyes but I also can be an over-fitting indicator: too smooth for some regions.</p><p>My favor is fast-prototyping, done the pipeline and get ‘enough’ results as fast as possible. It is important to get the idea implementation, especially fast with the fastai library.</p><h3>Unet</h3><p>The name says it all, the U style architecture for network which contains common deep-networks elements: convolution, max pool, up-convolution (UpSampling or Conv2dTranspose), and 1x1 conv (thanks to Resnet).</p><p>Other networks usually downs the output image size after maxpool layers into a small image-size but larger number of features. After that, do the up convolution from that middle layer to the desired output size. This kind of bottle-neck, encode-decode networks transfer gradually the input information into features and try to learn back again. However, this is a harder equation to solve if you do not have enough training data when input image size/information reducing over and over through the network. Generally, it is data compression problem, and computer is just computer, we need to give more information or easier problem.</p><p>The breaking point of Unet is reusing the data from middle layers to the up-convolution steps. Simply, more information is better and especially, middle layers contains information in different perspective/feature space.</p><p>People call the encoding path here is contracting and decoding is expansive path. And by make ‘crop and copy’ output layers from two symmetric side of the network. There are more information to decode now, more useful, and data efficiency.</p><p>Even, the Unet is already public from 2015, people have just used them in recently 2 years from Kaggle competition winners. I admire the way of authors see about the whole limited data segmentation problem. You should read about it if not yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*vRCJPrsFBm8XAEAr.jpg" /><figcaption>Illustration of U-Net architecture. Olaf Ronneberger, Philipp Fischer, Thomas Brox. U_Net: Convolutional Networks for Biomedical Image Segmentation. May 2015</figcaption></figure><h4>Unet for SuperResolution</h4><p>Technically, we can do SuperResolution by only using Unet directly.</p><ul><li>Down resolution training image.</li><li>Training Unet by default loss.</li><li>Training data: low resolution image</li><li>Training target: corresponding high resolution image. Of course, you need to change the output size: image width x height x 3.</li></ul><p>However, getting good results for superResolution task is not easy, there are something more than numerical losses to compare the upsampling image vs real image. In the semantic level, how human compare two images:</p><ul><li>Color/style difference.</li><li>Detail difference.</li><li>Conceptual difference (maybe).</li></ul><p>So what makes sense here is a more comprehensive loss. Remember that people done the style transfer between two images into a new one that including style/color/detail of two inputs. It is somehow similar topic now even the application is difference in these points:</p><ul><li>I need to keep the style, or transfer to the output.</li><li>Did that by more <em>intuitive</em> layer statistics losses.</li></ul><h3>Style transfer with VGG</h3><p>Style transfer is quite a hot algorithm around 2015 due to the practical and fun to use aspect. The problem is formulated as:</p><ul><li>Input: content image and style image.</li><li>Output: generated image that includes content pixels but mixed the style of the ‘style image’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tnA9Rkwfi-P5MAZz.png" /><figcaption>Style transfer example. <a href="https://hackernoon.com/how-do-neural-style-transfers-work-7bedaee0559a">https://hackernoon.com/how-do-neural-style-transfers-work-7bedaee0559a</a></figcaption></figure><ul><li>Todo: optimization on the generated random image, putting 3 images over a pretrain neural network to get the input for the loss. They need to be represented in the same feature space before doing the difference measurement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*_3hb-5KZcZ_UgOpI.png" /><figcaption>Style transfer diagram. <a href="https://hackernoon.com/how-do-neural-style-transfers-work-7bedaee0559a">https://hackernoon.com/how-do-neural-style-transfers-work-7bedaee0559a</a></figcaption></figure><p>As we only care about the loss:</p><ul><li>Content loss: L1 numerical loss among pixels (nothing new).</li><li>Style loss: it is content loss of the “feature correlation”.</li></ul><h4>Feature correlation and style loss</h4><p>At the middle-layer outputs or the activation layer, it is the layer of:</p><ul><li>[n, c, h, w] : batch size x feature_channels x feature_height x feature_width</li><li>The <em>correlation</em> here is the correlation among feature matrices: [h,w] size. Mathematically, it is called <em>Gram matrix </em>or<em> </em>matrix dot product of features matrices and a sum -&gt; return a number for correlation measurement.</li><li>The output will be a <em>feature correlation tensor</em> of [n, c, c]</li><li>It is all combination of correlation among feature channels.</li><li>Style loss is the content loss of <em>feature correlation tensor </em>of generated and style images.</li></ul><p>Remember when input image size reducing, there are no more pixel-level details to be fit rather than general image description.</p><h4><em>Where to get the VGG middle-layer outputs ?</em></h4><p>Where VGG changes output size is the interested location to get the activation/middle-layer outputs. As we can not do the style loss for all layer outputs and</p><p>Clearly, it is where the max-pool layer located. But ResNet don’t.</p><h3>VGG vs Resnet</h3><p>In short, Resnet advantages thanks to:</p><ul><li>Residual approximation, instead of learn the mapping f(x) from x to y. Learn the residual information that only need to transform x to f(x) + x.</li><li>1x1 convolution: still reduce half of size but no need max-pool.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*vgb5EFTHHJMRjGvl.png" /><figcaption><a href="https://cv-tricks.com/cnn/understand-resnet-alexnet-vgg-inception/">https://cv-tricks.com/cnn/understand-resnet-alexnet-vgg-inception/</a></figcaption></figure><p>To independent the Resnet implementation, just find the layer location of output size change.</p><h3>Resnet feature loss</h3><h4>Identify Resnet middle layers output in Fastai</h4><p>Resnet evaluation model purpose.</p><blockquote>body = create_body(models.resnet34, pretrained=True).cuda().eval()<br>requires_grad(body, False)</blockquote><p>Send dummy batch, use the <em>model_sizes </em>function, don’t mentioned in the document but you will find it in the fastai source code.</p><blockquote># Dummy batch to get the output size after each level<br>m_sizes = model_sizes(body, (224,224))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*YokHVjZXYROLphx1jq8HZA.png" /></figure><p>Get the location:</p><blockquote># Get the list where output size changes<br>list_idx = [i for i,x in enumerate(m_sizes) if i&lt;len(m_sizes)-1 and not(x == m_sizes[i+1])]<br>list_idx.append(len(m_sizes)-1)</blockquote><p>The final list of interesting layer is : [2, 4, 5, 6, 7]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_rEVOHdg_nASCSGMHRUYA.png" /></figure><p>The hook is the fastai/pytorch way to get an ouput from a middle-layer.</p><p>The layer weights for style losses are human input based on fast experiment by running the training few times and print all the losses. Rule of thumb: try to make these losses magnitude are close.</p><h3>Implementation</h3><p>My github notebook:</p><p><a href="https://github.com/nguyenv7/ipynb/blob/master/superres-featureLoss-resnet-preTrain_Imagenet.ipynb">https://github.com/nguyenv7/ipynb/blob/master/superres-featureLoss-resnet-preTrain_Imagenet.ipynb</a></p><p>One more detail about the Gram matrix function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*b1_vAT_yf4y6ONE-afYlyg.png" /><figcaption>Gram matrix function</figcaption></figure><p>The @ is matmul operator and when the input is the tensor is the batch matrix multiplication. Basically, keep the first dimension as the batch dimension and do multiplication for the rest.</p><p><a href="https://kite.com/python/docs/torch.matmul">https://kite.com/python/docs/torch.matmul</a></p><h3>Conclusion:</h3><ul><li>With Resnet: doing less training (half training time/steps) and still get a good result as expectation.</li><li>Using fastai if you not yet. Some of our work uses fastai elements, work well on the Aws lambda + opencv.</li></ul><h3><strong>REFERENCE</strong>:</h3><p>As one of the fastai follower from the Jeremy first practical machine learning to deep learning courses, a lot of learning and inspirations from him. This DIY deep learning experiment based on his latest online course, and spent 3 hours of coding and experiment in summer 2019. Maybe you need to modify a bit to run for the new fastai version. The reference source code here:</p><p><a href="https://github.com/fastai/course-v3/blob/master/nbs/dl1/lesson7-superres.ipynb">https://github.com/fastai/course-v3/blob/master/nbs/dl1/lesson7-superres.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79b469aa5bd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/superresolution-by-unet-and-customized-feature-loss-79b469aa5bd3">SuperResolution by Unet and customized feature loss</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricted Boltzmann Machine, a complete analysis. Part 3: Contrastive Divergence algorithm]]></title>
            <link>https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-3-contrastive-divergence-algorithm-3d06bbebb10c?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d06bbebb10c</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[boltzmann-machines]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 22:10:31 GMT</pubDate>
            <atom:updated>2020-01-09T22:10:31.079Z</atom:updated>
            <content:encoded><![CDATA[<p>This post will be a bit heavy math as usually it is hard to find a concrete writing to explain every steps of Contrastive Divergence algorithm for RBM. But the probabilistic machine learning will be more appealing for you after reading this. Just another practice!</p><p>Job to be done:</p><ul><li>As RBM contains latent variables, we need to add them to the probability distribution and loglikelihood function.</li><li>RBM energy function, probability distribution</li><li>RBM’s likelihood function and its derivative.</li><li>Constractive Divergence algorithm.</li><li>Relationship with modern algorithms.</li></ul><h3>Latent variables models</h3><p>In order to capture diﬀerent dependencies between data visible features, the Restricted Boltzmann Machine introduces hidden variables. For example, in a set of documents, the hidden variables describe diﬀerent abstract “topic” of them.</p><p>When including latent variables, the marginal distribution of input features is the sum of the join probability of visible features and each hidden variable. Denote the set H = (h_1,h_2,…,h_n) include n hidden variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*G2qdqsnAUY9qZCo38MX61A.png" /><figcaption>Equation 10: marginal distribution of latent variable models.</figcaption></figure><p>In the energy based model for Gibbs distribution of an MRF, the equivalent form of Equation (10):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*3MUeutBoKq2YeuX7bLa2ng.png" /><figcaption>Equation 11: marginal distribution in term of energy function</figcaption></figure><p>where the partition function Z =sum(exp(−E(x,h))) with all possible x, h.</p><h4>Log likelihood</h4><p>When the associating with model parameters θ, the log likelihood with hidden variables is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFYiE8k_b6woHalQfVio2g.png" /><figcaption>Log likelihood of latent variable based models</figcaption></figure><h4>Derivative of the log likelihood</h4><p>To apply the gradient ascent method to ﬁnd θ, we need to take the derivative of L with respect to θ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*EPyR4RtWPTlm0h5hwMRD9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ggeu-cNNnxKl_Rq9E4rkow.png" /></figure><p>As</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*mms1cswfJ8q6WLIqIjPp-g.png" /></figure><p>and following the Bayesian rule, then the ﬁnal derivative form of the log-likelihood is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*N5UixismqZMuDuR_msOHOg.png" /><figcaption>Equation 14. Derivation of the log likelihood function</figcaption></figure><p>It is a crucial step for latent variable based models definition. What we need to find for the next step for the RBM case:</p><ul><li>Definition of the energy function E for RBM.</li><li>The derivation of E(x,h) according to model parameters.</li></ul><h3>Modeling the Restricted Boltzmann Machine</h3><h4>Energy function</h4><p>An energy based model: In Figure 1, there are m visible nodes for input features and n hidden nodes for latent features. We solve the binary RBM first, when the random variables value in (x,h) ∈ {0,1}. There are <em>m </em>input features for x and <em>n </em>hidden variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*1tcPl0YrLxpvHSmT9J0dSA.png" /><figcaption>RBM energy function</figcaption></figure><p>where the real weight <em>w_ij </em>associated with the edge connects visible node <em>x_j </em>to a hidden node <em>h_i</em>. Also each visible node <em>x_j </em>has a real bias value <em>b_j</em>, and a bias <em>c_i</em> for each <em>h_i</em>, respectively. This energy function E(v,h) returns a scalar energy value for each conﬁguration of model parameters θ = {W,B,C}where W = {<em>w_ij</em>},B = {<em>b_j</em>},C = {<em>c_i</em>}; ∀i ∈{1,2,n}, j ∈{1,2,m}.</p><p>An important property of RBM is there are no connection between nodes in the same layer, then the latent variables are conditionally independent given input features and vice versa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*E7yy2SjDRJUMmClPSd0Flg.png" /></figure><h4>Taking the derivative</h4><p>The ﬁnal step to deﬁne the optimization procedure for binary RBM is ﬁnding its derivative for the log-likelihood function as equation 14. For example: the derivation with respect to a weight <em>w_ij </em>that connects hidden nodes <em>i</em> to a visible <em>j</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*-E5kLuLjktDLtB3pfDIRKw.png" /></figure><p>The ﬁrst term can be rewrite shorter as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*aujV6LUfmTciJMAzPXR6hg.png" /></figure><p>As sum of all <em>h_i</em> over p(<em>h_i</em>|x) = 1 and remember that <em>h_i</em> is binary or <em>h_i</em> in {0, 1}. Then, the derivative of log likelihood for a sample is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*vkpgIv0haMpmrk1djGJbOQ.png" /><figcaption>Equation 28: Derivation of log likelihood of RBM for one data point</figcaption></figure><p>We apply the same manner to get the derivative for bias term <em>b </em>and <em>c </em>for these nodes or simply adding <em>1^T</em> vector into the weight matrix on both dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*T3uqKQFaVrXCAb0OcQX4pw.png" /></figure><p>For all samples in the dataset L, this quantity become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*sXb2eRM3kXT2KgS2g8AEog.png" /></figure><p>where <em>q(x)</em> is the empirical distribution of visible features given dataset L, then <em>p(h|x)q(x)</em> is the <strong>empirical distribution </strong>of all model variables on given dataset. While <em>p(h,x)</em> is the<strong> model distribution</strong> of all possible 2m +2n values of visible and hidden variables. This lead to a general rule as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*H7EjL6ErWok3hsFNR25VBw.png" /><figcaption>Equation 29: Log likelihood derivative as the difference between <strong>empirical distribution</strong> and <strong>model distribution</strong></figcaption></figure><p>This derivation contains the diﬀerent of two exception when <em>x</em> ﬁt into a data and <em>x</em> free. When two terms are matched, the gradient becomes zero and the learning algorithm will stop. In the other hand, the objective of learning algorithm is making the empirical expectation approaches the model expectation.</p><h3>Algorithms</h3><p>Common algorithms for training a RBM model approximates the second expectation term in Equation (28) to do the gradient ascent step. The ﬁrst proposed algorithm utilizes simulated annealing [1] and [2] uses mean ﬁeld approximation to evaluate the gradient. Another approach is using the MCMC methods to approximate this gradient, but it requires many steps until reaching the equilibrium state. However, these algorithms are ineﬃcient in term of getting fast and accurate approximation.</p><p>The ﬁrst eﬃcient algorithm is Contrastive Divergence (CD) [3] which is a standard way to train a RBM model nowadays.</p><p>The idea is running <em>k</em> steps Gibbs sampling until convergence and k = 1 typically. This applies to the gradient for one sample (Equation (28)) and doing <em>k</em> time sampling as follow: at the time <em>t</em>, sampling <em>h^t</em> ∼ <em>p(h|x^t)</em> and sampling <em>x^t+1 ∼ p(x|h^t) </em>subsequently. Or simply:</p><ul><li>Sampling hidden variable values <em>h</em> from sampling visible variables <em>x</em> at time <em>t</em>.</li><li>Use these just sampling hidden variables <em>h</em> to generate the visible variables <em>x </em>data again.</li></ul><p>Then, the approximation form of Equation (28) is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*qgWg0xQCAGIRLJEZBE4Pvw.png" /></figure><p>where <em>x^0</em> is the original input vector or at time 0 and <em>x^k</em> is generated from RBM model at time <em>k</em>. Thanks to the hidden variables are independent given visible variables and vice versa, we can do the sampling for them in parallel in each layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTjshebBBewxyXQMGqiA3g.png" /><figcaption>Gibbs sampling for RBM, reproduce from Figure 27.31 of [4]. By stepwise sampling, from a vector, generating a corresponding latent vector and repeatedly doing until reaching the equilibrium state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqpcTliuNQkP5-zCaM2T1w.png" /><figcaption>One step Contrastive Divergence Algorithm</figcaption></figure><p>By processing one sample a time, taking and follow the gradient direction, this algorithm follows the Stochastic Gradient family of algorithms. The advantages of this approach is clearly visible in a large dataset, when it needs to compute the sum gradient for all data samples which tremendously expensive cost in conventional gradient methods. Thanks to this property, the RBM method is quite suitable for large scale machine learning problem.</p><h4>Sampling distribution</h4><p>What distribution to sampling from distribution <em>p(h|x)</em> and <em>p(x|h)</em>?</p><p>Due to <em>x_l </em>∈ {0,1} it belongs to the Bernoulli distribution and we only need to ﬁnd the conditional distribution of a particular <em>x_l</em> given the rest of <em>x</em> expect <em>l th </em>index and <em>h</em>: <em>p(x_l = 1|x_(−l),h)</em>. We denote that the set of all visible variables expect <em>l</em> is <em>x_(−l) = {x_1,x_2,…,x_(l−1),x_(l+1),…x_m}</em>. Then, the energy function can be rewrite as the function of <em>(x_l,x_(−l),h)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOH2S8yRcocHK1M_jeqKXA.png" /></figure><p>It is important to group terms to <em>E_2 </em>function as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*aUjRbKQetgbhyNAdSQLsrw.png" /></figure><p>Then the <em>p(x_l = 1|x_(−l),h)</em> derivation follow the Bayes rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zqkNAXuTd0xoBJCZLInyQ.png" /></figure><p>Clearly, it is the sigmoid function form, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*_CnhgLghvX7B-tHVpMdrFA.png" /></figure><p>Then the ﬁnal probabilistic model for visible and latent variables show that they are only depended on adjacent nodes state and its bias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*iKLD9XXNKX5qziGsyZRQMw.png" /></figure><p>where Ber stands for Bernoulli distribution, as we as in the binary RBM.</p><h3>Relationship with modern algorithms.</h3><p>Clearly, the RBM is both generative and unsupervised model.</p><h4>A generative model</h4><p>It is the most interesting part of RBM when they can generate both visible and hidden layers by sampling from distribution. After that, the information to update model parameters is the difference between ‘<strong>generated</strong>’ and ‘<strong>real</strong>’ data. Immediately, the links to these algorithms are clearly visible: Variational auto-encoders (VAE) and <a href="https://en.wikipedia.org/wiki/Generative_adversarial_network">Generative adversarial network</a> (GAN).</p><p>Or in more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*8IUwNLmZthELKzuA.png" /><figcaption>Taxonomy of generative models based on the tractability of the density distribution. Adapted from Ian Goodfellow, Tutorial: Generative adversarial networks. <a href="https://www.semanticscholar.org/paper/Deep-generative-models%3A-Survey-Oussidi-Elhassouny/64a1e4d18c2fab4904f85b3ee1a9af4263dae348/figure/7">https://www.semanticscholar.org/paper/Deep-generative-models%3A-Survey-Oussidi-Elhassouny/64a1e4d18c2fab4904f85b3ee1a9af4263dae348/figure/7</a></figcaption></figure><p>Some differences in the density setup, or number of latent layers, architecture among these above algorithms. It is about:</p><ul><li>What your algorithm want to capture: latent space modelling, direct optimize the likelihood…</li><li>How you the interested distribution setup:</li><li>How to sampling from distribution: MCMC, Gibbs, over the neural network</li><li>How your loss function to close the relation between actual and generated data from distribution.</li></ul><p>Usually, these papers are quite short or complicated mathematical models as the audience for researchers people. This binary RBM posts try to have a clear explanation for a original, simple enough case to approach these new algorithm. Essentially, they are the same, just we need to learn more in the right way.</p><h4>REFERENCE</h4><p>[1] David H Ackley, Geoﬀrey E Hinton, and Terrence J Sejnowski. A learning algorithm for boltzmann machines. Cognitive science, 9(1):147–169, 1985.</p><p>[2] Hilbert J. Kappen and Francisco de Borja Rodr´ıguez. Eﬃcient learning in boltzmann machines using linear response theory. Neural Computation, 10(5):1137–1156, 1998.</p><p>[3]Geoﬀrey E. Hinton. Training products of experts by minimizing contrastive divergence. Neural Computation, 14(8):1771–1800, 2002.</p><p>[4] Kevin P Murphy. Machine learning: a probabilistic perspective. MIT press, 2012.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d06bbebb10c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-3-contrastive-divergence-algorithm-3d06bbebb10c">Restricted Boltzmann Machine, a complete analysis. Part 3: Contrastive Divergence algorithm</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricted Boltzmann Machine, a complete analysis. Part 2: A Markov Random Field model]]></title>
            <link>https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-2-a-markov-random-field-model-1a38e4b73b6d?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a38e4b73b6d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[boltzmann-machines]]></category>
            <category><![CDATA[graphical-model]]></category>
            <category><![CDATA[markov]]></category>
            <category><![CDATA[maximum-likelihood]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 15:00:14 GMT</pubDate>
            <atom:updated>2020-01-07T15:03:49.610Z</atom:updated>
            <content:encoded><![CDATA[<p>This second post of the Restricted Boltzmann Machine is to explain about its core properties and establish fundamental tools/knowledge to solve it. We will see these things:</p><ul><li>Restricted Boltzmann Machine is a Markov Random Field model.</li><li>Markov Random Field is a graphical model.</li><li>What is graphical model? Why they exist?</li><li>Markov Random Field definition.</li><li>Why Restricted Boltzmann Machine is a Markov Random Field model ?</li><li>How to solve/ find parameters for a Markov Random Field model from data?</li></ul><p>The motivation of this writing is how to solve a RBM from beginning and throughout all formulations to build it. Nowadays, we can simply write a model in Pytorch or Tensorflow, use auto-gradient feature, and built-in gradient descent functions to solve it.</p><p>Of course, this is the best way to solve common problems that has big data, or easy to collect the data. But if you got the close form of the loss function’s derivative, everything will be thousand times faster.</p><ul><li>Transfer learning only works for well-developed application domains: computer vision, natural language processing.</li><li>Things usually getting better if you can put your prior knowledge about the data/problem into the algorithms. Understanding and using principle algorithms along newest AI frameworks is the best way to speedup training time and accuracy. I apply this principle to our work daily and it is really effective.</li></ul><p>I keep stuff in this writing is simple as much as possible in term of math, focus more in the reason why we need them and my personal experiences.</p><h3>Restricted Boltzmann Machine properties</h3><p>Let back on the main formula. Recall that:</p><ul><li>x is the data generated by the model</li><li>h is the latent variable: n hidden units including h_1, h_2, … h_n to capture the dependencies between observations features</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*unNKnICiENdeDt-bh7ukZQ.png" /></figure><h4>Why restricted?</h4><p>RBM is the special case of <a href="https://en.wikipedia.org/wiki/Boltzmann_machine">Boltzmann Machine</a>, the term “restricted” means there is no edges among nodes within a group, while Boltzmann Machine allows.</p><h4><strong>A Markov Random Field model</strong></h4><p>Markov Random Fields (MRF) is a class of probabilistic <a href="https://en.wikipedia.org/wiki/Graphical_model">graphical model</a> for undirected graphs of random variables that have Markov property. RBM is also a speciﬁc MRF model that form by a bipartite graph.</p><h4>What about the Graphical Model?</h4><p>From the observation that complex systems is the combination of simple parts [1], graphical models utilizes the probabilistic and graph theory to capture this property.</p><ul><li>The graph nodes represent random variables and edges show the dependence between these variables.</li><li>The graph theory gives the data structure for encoding the factorization of information or the independence between sets of variables.</li><li>The probabilistic property ensure how parts interact or combine to build the model, and provide the inference procedure.</li><li>Thus the probabilistic side guarantees the capability of uncertainty modeling and graph theory handles the complexity.</li></ul><p>From [1], it is a natural way to design a new system in solving problems in engineering. Many famous algorithms in machine learning, for example: Navie Bayes, Hidden Markov Models, Conditional Random Fields are graphical models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*iOOhwhybq9kDtcmACACyvQ.png" /><figcaption>Graphical models in a nutshell. <strong>From</strong>: Sutton, Charles, and Andrew McCallum. ”An introduction to conditional random ﬁelds.” Foundations and Trends in Machine Learning 4.4 (2012): 267–373</figcaption></figure><p>At this point, we already see the connection of RBM to other class of algorithms and the brief introduction about them. Then:</p><ul><li>The way to solve a MRF algorithm is the way to solve the Restricted Boltzmann Machine.</li></ul><h3>Markov Random Fields</h3><p>It takes ages to explain in detail about the MRF. Simply, I will explain the basic of MRF, why RBM is a MRF, tools from MRF to solve the RBM: Energy Function and MRF Inference.</p><p>A Markov Random Fields is a set of random variables that is satisfy the Markov properties in undirected graph. To be simple, the Markov properties formulates the dependencies among random variables and this dependencies are <strong>conditional independent </strong>in term of pair of variables, local set of variables, and variable subset.</p><ul><li><em>Pairwise Markov property</em>: Two un-adjacency random variables Xu,Xv are conditionally independent given all variables.</li><li><em>Local Markov property</em>: A variable Xv is conditionally independent with all other variables given its neighbors Nv.</li><li><em>Global Markov property</em>: Given three subsets: A,B,S ∈ V , if all paths from a vertex from A to another one in B need to pass through S. Then variables in set A is independent of its peers in set B given S.</li></ul><h4>Why <strong>conditional independent?</strong></h4><p>The biggest benefit is the reducing model complexity, less number of variables and terms thanks to the conditional independent.</p><p>For examples: a simple Bayesian network with 3 random variables: X1,X2,X3 and the join probability derivation of them by chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*IUvxgu71hsmD8gJt1SjFRw.png" /><figcaption>Join probability without conditional independent</figcaption></figure><p>If we apply the structure of the network that a variable only depends on its parents and independent with others given their parents. The factorization gives the shorter join probability formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*6DbWOysIpSjl0JT2MUNcKg.png" /><figcaption>Join probability with conditional independent</figcaption></figure><p>Indeed, not only shorter formulas, we need less parameters to store the join distribution: 2 + 2 + 1 vs 2³ − 1.</p><h4><strong>Why RBM is a MRF?</strong></h4><p>There is no inner connection between nodes in the hidden layer, they are conditionally independent given the observed features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*Niv4Qsfx6QWSQCEnXaugbg.png" /></figure><p>Then the RBM satisfies all Markov properties and itself undirected graph leads to RBM is a MRF model.</p><h4>Energy Function</h4><p>In the <a href="https://en.wikipedia.org/wiki/Hammersley%E2%80%93Clifford_theorem">Hammersley-Cliﬀord theorem</a>, a positive distribution p(x) &gt; 0 assures Markov properties of an undirected graph G <strong>iﬀ </strong>p factorizes over G as product of factors, each factor represents one maximal clique. It’s worth to mention that a clique is a complete subgraph (subset of vertices form a complete graph).</p><p>A maximal clique C is associated with a <em>nonnegative potential function</em> ψC. Then the probability distribution of a Markov Random Field can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*TS1YH7N9DneL183EOUm5PQ.png" /></figure><p>The denominator Z stands for normalization constant, is called parition function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*p5YqpzR50w0R9BHT5ff-bg.png" /></figure><p>Or (4) equivalent with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOrZKPFEmbkpb0uLuTuR-Q.png" /></figure><p>where people call E(x) is the <strong>energy function</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*HV6kjcUlDCit54U0fwgbEA.png" /></figure><p>In particular, this type of energy based function in Equation (6) is known as the Gibbs distribution which is commonly used in physics. The function E(x) &gt; 0 indicates the total energy of a variable conﬁguration associated inside cliques. Obviously, the higher probability for p(x) corresponding to low energy E(x).</p><p>A simple recap:</p><ul><li><a href="https://en.wikipedia.org/wiki/Hammersley%E2%80%93Clifford_theorem">Hammersley-Cliﬀord theorem</a> provide a theory background to formulate the Markov Random Field.</li><li>According to this we can formulate the probability distribution of a MRF under cliques.</li><li>Assign a non-negative potential function for each clique and takes product of them</li><li>As the properties of sum-log and products functions, we got the energy function for the probability distribution in exponential function form or Gibbs distribution.</li></ul><h4>MRF inference</h4><p>Given a dataset L including l samples: L = {x(1),x(2),…,x(l)} with the assumption that these data samples are generated from the same distribution and independent with others (i.i.d).</p><p>The inference task is ﬁnding a parameters setting for the probabilistic model to capture the underlying data distribution. Particularly, after the structure of a MRF is identify, the energy function is associated with a parameters set θ, and the inference is adjusting θ.</p><p>For each data point x, the likelihood for x is generated from a probabilistic model with the set of parameters θ is p(x|θ). In inference a graphical model, when the structure is known and all data observation is available, the learning phase uses the maximum likelihood criteria for ﬁnding parameters θ. The <strong>log-likelihood function</strong> for all samples in a dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Npe3mu7iI9DDIusMMvlV8A.png" /></figure><p>As there is no close form analytical solution for maximum the likelihood, we use the gradient ascent method on the log-likelihood function to solve it. Generally, the gradient ascent is iterative ﬁrst order method to ﬁnd the local optimum of given objective function. In order to seek the maximum objective value, it moves proportionally to the positive gradient direction in each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*CNLoyWA841QavYpf9Tusjw.png" /></figure><p>where α is the learning rate or the proportion of moving and θt is the current values of θ at time t.</p><p>At this point we already know:</p><ul><li>The definition of MRF probability distribution p(x) in term of E(x): energy function.</li><li>Target to maximum likelihood of parameters given data p(x|θ).</li><li>Solving by gradient ascent.</li></ul><h4>REFERENCE:</h4><ul><li>[1] Michael Irwin Jordan. Learning in graphical models, volume 89. Springer Science &amp; Business Media, 1998.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a38e4b73b6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-2-a-markov-random-field-model-1a38e4b73b6d">Restricted Boltzmann Machine, a complete analysis. Part 2: A Markov Random Field model</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricted Boltzmann Machine, a complete analysis. Part 1: introduction & model formulation]]></title>
            <link>https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-1-introduction-model-formulation-1a4404873b3?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a4404873b3</guid>
            <category><![CDATA[probabilistic-modelling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rbm]]></category>
            <category><![CDATA[deep-belief-network]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 21:06:40 GMT</pubDate>
            <atom:updated>2018-09-12T21:06:40.102Z</atom:updated>
            <content:encoded><![CDATA[<p>Someday ago, my colleague asked me about RBM algorithm and what is the difference vs other learning algorithms. It is really interesting about this algorithm as Netflix used it along with SVD in their <a href="https://medium.com/netflix-techblog/netflix-recommendations-beyond-the-5-stars-part-1-55838468f429">product</a>. Last year, RBM already took me a month to understand fully about it in term of theory and practice.</p><p>This serial of articles is dedicated to shortly writing my analysis along with demo source code for RBM. This analysis is a detailed story about why the RBM created, which assumption, which way to solve, formulas to get to the final algorithm. I usually find that RBM papers typically come up to use the final formula and build on the top, which is hard to accept and understand for high curiosity people like me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Z-uEtQkFPk7MtbolOSUvrA.png" /></figure><h3>RBM Timeline</h3><p>Let talk some historical aspect. Firstly, Restricted Boltzmann Machine is an undirected graphical model that plays a major role in Deep Learning framework nowadays. It is a relaxed version of Boltzmann Machine.</p><ul><li><strong>1986</strong>: was introduced as Harmonium. <em>Paul Smolensky. Information processing in dynamical systems: Foundations of harmony theory. Technical report, DTIC Document, 1986</em></li><li><strong>2001</strong>: fast approximated inference algorithm 1 as Contrastive<br>Divergence (CD). <em>Geoffrey E. Hinton. “Training products of experts by minimizing contrastive divergence”. In: Neural Computation 14.8 (2002)</em></li><li><strong>2007</strong>: first application (collaborative filtering ) for big data<br>(Netflix movie rating) . <em>Ruslan Salakhutdinov, Andriy Mnih, and Geoffrey E. Hinton. “Restricted Boltzmann Machines for Collaborative Filtering”. In: International Conference on Machine Learning (2007)</em></li><li><strong>2006 → 2010</strong>, stacked RBM models to Deep Belief Network. <em>Geoffrey E Hinton and Ruslan R Salakhutdinov. “Reducing the Dimensionality of Data with Neural Networks”</em></li><li><strong>2010</strong> → now: slow down due to the superior of other DL<br>frameworks, use for initializing networks parameters.</li></ul><p>Briefly, it is a <strong>Swiss army</strong> <strong>knife</strong>, a probabilistic model, also finally figure out to include the sigmoid unit (non-linearity). Moreover, it is a clustering algorithm thanks to binary hidden factor. Then, it is a probabilistic model to capture the data distribution, nonlinear factor analysis, clustering algorithm, nonlinear data representation.</p><p>In term of practice, it is a very fast learning algorithm, short implementation, handle binary, real input data, even for missing values input vector. Follow that, numerous applications of RBM was found in</p><ul><li>Dimensional reduction: <em>Geoffrey E Hinton and Ruslan R Salakhutdinov. Reducing the Dimensionality of Data with Neural Networks\r. Science, 313(5786):504–507, 2006.</em></li><li>Collaborative filtering: <em>Ruslan Salakhutdinov, Andriy Mnih, and Geoffrey E. Hinton. Restricted Boltzmann Machines for Collaborative Filtering. International Conference on Machine Learning, pages 791–798, 2007.</em></li><li>Classification: <em>Hugo Larochelle and Yoshua Bengio. Classification using discriminative restricted Boltzmann machines. ICML, pages 536–543, 2008</em></li></ul><p>In 2007, the first application of RBM that can handle big-data millions user ratings in Netflix competition, to model and predicts user preference on movies. In the period of 2006 to 2010, Deep Belief Network was invented by stacking multiple RBM models in order to build higher “abstract” data representation. It is the time people really get into the “deeper” model structure.</p><p>At this point, we clearly see the need of understanding RBM algorithm: the <strong>revenge</strong> for deep learning.</p><h3>RBM: model definition</h3><p>Usually, in high dimensional data, there may only some small number of degrees that explain/embedded most of the data variance, according to latent factors. For example, among a thousand face images, some underlying latent factors are gender, lighting condition, posing, emotions. One way to find these latent factors is the manifold learning, can be done through one of my favorite algorithms: Locally Linear Embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*_QLZCKe9c65Psg__.gif" /><figcaption>Locally Linear Embedding example. <a href="https://cs.nyu.edu/~roweis/lle/faces.html">https://cs.nyu.edu/~roweis/lle/faces.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*mTCEhV3NvBMc-BbR.png" /><figcaption>Density Estimation for a Gaussian mixture. <a href="http://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_pdf.html">http://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_pdf.html</a></figcaption></figure><p>In modelling complex and high dimension data distribution, a popular probabilistic approach is using the mixture model, a typical algorithm is the Gaussian Mixture Model (GMM). In this GMM model, the assumption is all data points are generated by a mixture of Gaussian models.</p><p><strong>Instead of</strong> modelling the sum of mixture models liked in GMM, RBM takes the product of simple Bernoulli distribution or “product of experts”, the aim to inference shaper posterior distribution (according to Hilton paper). In Figure 1, RBM contains two layers of units, the visible units from <em>x_1 , x_2 , . . . x_m</em> stand for <em>m</em> data input features, and the <em>n</em> binary hidden units including <em>h_1 , h_2 , . . . h_n</em> to capture the dependencies between observations features. According to this figure, each <em>h_i</em> models a particular dependency or relation of features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*BNXpECThn7Ki3x9qRBSb5w.png" /><figcaption>From my writing</figcaption></figure><p>Although the RBM structure looks like two layers neural network, RBM has a closed-form representation of data distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*pX5D8l6LJUIoXgb9z6aE_g.png" /></figure><h3>Recap:</h3><ul><li>RBM is a long history and influenced algorithm.</li><li>2 layers model: input and hidden layer, both of them originally binary (follow the Bernoulli distribution)</li><li>The data representation is as the product of hidden nodes.</li><li><strong>Swiss army knife</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a4404873b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/restricted-boltzmann-machine-a-complete-analysis-part-1-introduction-model-formulation-1a4404873b3">Restricted Boltzmann Machine, a complete analysis. Part 1: introduction &amp; model formulation</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow — day 1+2: High level APIs]]></title>
            <link>https://medium.com/datatype/tensorflow-day-1-2-high-level-apis-2a79286366c4?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a79286366c4</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Thu, 15 Feb 2018 13:48:58 GMT</pubDate>
            <atom:updated>2018-02-15T13:48:58.267Z</atom:updated>
            <content:encoded><![CDATA[<p>After 2 days of starting to touch the Tensorflow framework. I am starting to write my experience recap. Of course, it follows the tutorial of tensorlow but I try to make figures and important points for new comers as me (simple/easier to understand).</p><h4>Installing the simple way</h4><p>Anaconda2 + Python 2.7 is my choice as installing in Anaconda create a isolate environment, any update or remove packages will not affect python libraries. Moreover, I also enjoy the newest Jupyter version.</p><p>Currently, the default version of Tensorflow is 1.4. In order to run all official tutorial of Tensorflow, we need the Tensorflow 1.5 → just upgrade.</p><p>In my case of Ubuntu, Python 2.7, use GPU, already have Tensorflow 1.4 by default of Anaconda2. Quite simple one command.</p><pre><strong>pip install --ignore-installed --upgrade \<br></strong>https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.5.0-cp27-none-linux_x86_64.whl</pre><p>But the CUDA 9.1 is the lastest drive version, if you install Tensorflow 1.5, it only can use CUDA 9.0. Remember to downgrade/relink the Cuda and recheck by</p><pre>nvcc --version</pre><h4>Follow the first tutorial of Tensorflow in offical website</h4><p>I follow this link</p><ul><li><a href="https://www.tensorflow.org/get_started/premade_estimators">Getting Started with TensorFlow</a>, which is aimed at readers who have experience in machine learning.</li><li>All source code of this tutorial is in: <a href="https://github.com/tensorflow/models/blob/master/samples/core/get_started/">https://github.com/tensorflow/models/blob/master/samples/core/get_started/</a></li></ul><p>However, It is a bittle tedious to learn a new framework (coding style) by try to run it by the command line and start to read the source code.</p><ul><li>I already port the source code of <strong>premade_estimator.py </strong>to parts into Jupyter notebook. Of course, the results are similar but we can run parts sepearately and see what variables inside.</li><li>For lazy memorizer, you can take a look at: <a href="https://github.com/nguyenv7/tensor-flow/blob/master/tensorflow_iris.ipynb">https://github.com/nguyenv7/tensor-flow/blob/master/tensorflow_iris.ipynb</a></li></ul><p>Briefly, this tutorial shows how to classify 3 types of iris flowers (Setosa, Versicolor. Virginica) in the legendary Iris data. This data contains 120 training and 30 testing samples, respectively. Each data sample is described by 4 features: sepal length, sepal width, petal length, and petal width. Finally, the classifier is created by two layers dense network.</p><p>This tutorial will try to make a simple explaination for provided source code. Of course, it is coded in high-level Tensorflow APIs, so we will get to know the premade estimator and compare with the custom estimater coding approach.</p><h4>Tensorflow notices</h4><p>Firstly, Tensorflow frameworks will <strong>DEFINE FIRST, RUN LATER</strong>.</p><ul><li>All variables definition, computational operators are need to be defined first. There are no returning values if calling them as in Numpy or Python.</li><li>The execution step will feed the data into the model definition, run it, and return the output.</li><li>In the high level api, you don not need to consider explicit numbers training samples, matrix/tensor size in neural network layers. Tensorflow will do/arrange it automatically. You need to input the <em>hyper</em> — parameters such as batch-size, training steps, hidden units number.</li><li>All input data need to be transform/casting into the “tensor” form. Luckily, the <em>tf.feature_column</em> also provide functions to transform categorical/other kind of input features to numeric/hashed data.</li></ul><p>Secondly, there are 3 core structure to make the input Tensor to follow our navigation:</p><ul><li><em>tf.data.Dataset</em>: take the raw data and produce “Tensor” datatype.</li><li><em>tf.feature_column</em>: a general input feature handle, to transform many kind of input data, inform its type to the machine learning model to make sure the model is unchanged to handle new input data.</li><li><em>tf.estimator</em>: model definition and do the train/evaluate/predict the model.</li></ul><p>If defining that Food = Data, Box = Tensor, Food type = data type, then this figure describes the relation among them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*QIL8egnfoG3rIwHxSWWv3g.png" /><figcaption>The relation of 3 main Tensorflow structure</figcaption></figure><h4>[premade_estimator.py] Analyses the program flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*p0OH-7By63vPKnod2trdew.png" /><figcaption>[premade_estimator.py] Running flow chart</figcaption></figure><p>There are 3 main steps, clearly only the <em>tf.estimator</em> involve in two.</p><ul><li>Data pipeline</li><li>Model definition</li><li>Model execution</li></ul><p>Take a lot at the <strong>Data pipeline</strong>, after get the whole data in tuples, we need to process into the training ( <em>train_input_fn()</em>)<em> </em>or testing data (<em>eval_input_fn()</em>).</p><pre>(train_x, train_y), (test_x, test_y)</pre><p>The <em>train_input_fn()</em> takes the <em>(train_x, train_y, args.batch_size)</em> as input. Obviously, <em>tf.data.Dataset.from_tensor_slices</em> plays the most important role to create <em>TensorSliceDataset</em> from a <em>dict</em> of features (<em>train_x</em>). As the train data is 120 samples, we need to <em>repeat</em> it to get enough data for batches.</p><pre>#Source: #<a href="https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py">https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py</a></pre><pre>def train_input_fn(features, labels, batch_size):    <br>&quot;&quot;&quot;An input function for training&quot;&quot;&quot;    <br># Convert the inputs to a Dataset.</pre><pre>dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))     </pre><pre># Shuffle, repeat, and batch the examples.    <br>dataset = dataset.shuffle(1000).repeat().batch(batch_size)   <br> <br># Return the dataset.    <br>return dataset</pre><p>The <em>eval_input_fn() </em>is almost the same, except it needs to declare whether the data label is available or not. This aims for the case of predicting labels for new data or simply for the testing purpose (of course data labels are provided). As no training in this step, no need for shuffle or batch the data.</p><pre>#Source: #<a href="https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py">https://github.com/tensorflow/models/blob/master/samples/core/get_started/iris_data.py</a></pre><pre>def eval_input_fn(features, labels, batch_size):    <br>&quot;&quot;&quot;An input function for evaluation or prediction&quot;&quot;&quot;</pre><pre>features=dict(features)    </pre><pre>if labels is None:       <br># No labels, use only features.        <br>    inputs = features    <br>else:        <br>inputs = (features, labels)     </pre><pre># Convert the inputs to a Dataset.   <br>dataset = tf.data.Dataset.from_tensor_slices(inputs)     </pre><pre># Batch the examples    <br>assert batch_size is not None, &quot;batch_size must not be None&quot;<br>dataset = dataset.batch(batch_size)     </pre><pre># Return the dataset.   <br>return dataset</pre><p><strong>Model definition</strong>: The high level APIs with premade models from Tensorflow makes a simple job for model definition: we need to do 2 steps:</p><ul><li>Tell the type of data input or what inside the boxes, here the input is numeric data, just tell <em>tf.feature_column.numeric_column </em>with the feature names. Look a bit strange, but remember that we already make the <em>dict(features) </em>in the data pipeline. It means the data will be access by the key name (for e.g: <em>train_data[‘PetalLength’]</em> ). Then, along with the feature type, we need to provide its name (or key). Noticed it is the formal definition, no data passing yet.</li></ul><pre># Feature columns describe what is the input look like.<br>my_feature_columns = []<br>for key in train_x.keys():<br> my_feature_columns.append(tf.feature_column.numeric_column(key=key))</pre><ul><li>Call premade Tensorflow classifier, only need to pass <em>my_feature_columns</em> to tell about the feature type and name, and hyper parameters setting.</li></ul><pre># Build 2 hidden layer DNN with 10, 10 units respectively.<br>classifier = tf.estimator.DNNClassifier(<br>    feature_columns=my_feature_columns,<br>    # Two hidden layers of 10 nodes each.<br>    hidden_units=[10, 10],<br>    # The model must choose between 3 classes.<br>    n_classes=3)</pre><p>The <strong>model</strong> <strong>training</strong> part is also short with premade model, the <em>lambda</em> notation allows us to passing input variables to a function (<em>iris_data.train_input_fn</em>) inside a function call (<em>classifier.train</em>). The actual data goes through this step to the model definition and make all of them running.</p><pre># Train the Model.<br>classifier.train(input_fn=lambda:iris_data.train_input_fn(train_x, train_y,args.batch_size),steps=args.train_steps)</pre><p>The <strong>evaluation</strong> part is elegant as well, just calling <em>classifier.evaluate</em></p><pre># Evaluate the model.<br>eval_result = classifier.evaluate(input_fn=lambda:iris_data.eval_input_fn(test_x, test_y,args.batch_size))</pre><pre>print(&#39;\nTest set accuracy:{accuracy:0.3f}\n&#39;.format(**eval_result))</pre><h4>Premade estimater vs Custom estimator</h4><p>Finally, the custom estimator example helps us to understand the whole <em>tf.estimator</em> procedure above. We continue follow the official document from Tensorflow</p><ul><li><a href="https://www.tensorflow.org/get_started/custom_estimators">https://www.tensorflow.org/get_started/custom_estimators</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTPdpEQYt_3JztksWUO9AQ.png" /><figcaption>[custom_estimator.py] Variables flowchart</figcaption></figure><ol><li><strong>Build network structure</strong></li></ol><pre>def my_model(features, labels, mode, params):</pre><pre>net = tf.feature_column.input_layer(features,params[&#39;feature_columns&#39;])</pre><pre>for units in params[&#39;hidden_units&#39;]:        <br>    net = tf.layers.dense(net, units=units, activation=tf.nn.relu)</pre><ul><li><em>tf.feature_column.input_layer</em> makes the <em>Input layer </em>from input data: actual data features and the data ‘schema’ (<em>params[‘feature_columns’]</em>) or our <em>my_feature_columns</em>. It creates the first layer of the <em>net</em> layer with only input data.</li><li><em>net = tf.layers.dense(net, …)</em> is add another layer into the top of the current <em>net</em> layer. As high level APIs, it will automatically arrange the weight matrices and initialization.</li></ul><p><strong>2. Data forwarding</strong></p><pre># Compute logits (1 per class). <br>logits = tf.layers.dense(net, params[‘n_classes’], activation=None)</pre><ul><li>Call <em>tf.layers.dense</em> again to get the network output after fowarding input data through layers. Noticed that the <em>logits </em>are numbers, not the class labels.</li></ul><p><strong>3. Prediction, evaluation</strong></p><p>Active by the mode, for e.g:</p><pre>assert mode == tf.estimator.ModeKeys.TRAIN</pre><p>because we need to define all steps by ourself, but in one function → a need of part-based source code.</p><p>Indeed, as the data forwarding and getting the output firstly, we can use this result for the prediction and evaluation task.</p><pre>predicted_classes = tf.argmax(logits, 1)</pre><ul><li>Convert <em>logits</em> numbers to classes, each sample have 3 logits number (for Iris data according to 3 classes), which classes get the highest <em>logits</em> is the predicted class.</li><li>From the <em>logits</em> we define the <em>loss</em> functions by compare with the input labels. The <em>loss</em> is the criteria for training purpose, get the gradient, backpropagation.</li></ul><pre>loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)</pre><ul><li>We still need to define the evaluation criteria to known the performance of current model with the data.</li></ul><pre># Compute evaluation metrics. accuracy = tf.metrics.accuracy(labels=labels, predictions=predicted_classes, name=’acc_op’)</pre><p><strong>4. Training network</strong></p><p>After getting the <em>loss</em> definition, call a <em>tf.train</em> method, and <em>minimize</em> the loss :)</p><pre># Create training op.    <br>assert mode == tf.estimator.ModeKeys.TRAIN     <br>optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)    <br>train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())</pre><p>The rest source code is quite clear, you can remember by look at the figure.</p><h4>Recap</h4><ul><li>Tensorflow takes longer time to learn and reading the source code. Nevertheless, more well structure, a little bit “strange” logic but define first and run later is more optimal in term of whole data processing pipeline.</li><li>High level APIs provides a lof of flexible to interact/transform data as well as define/run the model.</li><li>It is also easier than Torch and PyTorch in term of GPU, Cuda setup.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a79286366c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/tensorflow-day-1-2-high-level-apis-2a79286366c4">Tensorflow — day 1+2: High level APIs</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeplearning.ai CNN week 4: Special applications]]></title>
            <link>https://medium.com/datatype/deeplearning-ai-cnn-week-4-special-applications-9f9dcdb24bd?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f9dcdb24bd</guid>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 10:42:16 GMT</pubDate>
            <atom:updated>2018-02-08T10:43:16.087Z</atom:updated>
            <content:encoded><![CDATA[<h4>Face recognition/ Neural style transfer application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39ZJRiO6QoH5M6fs7i4lkQ.png" /><figcaption>Terminology clarification. Source: deeplearning.ai C4W4L02</figcaption></figure><h4>One-shot learning</h4><ul><li>Learning from one example to recognize the person again.</li><li>Learning a “similarity” function.</li><li><em>d</em>(img1, img2) = degree of difference between images.</li><li>In certain degree of <em>d </em>value, the verfication works or not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YjZTT6nMqo9C15alXRz0Q.png" /><figcaption>Similarity function definition. Source: deeplearning.ai C4W4L02</figcaption></figure><h4>Siamese Network</h4><ul><li>Utilize the Convolutional network for transform the input to feature. Doing this by remove the final softmax layer for classification, keep the layer of “128” nodes.</li><li>Each input will be represented by a feature vector after passing this network.</li><li>Then the difference function is defined as: d(x¹, x²) = || f(x¹)- f(x²) ||²_2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3_EyZS63hf1G0QK8g_M1w.png" /><figcaption>Siamese network structure. Source: deeplearning.ai C4W4L03</figcaption></figure><ul><li>f(x^i) is length of 128</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dG87DeVj0TBaPfDT9oI0DQ.png" /><figcaption>Training target of the Siamese network. Source: deeplearning.ai C4W4L03</figcaption></figure><h4>Triplet loss</h4><ul><li>Look at 3 images in a time.</li><li>Small distance between “anchor” (A) and “positive” (P) image, large distance with the “negative”(N) image.</li><li>But of f(x) is 0, the condition is always satisfy → adding the margin variable (alpha) to keep the equation not return the trivial solution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jkZ3w7BGa9GSXGSvfPlsg.png" /><figcaption>Learning objective. Source: deeplearning.ai C4W4L04</figcaption></figure><ul><li>Need the loss as small as possible, or the similarity of A and P plus the margin (alpha) need to be bigger than the similarity of A and N</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7ac8x6T4YvbNY715DKATg.png" /><figcaption>Source: deeplearning.ai C4W4L04</figcaption></figure><ul><li>Choosing the triplet A, P, N training images is difficult</li><li>Need to choosing the “tough” triplet to train on, to make the gradient descent algorithm to work, otherwise the network weight is no change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_Ap38Z8LGb85o9KdY5Dew.png" /><figcaption>Choosing the triplet. Source: deeplearning.ai C4W4L04</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgnWPujehMMUkzC84VGwgQ.png" /><figcaption>Training data for the triplet loss example. Source: deeplearning.ai C4W4L04</figcaption></figure><ul><li>Typically, companies use a very large face images data for training the Siamese network.</li></ul><h4>Face Verification</h4><ul><li>The previous triple loss part for training the representative/ encoding space that can well discriminate images of different people and vice versa.</li><li>The final part is use this encoding to return the final prediction.</li><li>Turn the similarity function to the network based function.</li><li>Adding one final node to return the binary response for two input images is similar or not. Using the logistic regression or chi-square node.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hqA1c674QiNl2DLvXkznQ.png" /><figcaption>Learning the similarity function. Source: deeplearning.ai C4W4L05</figcaption></figure><ul><li>Face verification problem can be treated as a supervised learning problem.</li></ul><h4>Neural style transfer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPbAsDIwmqygZDebutGc4A.png" /><figcaption>Examples of network transfering image style. Source: deeplearning.ai C4W4L06</figcaption></figure><h4>What are deep Convolutional Network learning</h4><ul><li>For example in the AlexNet</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teSLvetwZGKj-mW4b9UXTA.png" /><figcaption>Layer 1 units visualization. Source: deeplearning.ai C4W4L07</figcaption></figure><ul><li>Obviously, we can see that the unit in layer 1 is more favorable in “edge” form of image patchs. 9 image patchs of each unit are similar to others in term of color and pattern. Clearly, there are horizontal, vertical, fading, sloping edge in these patchs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZUcLPcDiV0tsaraKqmBxg.png" /><figcaption>Layer 2 units visualization. Source: deeplearning.ai C4W4L07</figcaption></figure><ul><li>Follow that, layer 2 contains group of more complex edge patchs or textures. Circle, multiple line pattern ….</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGmtqJrLi_EoWyb-XJultA.png" /><figcaption>Layer 3 units visualization. Source: deeplearning.ai C4W4L07</figcaption></figure><ul><li>Layer 3 includes much more complex filter, or even clearly some object parts.</li><li>In summary, going to deeper layers, the filters follow this rule: Edge → Textures → more complex image form.</li></ul><h4>Neural style transfer: Cost function</h4><ul><li>Three components of the cost function.</li><li>J_content(C,G) how similar the content and generated image</li><li>J_style(S,G) how similar the style and generated image</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1birZoOsAc_Y4gi_zonk2A.png" /><figcaption>Cost function for Neural style transfer. Source: deeplearning.ai C4W4L08</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p40xVf0n9w8mjHg_y6EtGQ.png" /><figcaption>Find the generated image G. Source: deeplearning.ai C4W4L08</figcaption></figure><h4>Neural style transfer: Content cost function</h4><ul><li>The content here is not pixel-wise difference between two pictures. It is in the Convolution Network content. Noticed that when passing an image to a ConvoNet, it goes through many layers until the end. In each layer, the activation of previous layer input describes how likely/well it fit to a filter.</li><li>Picking the activation information or the response in a certain hidden layer, also describes the “content” information after several kind of “filtering”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lH3GAqTbh2DE-LeEpzAYBA.png" /><figcaption>Definition of the content cost function. Source: deeplearning.ai C4W4L09</figcaption></figure><h4>Neural style transfer: Style cost function</h4><ul><li>What Conv “style” ? the <strong>correlation</strong> among activation of channels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMXiFXQqwxgokLm0Lpuk7A.png" /><figcaption>n_C = 5, visualization of 5 channels activation. Source: deeplearning.ai C4W4L10</figcaption></figure><ul><li><strong>correlation</strong> among activation of channels = high level textures co-occur together in a image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Putz7Ak2aZAB4GWlYq91Wg.png" /><figcaption>The correlation of red/yellow channel of the style image according to the Convnet need to mantain in the generated image. Source: deeplearning.ai C4W4L10</figcaption></figure><ul><li>(i, j, k) height, weight, channel index</li><li>Input style image (s), generated image (G)</li><li>Need to compute all correlation between “pair” of channels to get the overall “style” correlation of an image → store in a matrix G^[<em>l</em>] with<em> l</em> is the <em>l</em>th hidden layer. As n_c channel then G is [n_c x n_c].</li><li>The correlation between “pair” of channels (<em>k</em>,<em>k’</em>) is computing by taking the sum of product of all elements in a channel → return a number.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQH1wGtrKsCO_ISZG2scjA.png" /><figcaption>Definition of style matrix of Style image (S) and generated image (G). Source: deeplearning.ai C4W4L10</figcaption></figure><ul><li>The FINAL Style cost function is the Frobenius between two matrices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnhGgi9bHQ9T-XtD0nm3UA.png" /><figcaption>Source: deeplearning.ai C4W4L11</figcaption></figure><ul><li>Can be more effective if J_style is computed in many hidden layer.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f9dcdb24bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/deeplearning-ai-cnn-week-4-special-applications-9f9dcdb24bd">Deeplearning.ai CNN week 4: Special applications</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeplearning.ai CNN week 3: Object detection]]></title>
            <link>https://medium.com/datatype/deeplearning-ai-cnn-week-3-object-detection-ce86e6c648e?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce86e6c648e</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 15:11:51 GMT</pubDate>
            <atom:updated>2018-02-06T15:14:07.310Z</atom:updated>
            <content:encoded><![CDATA[<h4>Heading to the YOLO algorithm</h4><ul><li>Classification vs Localization vs Dectection?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goQ3dzRFohmh8q9IVStHsQ.png" /><figcaption>Terminologies example. Source:deeplearning.ai C4W3L01</figcaption></figure><ul><li>Localization -&gt; return a bounding box of the object inside image</li><li>Adding the bounding box coordinate variables into the target of the network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xRKYhBjcQc3ZO972e6fEg.png" /><figcaption>Labeling structure for object localization. Source:deeplearning.ai C4W3L01</figcaption></figure><ul><li>p_c is the probability of having an object</li><li>b_x, b_y, b_h, b_w : bounding box information</li><li>c_1, c_2, c_3 : the classes of pedestrian/car/motorcycle. 1 if it is.</li></ul><h4>Landmark Detection</h4><ul><li>The same idea as object localization, the difference is returning the “point” instead of bounding box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQVcuYKPBhk0fjHwLSDWdQ.png" /><figcaption>Labeling structure for landmarkd detection. Source: deeplearning.ai C4W3L02</figcaption></figure><ul><li>Data label now in pair of x,y coordinates of landmarks which want to be learned. After passing through some ConvNet.</li><li>Labels have to consitant over training images.</li></ul><h4>Object detection</h4><ul><li>Create the training set by crop the object region + its label</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8n9Njm6_V-VhfMkgcbj_Q.png" /><figcaption>Training data from raw images. Source: deeplearning.ai C4W3L03</figcaption></figure><ul><li>In testing phase, detection by sliding the windows(different size) over image → push to ConvNet → predict.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjbJnk_nhXiSrSQzCCDE-A.png" /><figcaption>Sliding windows in different size. Source: deeplearning.ai C4W3L03</figcaption></figure><ul><li>The main disadvantage, many possible crop in the image in different scale→ computational cost. Running under ConvNet as take time to predict in one crop image → slow.</li></ul><h4>Convolutional Implementation Sliding Windows</h4><ul><li>How to turn Fully connected layer to convolutional layers ?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DztuySz0AQ_Ji9v0iUanJw.png" /><figcaption>Equivalent convolution based network (below) of the convo+fully connected network (above). Source: deeplearning.ai C4W3L04</figcaption></figure><ul><li>The main target is finding an appropriate way to keep the same network follow (input/output size) in each step, but not to use the fully connected layer anymore.</li><li>Remember the “network inside network” : fully connected layer == 1x1 convolution. Then by using an “suitable” way, this target can be achieved.</li><li>For the first fully connected layer of 400 nodes, due to its input is 5x5x16, we can use 400 convolution filters of the size 5x5x16. The result is 400 elements of the size 1x1 or 400 nodes.</li><li>The next fully connected layers is rebuilt by using 1x1 convolution way, quite simple :).</li><li>BUT the convolution filters ITSELF also sliding over regions of image to return the input. Then, the convolution is equivalent to the sliding window operator by an appropriate way.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RzjQKXqx-DGbHg9OUd6Xw.png" /><figcaption>1st row, trained model. 2nd, 3rd row, apply trained model in a new testing image. Source: deeplearning.ai C4W3L04</figcaption></figure><ul><li>For example, the test image 16x16x3 is 2 pixels more than the trained images. If putting them directly to the trained model, the final output is a 2x2x4 tensor where each 1x1x4 is corresponding the response of a region of 14x14x3 of the input testing image.</li></ul><h4><strong>Bounding Box Predictions</strong></h4><ul><li>The size of sliding window is critical, as sequentially capture a region by region, there are no 100% chance to catch an object at a certain window size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*H3t3Xorf2mYyhklA9BdOGA.png" /><figcaption>Sliding window behaviour is not like our desire. Source: deeplearning.ai C4W3L05</figcaption></figure><ul><li>YOLO algorithm (you only look one time)</li><li><strong>For example:</strong> for an image of 100x100, divide into 3x3 grid, for the training data, each grid rectangle need to be labeled as “y” of 8 variables.</li><li>p_c: probability response of having object or not</li><li>b_x, b_y : the coordinate of the center point of the object bounding box.</li><li>b_h, b_w: the height and weight of the bounding box</li><li>c_1, c_2, c_3: binary respone of each label class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_JSeU6Odd-k-Jy6u4XJVA.png" /><figcaption>Grid training data definition. Colors of right vectors are corresponding to the left gird area. Source: deeplearning.ai C4W3L05</figcaption></figure><ul><li>Then the output of this YOLO is a 3x3x8 tensor. Using the deep learning framework as usual, just modify the way of output.</li><li>It is image classification + localization + convolutional implementation.</li><li>Encode b_x, b_y, b_h, b_w information. By the fraction of it over the regional box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKhNGbPkSZxyKOMLADindA.png" /><figcaption>Bounding box labeling process. Source: deeplearning.ai C4W3L05</figcaption></figure><h4>Intersection over Union</h4><ul><li>One object can be found in many boxes, causing the overlapping of object recognize.</li><li>It is the size of the intersection / the union</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBATufmD-SrMOdCSyXw7kw.png" /><figcaption>Source: deeplearning.ai C4W3L06</figcaption></figure><h4>Nonmax Suppression</h4><ul><li>One object can be detected multiple times. Need to be clean up for the final result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*xKHd-XjmWySst2k_-4ggRQ.png" /><figcaption>Multiple detection of the same object. Source: deeplearning.ai C4W3L07</figcaption></figure><ul><li>Take the bounding box with the highest probability, get rid the rest of lower probability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*oRZiDsWwCUG_FDZwDEAxkQ.png" /><figcaption>Keep the highest response for overlapping region. Source: deeplearning.ai C4W3L07</figcaption></figure><ul><li>The algorithm</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nStN5kXYpIzHQARb62oytA.png" /><figcaption>Source: deeplearning.ai C4W3L07</figcaption></figure><h4>Anchor Boxes</h4><ul><li>What about overlapping objects ? How can recoginize multiple things in the same grid box?</li><li>Predefine anchor boxes, each box for a type of shape, replicated the same 8 variable label structure into “y” more.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ah5ofsM343WnU1MO2L0rA.png" /><figcaption>Anchor box 1 for pedestrian and 2 for the car.Source: deeplearning.ai C4W3L08</figcaption></figure><ul><li>Algorithm with 2 anchor boxes: <strong>Each</strong> object in training image is <strong>assigned</strong> to <strong>the grid cell</strong> that <strong>contains</strong> object’s <strong>midpoint</strong> and <strong>anchor box</strong> for the grid cell with <strong>highest IoU</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CloGEve8qi29awF2LU9xw.png" /><figcaption>Anchor box example. Source: deeplearning.ai C4W3L08</figcaption></figure><ul><li>Choosing how many type of anchor boxes in term of shape and number is tough. Almost by human prior.</li><li>Luckily, it is rarely happen that two objects appear in a grid cell IF the grid is 19x19 for 100x100 image size.</li><li>Can use K-mean algorithm to cluster all of anchor box and finallize them later.</li></ul><h4>YOLO algorithm</h4><ul><li>Putting all above components together. For example: classify three objects: car, pedestrian, motorcycle.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yjr5LN-ZTwUYu4imqAsWow.png" /><figcaption>Training data definition for YOLO algorithm. Source: deeplearning.ai C4W3L09</figcaption></figure><ul><li>There are two kind of anchor boxes: the red bounding box of the car is more IoU with the 2nd anchor box, then the label for the grid containing car as the above image (no information for the first 8 variables)</li><li>Making the prediction</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-7UW2Udt6h3b7t46vUMtg.png" /><figcaption>Prediction example for each grid cell. Source: deeplearning.ai C4W3L09</figcaption></figure><ul><li>Non max supressed the outputs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*qeSlWB8zrDC8JQ2prOopIg.png" /><figcaption>For each grid cell, get 2 predicted bounding boxes. Source: deeplearning.ai C4W3L09</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*q4LK1ONyc_ye5kwJwmO38w.png" /><figcaption>Get rid of low probability predictions. Source: deeplearning.ai C4W3L09</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*e5kzsmrysXsXRWZ2Ph4XRg.png" /><figcaption>For each class, use non-max supression to general final predictions. Source: deeplearning.ai C4W3L09</figcaption></figure><h4>Region Proposal R-CNN</h4><ul><li>Many background regions also are feeded into the convolution network. Running the image segmentation first and do the convol later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COwi_2GC4prboWqJHTzPrw.png" /><figcaption>Region Proposal idea, no need to evaluate background region. Source: deeplearning.ai C4W3L10</figcaption></figure><ul><li>But the segmentation is slow.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce86e6c648e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/deeplearning-ai-cnn-week-3-object-detection-ce86e6c648e">Deeplearning.ai CNN week 3: Object detection</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeplearning.ai: CNN Week 2 — Convolutional Neural Network Architecture]]></title>
            <link>https://medium.com/datatype/deeplearning-ai-cnn-week-2-97e075f8c801?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e075f8c801</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 12:25:32 GMT</pubDate>
            <atom:updated>2018-02-07T09:14:59.274Z</atom:updated>
            <content:encoded><![CDATA[<h4>Case studies of CNN</h4><ul><li>How to put CNN components together ?</li><li>Learn from other source code/ CNN architecture.</li><li>LeNet-5, AlexNet, VGG, ResNet, Inception neural net.</li><li>Ideas from one application/artchitecture can transfer to others domain.</li></ul><h4>Classic network</h4><ul><li><em>Letnet-5</em>: grayscale image of numbers (32 x 32) -&gt; two times of filtering and pooling (4 layers)→ 2 layers of fully connected → soft max func → labels. Purpose to recognize the numbers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7fXcAoFokQ3XrnuUuP5sA.png" /><figcaption>Lenet-5 structure. Source: deeplearning.ai lecture C4W2L02</figcaption></figure><ul><li><em>AlexNet</em>: almost the same as LeNet, extend more layers and parameters in the scale of milions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dKupQOawEzrU-HbCoiSrA.png" /><figcaption>AlexNet structure. Source: deeplearning.ai lecture C4W2L02</figcaption></figure><ul><li><em>VGG-16</em>: all Conv and max-poll in the network are the same settings. But the network is very large, larger than the AlexNet. Interestingly, while the max pooling decrease the size of the data “tensor”, the number of filter is increasing according to the scale of 2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EVlMNN7oPDZYhE2Y4A6Mg.png" /><figcaption>VGG-16 structure. Source: deeplearning.ai lecture C4W2L02</figcaption></figure><h4>Resnet</h4><ul><li>Vanishing, exploding gradient infomation ? How to train very deep neural network ?</li><li>A residual block. Typically, the input will be manipulated under two linear transformation with Relu activation. A residual network is copy the input directly to the second transformation output, and feed the sum into the final Relu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3TGtZpOPdG_kAAVAWZl0w.png" /><figcaption>A residual block structure. Source: deeplearning.ai lecture C4W2L03</figcaption></figure><ul><li>Residual Network: add many residual block together. The plain very deep network gradually loss its robust after a certain deepth, increasing the error. Nevertheless, the ResNet is not faced this problem.</li></ul><h4>Why ResNet work ?</h4><ul><li>Let think about the learning scenario: If W[l+1] = 0 and b[l+1] = 0, then the ouput a[l+2] = a[l] and thus “g” is the identity function. Recall that the Relu filters out negative values of a[l].</li><li>Then in the worst case of learning nothing or zero weights, the network still can learn the identiy function. That we know at least one solution for the network.</li><li>In the “Plain” network, if W[l+1] = 0 and b[l+1] = 0, then a[l+2] = 0. Of course, when the weight vanishing, nothings meaningful returned. We do not know the “worst” solution.</li><li>Then the “residual” means learning somethings residual/added transformation of the actual input but useful. The “Plain” network simply learns the serial transformation of input via layers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvNLc28z6bCKhA3WgkexmA.png" /><figcaption>Adding skip connection turns Plain network to ResNet. Source: deeplearning.ai lecture C4W2L04</figcaption></figure><h4>Network in Network</h4><ul><li>1 x 1 convolution. Technically, 1x1 conv operator in a matrices is the amplification of input data. BUT, it is worth when the input data is tensors, for example: the RBG image.</li><li>A filter now has the size of 1x1x “depth”, according to the 3rd dimension of data tensor. Taking the conv operator (element-wise multiplication over 3rd dimension) → sum of → ReLu. It is the same working way in a 1 output node network. Then it returns a number when applying 1x1 convolution in one “yellow” slide of the data tensor. Despite of the “depth” of the tensor, the output is a matrices: the Relu of linear transformation by the 1x1x “depth” convolution over tensor slides.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*KN7nlC5GiPQ4V60Y6_xtOw.png" /><figcaption>1x1 convolution. Source: deeplearning.ai lecture C4W2L05</figcaption></figure><ul><li>When many filters are applied, the output “depth” is the number of filters. It is the responses of data tensor over each convolution configuration. Or the responses of different linear transformation. It makes me remember about machine learning with random projection, used to 5 or 6 years ago is a hot topic. Or Extreme Machine Learning :).</li><li>The different with &gt;1 size convo is the 1x1 keeps the origin size of 2 dimension. Then it decreases the number of channels, saving computation time. Simple but strength :).</li></ul><h4>Inception network</h4><ul><li>Tough in choosing pool or convo or hyper parameters ?</li><li>Let do all of them on the input data and stack the results together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cCVF3u5g3gfTqwoCIgT7Q.png" /><figcaption>Motivation example of the Inception network. Source: deeplearning.ai C4W2L06</figcaption></figure><ul><li>Computational cost is a problem. For 32 filters of size 5x5 on the example input of 28x28x192 → computer needs to do 120milions calculation.</li><li>BUT 1x1 convolution is our friend. Let reduces the number of input layers or “depth” first and do the “inception” later. It is the “bottle-net” network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMMr2ozc34mD6FJAoFUh-A.png" /><figcaption>1x1 layer applied first. Source: deeplearning.ai C4W2L06</figcaption></figure><ul><li>Applying 16 filters of the size 1x1x192 to reduce the input tensor to 28x28x16 and continue with the convolution of 5x5….</li><li>Reducing from 120milions calucation to 2.4m + 10.0m = 12.4m. Around 10 times reduce.</li><li>Recap: do them all + concatenate</li><li><strong>An Inception module</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLBYMtysqeHbBqUlumVESw.png" /><figcaption>A typical module/ building block of the inception module. Source: deeplearning.ai C4W2L07</figcaption></figure><ul><li>I noticed that when the size of convolution filter increases, there are less number of filters. Maybe more “actions” to digging “small” details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwyAWaNq9ilpwlOT04i2nw.png" /><figcaption>Putting many inception module togeter → inception network</figcaption></figure><ul><li>Can add some softmax node in the middle to do the predicting task.</li><li>It is the GoogLeNet</li></ul><h4>Using Opensource implementation</h4><ul><li>Hard to replicate only with the publication of deep learning paper.</li><li>It is easier to look online to find the author implementation.</li><li>Google of Network “keyword + github”</li></ul><h4>Transfer learning</h4><ul><li>Many open dataset, sources code, pretrained model → can use the initial weight → train in new domain.</li><li>For example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVgJPGonMdUjr_TQHKAyrQ.png" /><figcaption>3 ways of doing the transfer learning. . Source: deeplearning.ai C4W2L09</figcaption></figure><ul><li>IF you want to train a classifier to classifer images which contain “cat” names Tigger, Misty, and either.</li><li>Which is the fastest way to train it with less available data about them?</li><li>Let use the trained weights on big datasets, e.g: ImageNet, as the input weight and network structure for our purpose. There are 3 ways to utilize it:</li><li>1. Use the whole trained weights, “frozen” it (no retraining), use the output of final network layer, add a fully connected softmax layer and learn the classification weights of it. This way we are using the distance from a datapoint to other “well-known” class, as the feature to learn.</li><li>2. Almost the same as the first way, execept retrain some final layers, use the loaded weights as the initial points.</li><li>3. Retraining whole network with initial loaded weights. Of course, this can happen as we expand or modify the classes cluster “structure” rather than find the structure of them from beginning.</li><li>Recap: save time and resources, faster develop.</li></ul><h4>Data Augmentation</h4><ul><li>Training a computer vision task quite tough in term of data availability. How to create more data ?</li><li>In common, Mirroring, Random cropping</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3071a-0MjrztALbH4kBsg.png" /><figcaption>Cropping and mirroring to create new data . Source: deeplearning.ai C4W2L10</figcaption></figure><ul><li>Color shifting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4o4VNT8tQvHd6pZeDAslQ.png" /><figcaption>Shifting the image color information. Source: deeplearning.ai C4W2L10</figcaption></figure><ul><li>Implement the data distortion during training:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNJFGZPhc2-qFK9WATw4Tg.png" /><figcaption>Using multiple thread CPU to load data/doing distortion → data batch → training algorithm. Source: deeplearning.ai C4W2L10</figcaption></figure><h4>State of Computer Vision</h4><ul><li>Less data = more hand engineering/ human actual work on data processing/ feature extraction/ annotate data/ more complex algorithms. But transfer learning can help.</li><li>More data = simple algorithms/ learn from data/ less engineering.</li><li>How to get higher benchmarks ?</li><li><em>Ensembling</em>: train algorithms independently, average their outputs.</li><li><em>Multi-crop at test time</em>: Run classifiers on different crops of a test image and average the result.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e075f8c801" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/deeplearning-ai-cnn-week-2-97e075f8c801">Deeplearning.ai: CNN Week 2 — Convolutional Neural Network Architecture</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeplearning.ai: CNN week 1 — Convolutional Neural Network terminology]]></title>
            <link>https://medium.com/datatype/deeplearning-ai-cnn-week-1-a0bac10d509b?source=rss-e2a125f88e00------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0bac10d509b</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Nguyễn Văn Lĩnh]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 15:27:25 GMT</pubDate>
            <atom:updated>2018-02-07T09:53:31.583Z</atom:updated>
            <content:encoded><![CDATA[<h4>From edge filtering to convolutional filters</h4><p>Applications: e.g Neural Style Transfer</p><h4>Edge detection,</h4><ul><li>Vertical edge detection, 6x6 grayscale image, 3x3 filter/kernel (sobel, robert, prewitt filter) -&gt; 4x4 image. In images with clear edges, visualize the image and the Prewitt filter.</li><li>Vertical vs horizontal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOqoc1j2-dWF-BEW4vQLxA.png" /><figcaption>Vertical edge detection example. Source: deeplearning.ai C4W1L02</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDqq5ZHYyJE70Zvdt1K_vA.png" /><figcaption>Vertical vs horizontal edge detection example. Source: deeplearning.ai C4W1L03</figcaption></figure><ul><li>prewitt filter → sobel filter: more weighted for the center, more robust</li><li>What about auto learn the filter ? hard-code filter -&gt; data-learned filter, robust with the rotation. data-dependent filter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRZmOcK9uMsAUvY1DFfCwQ.png" /><figcaption>Can learn <strong>w</strong> from data. Source: deeplearning.ai C4W1L03</figcaption></figure><h4>Padding:</h4><ul><li>The output filtered is depended on how “fit” the filter [f x f] to the image [n x n]. Then, the output is [(n-f+1), (n-f+1)]. “f” usually odd.</li><li>The “edge” pixels are used less times in filtering step, rather than more center pixels. Loss the informative and size of the ouput dismiss very fast.</li><li>Solution: padding edge “p” pixels to expand the size of the input image -&gt; (n+2p-f+1) x (n+2p-f+1)</li><li>“Valid” convolution: no padding, “Same” convolutions: padding, #input == #output =&gt; p = (f-1)/2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFCSCyFPYMq2oEGDIugZVw.png" /><figcaption>Blue area is added to keep the result is equal size with the input image. Source: deeplearning.ai C4W1L04</figcaption></figure><h4>Strided convolution:</h4><ul><li>Sweeping the filter not in 1 by 1 pixel, but jump 2 two pixels step or more =&gt; smaller output image.</li><li>Jumping “s” pixels =&gt; output[( (n+2p-f)/s+1) ; ( (n+2p-f)/s+1)]</li><li>Typical “covolution” operator in math/signal processing textbooks: flip and multiply. The “covolution” of deep learning is “cross-correlation”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgjfTAebULLEcD8Yow8Mwg.png" /><figcaption>Example of the convolution when stride = 2. Source: deeplearning.ai C4W1L05</figcaption></figure><h4>Convolution over volume:</h4><ul><li>RGB images (3 channels= Nc), including 3 layers of matrices =&gt; 3 covolution matrices to do the filterting for each channel.</li><li>The mechanism: in each area, doing the filtering for 3 channel by 3 layers respectively. Add all of them together to get the final number ( 1 number).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHm3Fv2cKOnIYWgVsA9ElQ.png" /><figcaption>Doing the covolution on 3 channels in each 6x6 element. Source: deeplearning.ai C4W1L06</figcaption></figure><ul><li>Multiple filters: use different filters and stackup the results. Each filter for different purpose.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17F_wAJLdva3JsSlxlqGrg.png" /><figcaption>Doing hortizontal and vertical filter “cube” covolution and stack the results. Source: deeplearning.ai C4W1L06</figcaption></figure><h4>One layer of the covolutional neural network</h4><ul><li>Input -&gt; Filtering -&gt; output_tmp -&gt; add bias -&gt; relu -&gt; final ouput</li><li>Parameters are the number of elements in these filters cubic. NOT the number of weights in the full connected neural network. Less parameters + less overfitting + easier to learn + more robust.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXxEf7H1RtfnduszfqffiQ.png" /><figcaption>Example of a CNN layer. Source: deeplearning.ai C4W1L07</figcaption></figure><h4>Simple convolutional network</h4><ul><li>One convolution layer: Images input (3 channels) -&gt; filtering -&gt; output (affected by padding, stride, size of the filter) x (number of filters).</li><li>Input -&gt; many convolution layers -&gt; flattening -&gt; full connected layer -&gt; softmax -&gt; outputs.</li><li>Type of layer in the convolutional network: convolution (conv) + pooling (pool) + fully connected (fc)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iM1VFCkjeinjC-7RmywTpg.png" /><figcaption>A Convolution Network. Source: deeplearning.ai C4W1L08</figcaption></figure><h4>Pooling</h4><ul><li>Max operator: break image -&gt; region -&gt; pick the max value of each region.</li><li>Hyper parameter: stride (s) and filter size (f), do not need to be learned.</li><li>Reserve the key feature by max operator, if the feature is dismiss in the output, it is not “key” feature.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwDo5gTeqZ-JGLvIsfMsQg.png" /><figcaption>Example of Max pooling for f= 2, s= 2. Source: deeplearning.ai C4W1L09</figcaption></figure><ul><li>The average operator can be used in the pooling step.</li></ul><h4>CNN example:</h4><ul><li>Andrew Ng convention: Convolution+pool = one layer.</li><li>LeNet-5: Input -&gt; layer 1 -&gt; layer 2 -&gt; fully connected layer 3 -&gt; fully connected layer 4 -&gt; softmax -&gt; output</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQaf2hlimC8G3bBaRL_zzg.png" /><figcaption>LeNet-5 structruture. Source: deeplearning.ai C4W1L10</figcaption></figure><ul><li>Activation size decrease fastly, but the number of parameters increase (still a lot smaller than the full connected weights).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFzHJwl5eBiX2Jx38T7kVQ.png" /><figcaption>Network size in each step. Source: deeplearning.ai C4W1L10</figcaption></figure><h4>Why CNN ?</h4><ul><li>Parameters sharing and Sparsity of the connection</li><li><em>Parameters sharing</em> in the cubic of features, it learns the data-dependent filter based on areas/parts of input images. Useful in one part is also useful in other parts. Less parameters</li><li><em>Sparsity of the connection</em>: each output element is depended only some number of input : as this element is the result number of the convolution operator of the filter on a part of the image. Less overfitting, less translation invariance.</li><li>How to train ? need a “cost” function, gradient descent</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0bac10d509b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datatype/deeplearning-ai-cnn-week-1-a0bac10d509b">Deeplearning.ai: CNN week 1 — Convolutional Neural Network terminology</a> was originally published in <a href="https://medium.com/datatype">datatype</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>