<?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 Srinivas Chakravarthy on Medium]]></title>
        <description><![CDATA[Stories by Srinivas Chakravarthy on Medium]]></description>
        <link>https://medium.com/@srinivas-yeeda?source=rss-43159ab4d110------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0eMgzO8WQnH0o79zgrT4wg.png</url>
            <title>Stories by Srinivas Chakravarthy on Medium</title>
            <link>https://medium.com/@srinivas-yeeda?source=rss-43159ab4d110------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srinivas-yeeda/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[Steps to install CUDA and PyTorch for QuadroK5200 GPU card]]></title>
            <link>https://srinivas-yeeda.medium.com/steps-to-install-cuda-and-pytorch-for-quadrok5200-gpu-card-15f37c301754?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/15f37c301754</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 13:46:46 GMT</pubDate>
            <atom:updated>2021-10-19T13:46:46.463Z</atom:updated>
            <content:encoded><![CDATA[<p>We were trying to install CUDA and Pytorch as GPU and we had search for some information for this. I wanted to just put down the things at a place so that it would be useful</p><p>1. Check if the system is able to detect the Nvidia GPU card of your system</p><p>lspci | grep -i nvidia</p><p>The result would be similar to below lines.</p><p>02:00.0 VGA compatible controller: NVIDIA Corporation GK110GL [Quadro K5200] (rev a1)</p><p>02:00.1 Audio device: NVIDIA Corporation GK110 High Definition Audio Controller (rev a1)</p><p>2. Clean or remove or uninstall all the previous versions of CUDAand its dependencies by executing the below commands</p><p>sudo apt-get purge nvidia*<br> sudo apt-get remove — auto-remove nvidia-cuda-toolkit</p><p>sudo apt-get remove nvidia-cuda-toolkit</p><p>sudo apt-get — purge remove “*cublas*” “cuda*” “nsight*”</p><p>sudo rm <em>etc/</em>apt/sources.list.d/cuda*</p><p>sudo apt remove –autoremove nvidia-cuda-toolkit</p><p>sudo apt remove –autoremove nvidia-*</p><p>sudo apt update</p><p>sudo apt-get autoremove</p><p>sudo apt-get autoclean</p><p>sudo rm -rf /usr/local/cuda*</p><p>3. Since it is old GPU card you can install CUDA 10.2 which is compatible with the Nvidia Quadro K5200 GPU card. Install the required driver files using the below commands</p><p>wget <a href="https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin">https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin</a></p><p>sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600</p><p>wget <a href="http://developer.download.nvidia.com/compute/cuda/10.2/Prod/local_installers/cuda-repo-ubuntu1804-10-2-local-10.2.89-440.33.01_1.0-1_amd64.deb">http://developer.download.nvidia.com/compute/cuda/10.2/Prod/local_installers/cuda-repo-ubuntu1804-10-2-local-10.2.89-440.33.01_1.0-1_amd64.deb</a></p><p>sudo dpkg -i cuda-repo-ubuntu1804–10–2-local-10.2.89–440.33.01_1.0–1_amd64.deb</p><p>sudo apt-key add /var/cuda-repo-10–2-local-10.2.89–440.33.01/7fa2af80.pub</p><p>sudo apt-get update</p><p>sudo apt-get -y install cuda</p><p>4. Update the CUDA path by updating the below environment variables and files.</p><p>sudo nano /etc/profile.d/cuda.sh</p><p>#write following lines in nano editor</p><p>export PATH=$PATH:/usr/local/cuda/bin</p><p>export CUDADIR=/usr/local/cuda</p><p># save and exit</p><p>sudo nano /etc/ld.so.conf.d/cuda.conf</p><p>#write</p><p>/usr/local/cuda/lib64</p><p># save and exit</p><p>sudo ldconfig</p><p>Add the below lines to ~/.bashrc and ~/.profile</p><p># set PATH for CUDA 10.2 installation if [ -d “/usr/local/cuda/bin/” ]; then export PATH=/usr/local/cuda/bin${PATH:+:${PATH}} export LD_LIBRARY_PATH=/usr/local/cuda/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} fi</p><p>5. Install the latest version of cudnn7 using the below commmand</p><p>sudo apt install libcudnn7</p><p>or</p><p>5a. Install the latest version cudnn using the below command</p><p>wget <a href="https://developer.download.nvidia.com/compute/machine-learning/cudnn/secure/7.6.5.32/Production/10.2_20191118/cudnn-10.2-linux-x64-v7.6.5.32.tgz?YOUR_ACCESS_TOKEN">https://developer.download.nvidia.com/compute/machine-learning/cudnn/secure/7.6.5.32/Production/10.2_20191118/cudnn-10.2-linux-x64-v7.6.5.32.tgz?YOUR_ACCESS_TOKEN</a></p><p>Make sure you give your access token for YOUR_ACCESS_TOKEN</p><p>If you use step 5a then follow the steps in Appendix A for installation of cudnn</p><p>6. Reboot the computer to reflect the changes</p><p>7. Verify if the system has reflected the changes installed by running the below commands</p><p>Check the CUDA compiler driver version using,</p><p>nvcc –version</p><p>Check the nvidia driver version using,</p><p>nvidia-smi</p><p>Check the cudnn version using,</p><p>/sbin/ldconfig -N -v $(sed ‘s/:/ /’ &lt;&lt;&lt; $LD_LIBRARY_PATH) 2&gt;/dev/null | grep libcudnn:</p><p><strong>Now to install PyTorch for CUDA 10.2</strong></p><p>8. Make sure you are installing PyTorch for the CUDA 10.2. Check the CUDA version</p><p>cat /usr/local/cuda/version.txt</p><p>or nvcc –version</p><p>or nvidia-smi</p><p>9. Install right version of PyTorch which supports CUDA 10.2. The PyTorch version 1.5.0 and above supports CUDA 10.2 and earlier versions does not. So you can install the version above 1.5.0</p><p>pip install torch==1.7.0 torchvision==0.8.1 -f <a href="https://download.pytorch.org/whl/cu102/torch_stable.html">https://download.pytorch.org/whl/cu102/torch_stable.html</a></p><p>10. Check if PyTorch is installed and works for CUDA 10.2 with below commands</p><p>$ python</p><p>&gt;&gt;&gt; import pytorch</p><p>&gt;&gt;&gt; torch.version.cuda</p><p>‘10.2’</p><p>&gt;&gt;&gt; print(torch.cuda.is_available())</p><p>True</p><p>&gt;&gt;&gt; torch.zeros(1).cuda()</p><p>tensor([0.], device=’cuda:0&#39;)</p><p>11. If any last command returns error then it is better to install PyTorch from source. For that you can follow the below steps</p><p>Get the source of PyTorch from github</p><p>git clone — recursive <a href="https://github.com/pytorch/pytorch">https://github.com/pytorch/pytorch</a></p><p>cd pytorch</p><p># if you are updating an existing checkout</p><p>git submodule sync</p><p>git submodule update — init — recursive — jobs 0</p><p>12. Install PyTorch from the sources using below command</p><p>export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-”$(dirname $(which conda))/../”}</p><p>python setup.py install</p><p>13. If there is any error due to gcc or g++ during the build then you can install the appropriate version of gcc and g++ using the below commands.</p><p>Add below lines</p><p>deb <a href="http://dk.archive.ubuntu.com/ubuntu/">http://dk.archive.ubuntu.com/ubuntu/</a> xenial main</p><p>deb <a href="http://dk.archive.ubuntu.com/ubuntu/">http://dk.archive.ubuntu.com/ubuntu/</a> xenial universe</p><p>sudo apt update</p><p>sudo apt install g++-5 gcc-5</p><p>sudo update-alternatives — install /usr/bin/gcc gcc /usr/bin/gcc-5 5</p><p>sudo update-alternatives — install /usr/bin/g++ g++ /usr/bin/g++-5 5</p><p>sudo update-alternatives — config gcc</p><p>sudo update-alternatives — config g++</p><p>14. The build should be successful and you can verify the installation using the step 10 above.</p><p>Appendix A</p><p>Follow the below steps to install latest version of cudnn 7</p><p>1. Untar the file downloaded in step 5a, the files gets untar into cuda directory.</p><p>tar -zxf cudnn-10.2-linux-x64-v7.6.5.32.tgz</p><p>2. Copy the library files into the system library path</p><p>cd cuda/</p><p>sudo cp lib64/* /usr/local/cuda/lib64/</p><p>sudo cp include/* /usr/local/cuda/include/</p><p>3. Reboot the system or computer</p><p>4. Verify installation using the below command</p><p>cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2</p><p><strong>Authors</strong></p><p>Srinivas Chakravarthy — <a href="/service/mailto:Srinivas.yeeda@gmail.com">Srinivas.yeeda@gmail.com</a></p><p>Chandrashekar B N- <a href="/service/mailto:chandru4ni@gmail.com">chandru4ni@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15f37c301754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Summarization Using Latent Semantic Indexing]]></title>
            <link>https://medium.com/data-science/document-summarization-using-latent-semantic-indexing-b747ef2d2af6?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/b747ef2d2af6</guid>
            <category><![CDATA[latent-semantic-indexing]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[extractive-summarization]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 08:20:23 GMT</pubDate>
            <atom:updated>2020-11-05T14:35:45.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Document summarization is method of getting the gist or summary of the document from the text. There are 2 methods of summarization. Abstractive summarization and Extractive summarization.</p><p>Extractive summarization is basically creating a summary based on strictly what you get in the text. It can be compared to copying down the main points of a text without any modification to those points and rearranging the order of that points and the grammar to make more sense out of the summary.</p><p>Abstractive summarization techniques tend to mimic the process of ‘paraphrasing’ from a text than just simply summarizing it. Texts summarized using this technique looks more human-like and produce more condensed summaries. These techniques are much harder to implement than extractive summarization techniques in general.</p><p>Latent Semantic Indexing or Latent semantic analysis is one of the extractive summarization methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Iy9hWUku6Y1HbJf0a5p4g.jpeg" /><figcaption>Photo by UX Indonesia on Unsplash</figcaption></figure><p><strong>Latent Semantic Indexing</strong></p><p>Latent sematic indexing is used to analyze the relationship between a set of documents and terms contained in the document. This uses a mathematical concept called Singular Value Decomposition (SVD) to compute set of matrices which give the similarity between the documents.</p><p>Latent Semantic Analysis uses the mathematical technique Singular Value Decomposition (SVD) to identify the patterns of relationships between the terms and concepts. This is based on the principle that the words which occur in same contexts tend to have similar meanings.</p><p><strong>Singular Value Decomposition (SVD)</strong></p><p>Singular Value Decomposition is one of dimensionality reduction techniques. SVD is factorization of matrix into 3 matrices. So if we have a matric A it is represented by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*AEs7f-Zr3QxZgi81n58cRg.png" /></figure><p>A is a matrix of dimension mxn. U is a orthogonal matrix of dimension mxm. ∑ is a diagonal matrix of dimension mxn and V is an orthogonal matrix of dimension nxn.</p><p>U is referred to a left singular vector, ∑is a singular values or eigen values, V is a right singular vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*oaPXQSvs02ykvBsOE69ylg.png" /><figcaption><a href="https://commons.wikimedia.org/w/index.php?curid=67853297">“File:Singular value decomposition visualisation.svg”</a> by <a href="https://commons.wikimedia.org/wiki/User:Cmglee">Cmglee</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0?ref=ccsearch&amp;atype=rich">CC BY-SA 4.0</a></figcaption></figure><p>(The following example is taken from the book Information Retrieval, Algorithms and Heuristics by David A Grossman and Ophir Frieder)</p><p>Consider the following 3 documents</p><p>d1: Shipment of gold damaged in a fire.</p><p>d2: Delivery of silver arrived in a silver truck.</p><p>d3: Shipment of gold arrived in a truck.</p><p>Now we create term document matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*SgBrk4hpnhLdOR-8k9P1Kw.png" /></figure><p>If we perform the SVD on this matrix we get the components as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*jFxsV4rGxfbN1tRnVMP1nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*sjcxmo3AgH7cSQVHcTz0GQ.png" /></figure><p>Consider the 2 want to classify these documents into 2 topics</p><p>The columns of the U give the weights that would match each of the word belonging to the topic. For example, the word silver has more weightage to second topic and the word truck has more weightage to 1st topic</p><p>In the matrix S or ∑ the 1st diagonal entry gives weightage of 1st topic and 2nd diagonal entry gives weightage of 2nd topic</p><p>The columns of matrix VT gives weightage of the documents belonging to each of the topic. Like the first 2 documents belong more to the 2nd topic and 3rd document belongs to 1st topic.</p><p>LSI basically helps in classifying the documents belonging to different topics. LSI is also used in search engines. As matrix U gives the relevance of the words to each of the topics and we also have the relevance of the documents belonging to each of the topics we can estimate the relevance of the word to each of the documents. In this way we can get the weightage of the query word belonging to the each of the documents.</p><p><strong>Summarization using Latent Semantic Analysis</strong></p><p>The LSI gives the weightage of the documents belonging to different topics. Summarization is done by selecting the top N documents from each topic depending on the weightage.</p><p>This gives a summarization where we get the higher weighted documents from each of the topics for the summary.</p><p><strong>Applying Latent Semantic Analysis for Summarization</strong></p><p>We have tried to explain the same with the code snippet below</p><p>We need to first load the packages required</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5pLFPzUdF2aaJ4eVxDqVw.png" /></figure><p>We need to load the data from the file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7JeBP2MFJTAUOHtWXClsA.png" /></figure><p>Next we will preprocess the data. This is to tokenize, remove the stop words and stem the words</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieDYi8nVR5BO5gMWn3lgMA.png" /></figure><p>Now we create the term frequency for the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5J_qC-ZJSRbW7U20bZ_t7Q.png" /></figure><p>Now we create LSI model. We use the LSIModel function from Gensim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TyoH5lHtFcK-vFga_vIyw.png" /></figure><p>Now we try to apply the LSI model for the documents. We select the number of topics as 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvPLjxeVXUo_KqqJpVocCA.png" /></figure><p>Now we sort the documents as per the weightage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwKLegG3j6j1C-5nDtP6bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1f5GdcqbPgZ2hYAemZ2jQ.png" /></figure><p>We try to select the top documents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoy3LoJnGVwK4rzKM4SaLQ.png" /></figure><p>We try to sort the sentence numbers in order</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8ufGRMoZC7TQDQ23_giqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivuEs6_yLpBuBiRoguoL_g.png" /></figure><p>Now we try to get the summary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCuxBuYR_05qMsf9ld1XbQ.png" /></figure><p><strong>Conclusion</strong></p><p>Latent Semantic indexing is an extractive summarization technique. As the documents are sorted as per the number of topics, we get the summary of the documents from all the topics. Also, the documents or sentences are sorted according to sematic similarity.</p><p><strong>Authors</strong></p><p>Srinivas Chakravarthy — <a href="/service/mailto:Srinivas.yeeda@gmail.com">Srinivas.yeeda@gmail.com</a></p><p>Chandrashekar B N- <a href="/service/mailto:chandru4ni@gmail.com">chandru4ni@gmail.com</a></p><p><strong>References</strong></p><p><a href="https://radimrehurek.com/gensim/">https://radimrehurek.com/gensim/</a></p><p>Information Retrieval, Algorithms and Heuristics by David A Grossman and Ophir Frieder</p><p><a href="https://github.com/yeedas/Abstractive_Summary_of_Transcriptions/blob/master/Summarization_using_Latent_Semantic_Analysis.ipynb">https://github.com/yeedas/Abstractive_Summary_of_Transcriptions/blob/master/Summarization_using_Latent_Semantic_Analysis.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b747ef2d2af6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/document-summarization-using-latent-semantic-indexing-b747ef2d2af6">Document Summarization Using Latent Semantic Indexing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis using Word2Vec and GloVe Embeddings]]></title>
            <link>https://srinivas-yeeda.medium.com/sentiment-analysis-using-word2vec-and-glove-embeddings-5ad7d50ddb0d?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad7d50ddb0d</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[wordemdeddings]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 14:29:43 GMT</pubDate>
            <atom:updated>2020-09-28T18:01:13.681Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Word2Vec and Glove Embeddings for Natural Language Processing</strong></h4><p>Word embedding is a language modelling technique to represent the words or phrases as vectors. The words are grouped together to get similar representation for words with similar meaning. The word embedding learns the relationship between the words to construct the representation. This is achieved by the various methods like co-occurrence matrix, probabilistic modelling, neural networks.</p><p>Word2Vec , GloVe are popular word embeddings. BERT is one of the latest word embedding.</p><p>Word embeddings are categorized into 2 types</p><p>Frequency based embeddings — Count vector, Co-occurrence vector, HashingVectorizer, TF-IDF</p><p>Pre-trained word embeddings — Word2Vec, GloVe, BERT, fastText</p><p>In this article we discuss about the Word2Vec and GloVe embeddings and their usage in problems for natural language processing</p><p><strong>Pre-Trained Word Embeddings</strong></p><p>Pre trained word embeddings use the Neural Networks to train the word embeddings and get the word vectors. The word vectors are obtained by context, co-occurrence of the words , semantic and syntactic similarity.</p><p>Word2Vec, Glove, ELMO, Fasttext and BERT are belong to this type of embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPRiQ6wiowO3HsQ0CzMSjA.jpeg" /><figcaption>Photo by Dollar Gill on Unsplash</figcaption></figure><p><strong>Word2Vec</strong></p><p>Word2Vec uses shallow neural networks to learn the embeddings. It is one of the popular word embeddings. It was created by Tomas Mikolov, It has two variants namely CBOW and Skipgrams.</p><p><strong>CBOW — Continuous bag of words</strong></p><p>CBOW model guesses the next word with the context of the words. In turn it gets the vectors for the word that is guessed. Consider a sentence <em>“The Boy rides Bike</em>”. In CBOW the guessing is done for the Bike depending on the context <em>“The Boy rides”</em>. The vectors for the words “The”, “Boy”, “rides” are passed to a neural network and the vectors for the output are formed. This is compared to the vectors for the output and error is fed back. In turn vectors for the word Bike are created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Z1-e2AcDkztK5igRuYuuoQ.png" /><figcaption>This picture is taken from Creative Commons — <a href="https://commons.wikimedia.org/w/index.php?curid=45557615">“File:Cbow.png”</a> by <a href="https://commons.wikimedia.org/w/index.php?title=User:Moucrowap&amp;action=edit&amp;redlink=1">Moucrowap</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0?ref=ccsearch&amp;atype=rich">CC BY-SA 4.0</a></figcaption></figure><p>This picture shows the model for CBOW. It has a shallow single hidden layer neural network. Input layer has the context words <em>X1k — Xck</em> . Each of the words is vector of dimension V. The hidden layer has N nodes. The output Yj is a vector of dimension V. The weights WXN and W|XN will be learnt in the training. The output vectors are learnt in the process of training.</p><p>In the picture above C context words are used.</p><p><strong>Skip-Gram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OBQPzl63kVRHAcSmntRE6Q.png" /><figcaption>This picture is taken from Creative Commons — <a href="https://commons.wikimedia.org/w/index.php?curid=45557615">“File:Cbow.png”</a> by <a href="https://commons.wikimedia.org/w/index.php?title=User:Moucrowap&amp;action=edit&amp;redlink=1">Moucrowap</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0?ref=ccsearch&amp;atype=rich">CC BY-SA 4.0</a></figcaption></figure><p>Skip Gram model tries to achieve the reverse of the CBOW model. It takes the target word as input and it tries to get the C context words.</p><p>Skip Gram is good for the small dataset and if the data set is large it is good to use CBOW.</p><p><strong>Glove (Glove: Global Vectors for Word Representation)</strong></p><p>The main theme of Glove is to capture the meaning of a word embedding with overall structure of the entire corpus and to derive the relationship between them from global statistics. Most of the unsupervised algorithms are trained using the word frequency and co-occurrence counts of words. Similarly Glove also generates word embedding by training a model based on global co-occurrence counts of words , global statistics and uses mean squared error as the loss function. The generated word embedding with such a model preserves word relationships and similarities. A co-occurrence matrix for a given sentence tells us how often a given pair of words appear together. Each element in the matrix is the count of the pair of the words occurring together.</p><p>Consider a sentence “<em>The small red book and the big red book are on the table</em>” for example. Its co-occurrence matrix for this will be like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tW5udNkCNFhsBt6Tf6_TmA.png" /></figure><p>As an example let us now try to develop the relationships between the words from the table above.</p><p>For illustration purpose let us consider the word “red”. The conditional probabilities of “red” with respect to the words with which it is paired in the sentence is given below.</p><p>P(red/small) = 1</p><p>P(red/book) = 0.5</p><p>If the ratio of probabilities is computed as given below, it can seen it is greater than 1.</p><p>P(red/small) / P(red/book) = 1 / 0.5 = 2</p><p>As the ratio of probabilities is greater than 1, it can inferred that the word “red” is more relevant to the word “small” rather than to “book”. Similarly if the ratio computed came closer to 1 then it would infer that both the words “small” and “book” are relevant to the word “red”.</p><p>Consider another example sentence, <em>“I eat bread, I love bread and I love biscuits”. </em>The co-occurrence matrix for the sentence is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJea04ZMbxrdFMLJfqfprQ.png" /></figure><p>For illustration purpose let us consider the word “bread”. The conditional probabilities of “bread” with respect to the words with which it is paired in the sentence is given below.</p><p>P(bread/eat) = 1</p><p>P(bread/love) = 0.5</p><p>If the ratio of probabilities is computed as given below, it can seen it is greater than 1.</p><p>P(bread/eat) / P (bread/love) = 1 / 0.5 = 2</p><p>As the ratio of probabilities is greater than 1, it can inferred that the word “bread” is more relevant to the word “eat” rather than to “love”. Similarly if the ratio computed came closer to 1 then it would infer that both the words “love” and “eat” are relevant to the word “bread”.</p><p>Thus the statistics allowed to build the relationship between the words, this is the main concept behind Glove embedding. Let us now get into equations to support it.</p><p>Let the co-occurrence matrix be represented by X and each element in the X will represent the number of times the word j occurs in the context of word “i”. With this context, the below conditional probability can be derived.</p><p>Pij = P(j/i) = Xij / Xi</p><p>The probability Pij gives the probability that the word with index j occurs in the context of word “i”.</p><p>As seen from examples above, the ratios of co-occurrence probabilites gives the relevance of the word j. So consider the function F as below.</p><p>F (wi, wj, w’k) = Pik / Pjk</p><p>Here F is dependent on two word vectors “i” and j and context vector with index k.</p><p>With this as starting point and from paper “GloVe: Global Vectors for Word Representation” by Jeffrey Pennington and et al the loss function for the Glove model can be derived. The loss function is given below.</p><p>Here ‘f’ is the weighting function, bi, and bj are biases. For detailed derivation of the loss function, please refer to the above paper.</p><p><strong>Sentiment Analysis using Word2Vec Embeddings</strong></p><p>We try to use the Word2Vec embeddings to the sentiment analysis of the Amazon Music Reviews. This dataset is taken from Kaggle and the dataset has CC0 license.</p><p>This dataset contains the reviews on the musical instruments sold on amazon. This has review text, summary and overall rating given by various customers.</p><p>In this problem we try to judge the sentiment of the customers by looking at the review text.</p><p>We use word2vec embeddings to vectorize the words in the text. This is text classification problem for the review text.</p><p>We try to import the required dependencies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3du81AILRzpRxZM6Xj41A.png" /></figure><p>Read the data into a dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_P6jalzegK9vSIVQBIHBzg.png" /></figure><p>After this we do a basic pre-processing such as checking if there are any empty values for the columns and changing them as empty space instead of NA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzmGAPSlwPYtRWLT5dw2xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCBaG4uQNcaP7ci4DD_r_w.png" /></figure><p>Convert the overall ratings into sentiment good or bad</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlKIG7XrAZBT2VdfPOeb9A.png" /></figure><p>Take the reviews into an array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH41pFwwp_7P0SSINo5kLQ.png" /></figure><p>Tokenize the text using the Keras tokenizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iz2eJFf9k5vu7Zn6tQlQXg.png" /></figure><p>Split into training and validation datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH_nLTN55OCTmOer4q1h6g.png" /></figure><p>Now we need to get the pre-trained vectors for the word2vec embeddings. There are different ways to get the pre-trained vectors</p><p>Getting the pre-trained vectors from web. We use wget for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hJlX2DYBGZ37_PUzNuosg.png" /></figure><p>Now we use load word2vec format from KeyedVectors to get the pre-trained vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbk6s7juL-ehufUZ19fYFQ.png" /></figure><p>Another way to load using datapath from genism</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejhH2OQ87gdnehqEChAmzQ.png" /></figure><p>We can also get the pre-trained vectors using genism downloader</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vf1DGMZqhdY3LF11dTK--w.png" /></figure><p>After this we create an embedding matrix for the tokenized text for the reviews</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFqhp1bgX_4-eTkjC5GSGQ.png" /></figure><p>We create model using word2vec embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibp5RzyLoVkt-yJXoSTCKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYmw1oNpAfXPviIeIk_ADA.png" /></figure><p>We use a fit function to train using this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dPKN2Hgd9vRdMcdg_zisQ.png" /></figure><p><strong>Sentiment Analysis using Glove Embeddings</strong></p><p>In the similar way as above, we can use the pre-trained glove embeddings to do the sentiment analysis</p><p>The initial steps of preprocessing remain the same</p><p>Create an embedding matrix with the pre-trained vectors from Glove Embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0NDWzJBurVyjKkmqcILOg.png" /></figure><p>Create model with Glove Embeddings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wel5vrp0ouOKKU_SzsIIaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu9peOgKPpqTzSk-U8SDzA.png" /></figure><p>We use Keras fit function to train using the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRoT0RiC_vF3u0vOPJI84Q.png" /></figure><p><strong>Conclusion</strong></p><p>The Word2Vec embeddings are learnt based on the context and co-occurrence of the words. The semantic and syntactic relationships are maintained in the vectors . For example man , woman and king and queen , sun and day are given similar vectors. Glove embeddings are based on overall co-occurrence of the words in the corpus.</p><p>Word2vec tries to capture the co-occurrence one window at a time but Glove is based on co-occurrence of words in the whole corpus.</p><p>Authors:</p><p>Srinivas Chakravarthy — srinivas.yeeda@gmail.com</p><p>Chandrashekar B N — chandru4ni@gmail.com</p><p><a href="https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.Word2VecKeyedVectors.load_word2vec_format">gensim: topic modelling for humans</a></p><p><a href="https://github.com/yeedas/Musicreviews">https://github.com/yeedas/Musicreviews</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad7d50ddb0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Word Embedding for Natural Language Processing]]></title>
            <link>https://medium.com/data-science/simple-word-embedding-for-natural-language-processing-5484eeb05c06?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/5484eeb05c06</guid>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[count-vectorizer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[natural-language-processi]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 10:01:08 GMT</pubDate>
            <atom:updated>2020-08-03T15:03:18.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Word embedding is a language modelling technique to represent the words or phrases as vectors of real numbers. The words are grouped together to get similar representation for words with similar meaning. The word embedding learns the relationship between the words to construct the representation. This is achieved by the various methods like co-occurrence matrix, probabilistic modelling, neural networks. It has become one of the basic knowledge in natural language processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHNAogNW8nUlcn4Dgc1QQQ.jpeg" /><figcaption>Photo by Jon Tyson on Unsplash</figcaption></figure><p>One-hot vectors is one of the simple representations of the words. Each word can be represented by one hot vector but as the number of words increases the dimensionality increases. Word embeddings reduces this dimensionality of the word vectors by using various ways such how the words occur collectively like King , Queen or words which can be used alternatively like car , vehicle etc. So similar words are represented by similar representation of vectors. This reduces dimensionality of the vectors. Though one-hot vectors are easy to construct there usually not a good choice to represent large corpus of words. This is because it does allow to express the similarity between the words in the corpus.</p><p>Word2Vec , GloVe are popular word embeddings. BERT is one of the latest word embedding.</p><p>Word embeddings are categorized into 2 types</p><p>Frequency based embeddings — Count vector, Co-occurrence vector, HashingVectorizer, TF-IDF</p><p>Pre-trained word embeddings — Word2Vec, GloVe, BERT, fastText</p><p>In this article we discuss about the Frequency based embeddings and their usage in problems for natural language processing</p><p><strong>Frequency Bases Embeddings</strong></p><p>Frequency based embeddings vectorize the text depending on the frequency of occurrence of the words in the text/ document. One example of usage of the frequency bases embedding can be use of this in the text classification. Consider we are classifying the text into different categories of technology, politics, economics etc. The words in the texts are vectorized using frequency based vectorizer such as countvectorizer. Then the documents are trained based on the vectors obtained by frequency vectorization. Model prepared will be able to predict the document type. This is because the frequency of some of the words will be more in each type of document. A technology document will have a different set of words compared to a document of politics or economics.</p><p><strong>CountVectorizer</strong></p><p>CountVectorizer is a very simple vectorizer which gets the frequency of the words in the text. CountVectorizer is used convert the collection of text documents to the word/token counts.</p><p>Consider the text “The cup is present on the table”</p><p>Data =[‘The’, ‘cup’, ‘is’, ‘present’, ‘on’, ‘the’, ‘table’]</p><p>This can be vectorized as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*OWnEpIdLcQOWRuOozOWZqQ.png" /></figure><p>Count vectorization can be done with the CountVectorizer from Sklearn. Below is the example to use it. The CountVectorizer encodes the document based on the frequency of the occurrence of the words in the document. CountVectorizer gives the sparse matrix of the frequencies of the words/ n-grams in the document. This is useful to create the model for document classification, document clustering, sentiment analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI-EO_WO0MQpdATd_B8MHA.png" /></figure><p><strong>Co-occurrence Vectorizer or N gram</strong></p><p>The default parameter for the ngram_range is (1,1) that is taking the frequency of 1 word at a time from the document. The ngram range gives the lower and upper boundary of words. This is required because some of the words if taken individually does not give the complete meaning. For example take the text “good book”, “nice read”, “one cent”, “quite cheap”. In these examples the set of the words “nice read” gives complete meaning than the individual words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQV66T-ed6whfSIrUcsubg.png" /></figure><p>CountVectorizer one of the simple ways of extracting the features from the text which can be used later in the developing the model.</p><p><strong>HashingVectorizer</strong></p><p>HasingVectorizer is similar to CountVectorizer but it does not store the vocabulary for the document. It uses hashing to find the token string name to feature index mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlxGqu0i2B-RXXKAQ0fUVA.png" /></figure><p>Hashing vectorizer converts the documents to sparse matrix containing the frequencies of occurrences of tokens. This is normalized as token frequencies depending on the norm parameter. It can be either l1 norm or l2 norm.</p><p>HashingVectorizer has several advantages.</p><p>· The memory consumption is reduced as the vocabulary dictionary need not be stored.</p><p>· It is fast to pickle and un-pickle as it does not hold any state.</p><p>· It can be used for streaming or parallel pipeline data as there is no state used.</p><p>There are some disadvantages of this</p><p>· There is no possibility to retrieve the string names as they are not stored.</p><p>· There can be feature collusions if the number of features is less.</p><p>· There is no IDF weighting as it would render this stateful.</p><p>When you have a large dataset, it is better to use the HashingVectorizer as it reduces the memory consumption and speeds up the algorithm. If the dataset is small, then it is better to use CountVectorizer as it is simple.</p><p><strong>TF-IDF Vectorizer</strong></p><p>The simple frequency based vectorizers sometimes may not serve the purpose as it only gives the frequency of the words. The TF-IDF Vectorizer tries to resolve this issue. TF-IDF is an acronym for “Term Frequency — Inverse Document Frequency”.</p><p>TF — Term Frequency: This is the number of times the word appears in the document</p><p>TF = ( Number of times a word appears in a document ) / ( Number of words in the document)</p><p>IDF- Inverse Document Frequency: This downscales the word which appear frequently across the documents.</p><p>IDF = log_e(Number of documents/ Number of documents in which the term appears)</p><p>Basically TF-IDF increases the value of the words or token which are important for the document.</p><p>TF-IDF is used by search engines to rank the documents relevant to the query done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzJlnHTE_YFtGTCmKEzXoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuKxYTsYTJ1uzmEWadhAoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1E_vzoG5WK3ygSM41teHw.png" /></figure><p>CountVectorizer gives the sheer volume of the word usage but TF-IDF presents the importance of the word in the document.</p><p>Consider a problem of text classification. Some of the words are of importance in certain kind of documents. Consider a document on a medicine will have some medical terms will be of importance in that document and these terms will be highlighted by the TF-IDF. Similar consider a document related to sports the terms related to sports and games will be highlighted by TF-IDF.</p><p><strong>Using Word Embeddings for simple Text Classification Problem</strong></p><p>Let us look at simple test classification problem and using word embeddings to solve it.</p><p>This is a problem of Spam message classification. This is a dataset taken from Kaggle with CC0 License.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuBb99OfA2CzZDsT76VzbA.png" /></figure><p>Read the messages into pandas dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cB1u7NpHiCExl50-g6H0Rw.png" /></figure><p><strong>Using CountVectorizer as Word Embedddings</strong></p><p>Fit the word embeddings with CountVectorizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NT7Y_eIlLHHuQbWn9DqKwg.png" /></figure><p>Use Label Encoder from Sci-kit learn to encode the labels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofoncxyBLcPtE-x11IT0Bg.png" /></figure><p>Split the data set into training and test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWQwwdmJ4HY7jtlrTtF3Zw.png" /></figure><p>Now we create a simple neural network model using Keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY_SUAaoNZUpUBBrklISMw.png" /></figure><p>We have created simple model with 2 hidden layers each of 64 nodes and 32 nodes. We have used the Softmax layer to get the outputs as ham and spam.</p><p>We use adam optimizer for optimization and categorical cross entropy for the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr-afMF2TzXtGwQb132jgw.png" /></figure><p>We can use the evaluate function to evaluate our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHX_qSrph0n9T87I_XQB2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOB-yYx-MFSjO9eHu2uwsg.png" /></figure><p><strong>Using TF-TDF as Word Embedding<br> </strong>Fit the vectors with TF-TDF</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIubz0Hb-dJsyBkVrl4h0w.png" /></figure><p>Use Label Encoder from Sci-kit learn to encode the labels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofoncxyBLcPtE-x11IT0Bg.png" /></figure><p>Split the data set into training and test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWQwwdmJ4HY7jtlrTtF3Zw.png" /></figure><p>Now we create a simple neural network model using Keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY_SUAaoNZUpUBBrklISMw.png" /></figure><p>We have created simple model with 2 hidden layers each of 64 nodes and 32 nodes. We have used the Softmax layer to get the outputs as ham and spam.</p><p>We use adam optimizer for optimization and categorical cross entropy for the loss.</p><p>Evaluate the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7VXWgDonah-Lr1yP68LTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqO6zBoubB3g_oVNIxeQ6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJqJV1PmE-zXd6erCNk-7A.png" /></figure><p>The predict function can be used to make the predictions.</p><p>Get the summary of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE4ETF-QNGkfYqKfv-bkzQ.png" /></figure><p><strong>Using Hashing Vectorizer as Word Embedding</strong></p><p>Fit the vectors with Hashing Vectorizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbSi9c-Ay8keaL55G_huLA.png" /></figure><p>Usage of the label Encoder and the creation of the model remain the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTrI3lXQQ16xubengUEo-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvWZGl1VdoZJ9PUTAa0YPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6bze-VTEK230gf2JnfX5w.png" /></figure><p>We see that number of parameters are reduced and it depends on the size of the feature used.</p><p><strong>Conclusion</strong></p><p>The CountVectorizer, Hashing Vectorizer and TF-IDF Vectorizer can be used to create the word embeddings for the words for natural language processing tasks.</p><p>The memory required in terms of parameters is lesser in hashing vectorizer. The number of parameters depends on the size of features. Also in hashing vectorizer the amount of storage for the vocabulary is saved as vocabulary is not stored in Hashing Vectorizer.</p><p>The TF-IDF gets better accuracy for a slightly complex classification jobs as the occurrence of the word in the particular type of document is given importance.</p><p><strong>Authors</strong></p><p>Srinivas Chakravarthy — srinivas.yeeda@gmail.com</p><p>B N Chandrashekar — chandru4ni@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5484eeb05c06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simple-word-embedding-for-natural-language-processing-5484eeb05c06">Simple Word Embedding for Natural Language Processing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preprocessing for Natural Language Processing]]></title>
            <link>https://srinivas-yeeda.medium.com/preprocessing-for-natural-language-processing-498df071ab6e?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/498df071ab6e</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 15:50:27 GMT</pubDate>
            <atom:updated>2020-07-03T15:50:27.135Z</atom:updated>
            <content:encoded><![CDATA[<p>Raw data for natural language processing is received from lot of sources and it needs to be cleaned and preprocessed before applying any model to the data.</p><p>Following are some of methods used in pre- processing</p><p>Tokenization</p><p>Stop words removal</p><p>Stemming</p><p>Normalization</p><p>Lemmatization</p><p>Parts of speech tagging</p><p>Text Enrichment or Augmentation</p><p>Word Embedding or Text Vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYYClzVEXlrtSRPQ1hY8zQ.jpeg" /><figcaption>Photo by Kelly Sikkema on Unsplash</figcaption></figure><p><strong>Stop Words Removal</strong></p><p>Stop word removal is one of the preprocessing techniques in the NLP. Stop words are the most commonly occurring words in English or any language like a, the, in, on etc. When we do a text classification these words do not add much value. These stop words could be removed so that the number of tokens are reduced and performance of the model improves.</p><p>There are number of ways of removing the stop words with different libraries.</p><p><strong>Stop words removal with NLTK</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25PM5tCu3Lr0bJYWzX7YFA.png" /></figure><p><strong>Stop words removal with Gensim</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r-WRr9cCs7g6PDHJcay4Q.png" /></figure><p>Stop words removal reduces the amount of data and increases the performance of model. It also reduces the time taken for training.</p><p>Stop words removal can be problematic when the context is affected. When the sequence to sequence models are used then removing the stop words can affect the context. Stop word removal need to be avoided when we are generating models for sentiment analysis, language translation, question answer models.</p><p>Stop words can be used when we are doing text classification models. It is mostly employed when classical NLP techniques such as Bag of Words, TF-IDF models are used. Stop word removal is not used when the deep learning , sequence to sequence models like RNN, LSTM are used.</p><p><strong>Stemming and Lemmatization</strong></p><p>In English a lot of the words are derived from a root word. For example recovery, recovers, recover, recovered, recovering are derived from the root word recover.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*29PJCd5tJWxCkezmQ-6YoQ.png" /></figure><p>Stemming and lemmatization are the processes of removing the letters from the word to match the root word. Stemming and lemmatization reduce the inflectional forms. This reduces the number of tokens so it improves the performance of model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ipsu9eU9QPR8MxXIHsZXoQ.png" /></figure><p>Stemming follows a crude heuristic way in which the letters in the end are chopped off. The word which remains may not be an exact English word. In the above example stem of the tried becomes tri after removing the letters ‘ed’ but ‘trying’ becomes ‘try’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*wPqibm4aIcAEAhzHZk9r0Q.png" /></figure><p>Stemming may get exact English word in some occasions.</p><p>Lemmatization uses vocabulary and context of the word to get a proper lemma (word) when the lemmatization is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*KHI46i4qgZXEEhFzbn-8Sw.png" /></figure><p>Stemming is faster than lemmatization as the chopping of the letters is done but in case of lemmatization there needs to be a search in corpus for a proper word.</p><p><strong>Stemming with NLTK</strong></p><p>There are 4 types of stemmer porter stemmer, Lancaster stemmer, regexp stemmer and snowball stemmer depending on the algorithm used for stemming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UoFbas6gvxqXUg8PtyTLWA.png" /></figure><p><strong>Lancaster Stemmer</strong></p><p>This is stemmer based on Lancaster (Paice/Husk) stemming algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMDk9CQLof0pYxqEYuMG3w.png" /></figure><p><strong>Regexp Stemmer</strong></p><p>This stemmer uses regular expression to chop the suffix. This takes the custom suffixes given as inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5mtfr8E61hmY7dFHs6Y8A.png" /></figure><p><strong>Porter Stemmer</strong></p><p>This is a stemmer based on Porter stemming algorithm . You can select the mode for the stemmer. You can either select ORIGINAL_ALGORITM, MARTIN_EXTENIONS, NLTK_EXTENSIONS. NLTK extension is taken as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYGyZrVBdN0wvhxISTNPGw.png" /></figure><p><strong>Snowball Stemmer</strong></p><p>This stemmer provides a port of Snowball stemmers developed by Martin Porter. This has stemmers for different languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfZZOUVtwDoJXJZJUyyzRw.png" /></figure><p><strong>Stemming with genism</strong></p><p>Gensim only supports porter stemmer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTrESZCjJrxemV74p4z0Cw.png" /></figure><p><strong>Lemmatization with NLTK</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUrcA53gJVwffTzWdj53Jw.png" /></figure><p><strong>Normalization</strong></p><p>Normalization is another method of cleaning the text before the model is applied. Normalization involves cleaning of data like removing #tags, removing the prefixed or suffixed unnecessary data like dots, converting the case of the text data to lower / upper case. When the data is normalized the performance of stemming and lemmatization also improve. Following figure below shows some methods of normalization of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*2GiNsf8o9ZUk7TlmqkYlng.png" /></figure><p><strong>Conversion of Text to lower or upper case</strong></p><p>Text data received can have data with mixed case like lower or upper case. It is general to convert the case of text to lower case. This method which makes processing simple without having to worry about taking care of Capitalization of words or letters in the text. However care should be taken for special cases like US and us, since these two words have different meaning and will become same after lowercasing.</p><p><strong>Transformation to Canonical Form</strong></p><p>Lot of text data generally in tweets is received in short forms like 2morrow for tomorrow or there can be data ‘: )’ for smile etc. These need to be converted to normal forms. This method allows the text to be transformed into some standard form. As part of the process it allows words with same meaning but with different spellings to be transformed into single word. For example, goood, gud, should be transformed to good. Cross-words, crossword, cross words should be transformed to “crosswords”. It removes extra white spaces. It transforms numbered words to numeric form.</p><p><strong>Text Noise Removal</strong></p><p>There can be lot of prefixed or suffixed data which needs to be removed. Noise refers to all text which does not contribute to text analysis like digits, punctuation, special characters. They may interfere with text analysis and hence removing noise helps the NLP models to perform better and improve accuracy. It removes extra white spaces, html tags, and unknown characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*FfO3hOBMpiyvsABFvTyjEg.png" /></figure><p><strong>Correction of Spelling mistakes</strong></p><p>There can also lot of spelling mistakes in data which needs to be corrected.</p><p><strong>Handling of numerical text</strong></p><p>The numbers in the text data need to be either removed or converted into a word.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*7gdAjNKVQiWE7o7adUnvnw.png" /></figure><p>Regular expression in python can be used for normalization.</p><p><strong>Text Enrichment or Augmentation</strong></p><p>This method involves in extending the data set using few operations based on the data type of data in the data set. It can be achieved by enriching the data set with information which previously did not exist. It provides more semantics to the text and hence improves the predictive accuracy. The data can be augmented using external knowledge sources, sentence or word shuffling, word replacement, and adding new words based on context.</p><p><strong>Tokenization</strong></p><p>This method allows the sentences to be changed to words, paragraph to sentences to words where each word can be treated as token and be used for processing in NLP.</p><p><strong>Word Embedding or Text Vectors</strong></p><p>This is the modern way of representing words as vectors. It allows the high dimensional word features in text to be represented as word vectors. The words are represented by vectors using suitable methods which maintain the relationship of words. That means if the vectors are represented in co-ordinate system, the words closer will be placed closer in the representation.</p><p><strong>Authors</strong></p><p>Srinivas Chakravarthy : srinivas.yeeda@gmail.com</p><p>Chandrasekhar B N : chandru4ni@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498df071ab6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokenization for Natural Language Processing]]></title>
            <link>https://medium.com/data-science/tokenization-for-natural-language-processing-a179a891bad4?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/a179a891bad4</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 11:23:06 GMT</pubDate>
            <atom:updated>2020-07-10T16:37:52.413Z</atom:updated>
            <content:encoded><![CDATA[<p>Natural language processing is one of the fields in programming where the natural language is processed by the software. This has many applications like sentiment analysis, language translation, fake news detection, grammatical error detection etc.</p><p>The input in natural language processing is text. The data collection for this text happens from a lot of sources. This requires a lot of cleaning and processing before the data can be used for analysis.</p><p>These are some of the methods of processing the data in NLP:</p><ul><li>Tokenization</li><li>Stop words removal</li><li>Stemming</li><li>Normalization</li><li>Lemmatization</li><li>Parts of speech tagging</li></ul><p><strong>Tokenization</strong></p><p>Tokenization is breaking the raw text into small chunks. Tokenization breaks the raw text into words, sentences called tokens. These tokens help in understanding the context or developing the model for the NLP. The tokenization helps in interpreting the meaning of the text by analyzing the sequence of the words.</p><p>For example, the text “It is raining” can be tokenized into ‘It’, ‘is’, ‘raining’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytMHEQlqqOXY8UHv2fkxmA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@soulsana?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">SOULSANA</a> on <a href="https://unsplash.com/s/photos/scrabble?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are different methods and libraries available to perform tokenization. NLTK, Gensim, Keras are some of the libraries that can be used to accomplish the task.</p><p>Tokenization can be done to either separate words or sentences. If the text is split into words using some separation technique it is called word tokenization and same separation done for sentences is called sentence tokenization.</p><p>Stop words are those words in the text which does not add any meaning to the sentence and their removal will not affect the processing of text for the defined purpose. They are removed from the vocabulary to reduce noise and to reduce the dimension of the feature set.</p><p>There are various tokenization techniques available which can be applicable based on the language and purpose of modeling. Below are a few of the tokenization techniques used in NLP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*FTEu803GEsNrNslvY1RbXQ.png" /></figure><p><strong>White Space Tokenization</strong></p><p>This is the simplest tokenization technique. Given a sentence or paragraph it tokenizes into words by splitting the input whenever a white space in encountered. This is the fastest tokenization technique but will work for languages in which the white space breaks apart the sentence into meaningful words. Example: English.</p><p><strong>Dictionary Based Tokenization</strong></p><p>In this method the tokens are found based on the tokens already existing in the dictionary. If the token is not found, then special rules are used to tokenize it. It is an advanced technique compared to whitespace tokenizer.</p><p><strong>Rule Based Tokenization</strong></p><p>In this technique a set of rules are created for the specific problem. The tokenization is done based on the rules. For example creating rules bases on grammar for particular language.</p><p><strong>Regular Expression Tokenizer</strong></p><p>This technique uses regular expression to control the tokenization of text into tokens. Regular expression can be simple to complex and sometimes difficult to comprehend. This technique should be preferred when the above methods does not serve the required purpose. It is a rule based tokenizer.</p><p><strong>Penn TreeBank Tokenization</strong></p><p>Tree bank is a corpus created which gives the semantic and syntactical annotation of language. Penn Treebank is one of the largest treebanks which was published. This technique of tokenization separates the punctuation, clitics (words that occur along with other words like I’m, don’t) and hyphenated words together.</p><p><strong>Spacy Tokenizer</strong></p><p>This is a modern technique of tokenization which faster and easily customizable. It provides the flexibility to specify special tokens that need not be segmented or need to be segmented using special rules. Suppose you want to keep $ as a separate token, it takes precedence over other tokenization operations.</p><p><strong>Moses Tokenizer</strong></p><p>This is a tokenizer which is advanced and is available before Spacy was introduced. It is basically a collection of complex normalization and segmentation logic which works very well for structured language like English.</p><p><strong>Subword Tokenization</strong></p><p>This tokenization is very useful for specific application where sub words make significance. In this technique the most frequently used words are given unique ids and less frequent words are split into sub words and they best represent the meaning independently. For example if the word few is appearing frequently in the text it will be assigned a unique id, where fewer and fewest which are rare words and are less frequent in the text will be split into sub words like few, er, and est. This helps the language model not to learn fewer and fewest as two separate words. This allows to identify the unknown words in the data set during training. There are different types of subword tokenization and they are given below and Byte-Pair Encoding and WordPiece will be discussed briefly.</p><ul><li>Byte-Pair Encoding (BPE)</li><li>WordPiece</li><li>Unigram Language Model</li><li>SentencePiece</li></ul><p><strong>Byte-Pair Encoding (BPE)</strong></p><p>This technique is based on the concepts in information theory and compression. BPE uses Huffman encoding for tokenization meaning it uses more embedding or symbols for representing less frequent words and less symbols or embedding for more frequently used words.</p><p>The BPE tokenization is bottom up sub word tokenization technique. The steps involved in BPE algorithm is given below.</p><ol><li>Starts with splitting the input words into single unicode characters and each of them corresponds to a symbol in the final vocabulary.</li><li>Find the most frequent occurring pair of symbols from the current vocabulary.</li><li>Add this to the vocabulary and size of vocabulary increases by one.</li><li>Repeat steps ii and iii till the defined number of tokens are built or no new combination of symbols exist with required frequency.</li></ol><p><strong>WordPiece</strong></p><p>WordPiece is similar to BPE techniques expect the way the new token is added to the vocabulary. BPE considers the token with most frequent occurring pair of symbols to merge into the vocabulary. While WordPiece considers the frequency of individual symbols also and based on below count it merges into the vocabulary.</p><p>Count (x, y) = frequency of (x, y) / frequency (x) * frequency (y)</p><p>The pair of symbols with maximum count will be considered to merge into vocabulary. So it allows rare tokens to be included into vocabulary as compared to BPE.</p><p><strong>Tokenization with NLTK</strong></p><p>NLTK (natural language toolkit ) is a python library developed by Microsoft to aid in NLP.</p><p>Word_tokenize and sent_tokenize are very simple tokenizers available in NLTK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0YZW6ngmy2kIzzp1VmAxQ.png" /></figure><p>It basically returns the individual works from the string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4eHX3aFLzQoQwu9fLPZjg.png" /></figure><p>Sent_tokenize splits the string into multiple sentences. The sent_tokenizer is derived from PunktSentenceTokenizer class. The sent_tokenize uses the pre trained model from tokenizers/punkt/english.pickle. There are pre trained models for different languages that can be selected. The PunktSentenceTokenizer can be trained on our own data to make a custom sentence tokenizer.</p><p>custom_sent_tokenizer = PunktSentenceTokenizer(train_data)</p><p>There are some other special tokenizers such as Multi Word Expression tokenizer (MWETokenizer), Tweet Tokenizer.</p><p>The MWETokenizer takes a string which is already been divided into tokens and retokenizes it, merging multiword expressions into single token, by using lexicon of MWEs.</p><p>Consider the sentence “He completed the task in spite of all the hurdles faced”</p><p>This is tokenized as [‘He’, ‘completed’, ‘the’, ‘task’, ‘in’, ‘spite’, ‘of’, ‘all’, ‘the’, ‘hurdles’, ‘faced’]</p><p>If we add the ‘in spite of’ in the lexicon of the MWETokenizer, then when the above tokens are passed to MWETokenizer it will be tokenized as [‘He’, ‘completed’, ‘the’, ‘task’, ‘in spite of’, ‘all’, ‘the’, ‘hurdles’, ‘faced’]</p><p>The TweetTokenizer addresses the specific things for the tweets like handling emojis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9x0CNwpDds6gJCyu97sdA.png" /></figure><p>RegexpTokenizer</p><p>This tokenizer splits the sentence into words based on regular expression. For example in the below example, the tokenizer forms the tokens out of money expressions and any other non-whitespace sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUY9B-hQaJgUblAoe8Hwsg.png" /></figure><p><strong>Tokenization with Textblob</strong></p><p>Textblob is used for processing of text data and is a library in Python. Similar to other packages it provides APIs for sentiment analysis, parts of speech tagging, classification, translation and so on. Below is the code fragment to tokenize into sentence and words and you can notice in the output the emoji’s are removed from the punctuation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pDkvXn7CdgWmd-4uvpDWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7qIWpQuj50Lr5J3mgh3xA.png" /></figure><p><strong>Tokenization with Gensim</strong></p><p>Gensim is one of the libraries mainly used for Topic Modelling. Gensim provides utility functions for tokenization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeOGMNXtE-LhdhbELkXaHw.png" /></figure><p>Gensim also has a sentence tokenizer. Split_sentences from the text cleaner does this sentence tokenization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlmmAD-rSVShVc1TUEv3SQ.png" /></figure><p><strong>Tokenization with Keras</strong></p><p>Tokenization can also be done with Keras library. We can use the text_to_word_sequence from Keras. preprocessing.text to tokenize the text. Keras uses fit_on_words to develop a corpora of the words in the text and it uses this corpus to create a sequence of the words with the text_to_word sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vcE9weV3IKNc7XknMoNig.png" /></figure><p><strong>Challenges in Tokenization</strong></p><p>There are lot of challenges in tokenization, but we discuss few of the difficulties in segmentation of the words.</p><p>One of the biggest challenges in the tokenization is the getting the boundary of the words. In English the boundary of the word is usually defined by a space and punctuation marks define the boundary of the sentences, but it is not same in all the languages. In languages such as Chinese, Korean, Japanese symbols represent the words and it is difficult to get the boundary of the words.</p><p>Even in English there are lot of symbols used as £, $, € followed by numerical to represent money and there are lot of scientific symbols such as µ, α etc. which create challenges in tokenization.</p><p>There are also lot of short forms used in English such as I’m (I am), didn’t (did not) etc. which needs to resolved or else these cause a lot of problems in next steps of NLP.</p><p>There is still a lot of research going on in this field of NLP and we need to select the proper corpora for the NLP task at hand.</p><p><strong>References:</strong></p><p>Gensim documentation: <a href="https://pypi.org/project/gensim/">https://pypi.org/project/gensim/</a></p><p>NLTK documentation: <a href="https://www.nltk.org/">https://www.nltk.org/</a></p><p>Keras Documentation: <a href="https://keras.io/">https://keras.io/</a></p><p><strong>Authors</strong></p><p>Srinivas Chakravarthy — srinivas.yeeda@gmail.com</p><p>Chandrasehkar Nagaraj — chandru4ni@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a179a891bad4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tokenization-for-natural-language-processing-a179a891bad4">Tokenization for Natural Language Processing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization for Machine Learning]]></title>
            <link>https://medium.com/data-science/data-visualization-for-machine-learning-d1f906664f56?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1f906664f56</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Fri, 22 May 2020 13:15:24 GMT</pubDate>
            <atom:updated>2020-07-08T14:08:58.927Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the data is one of the very important topics in machine learning. We get a lot of raw data in real world problems and we need to derive meaningful information out of the data to solve the problems.</p><p>There are two kinds of problems in machine learning. Regression and classification. Consider a problem where we are required to predict the cost of a house. Here we need to predict a numeric value. This problem becomes a regression problem. Some time we need to take a “Yes” or “No” decision. This is a binary classification problem. Sometimes we need to predict a class. Consider a problem where we are required to predict an animal like cat, dog, horse etc. This is a multi-class classification problem.</p><p>Whenever we get the data for a problem for supervised learning, we get attributes and labels. Attributes are independent variables with which we must predict the labels or dependent variables. Attributes are called inputs, predictors, features, independent variables. Labels are called outputs, targets, outcomes, dependent variables. If the labels are categorical the problem becomes a classification problem, if it is numerical it becomes regression problem.</p><p>When you get the data for any problem there will be lot of attributes. We need to select the features from these attributes. The problem is when we get the data there are lot of related as well as unrelated attributes. We need to check the correlation of these attributes with the output. We need to select the features depending on the correlation with the output data. We need to differentiate between good and bad attributes that can be selected.</p><p>One of the most time-consuming steps in the machine learning or making a predictive model is feature selection or feature engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kf224P6ykNRXkv8WYBGUVw.jpeg" /><figcaption>Photo by Scott Blake on Unsplash</figcaption></figure><p><strong>Studying the data</strong></p><p>Data contains the attributes and labels. Among many ways of understanding the data, below are two main methods. Understanding the data with descriptive statistics and understanding the data with data visualizations</p><p><strong>Understanding the Data with descriptive statistics</strong></p><p>Following are the ways in which we can analyze the data</p><p>1. Looking at the raw data to understand the problem</p><p>2. Understand the size of the data</p><p>3. Check if there are any missing data</p><p>4. Understand the type of the data</p><p>5. Summarize the descriptive statistics of data to understand better.</p><p>6. Understand the relations between the attributes with correlation.</p><p><strong>Understanding the data types of attributes in the data set</strong></p><p>The data, in general, will be of two types, quantitative and qualitative. Quantitative data consists of numbers only and qualitative data consists of data other than numbers. Based on how the data is collected, organized, stored and formatted, qualitative data is further divided into structured and unstructured data.</p><p>Structured data consists of number or words and will fall into either nominal or ordinal data. Nominal data also called categorical data can be either labels, numbers or texts and represent a category. For example, male and female can be represented as either 0 or 1 or M and F. Ordinal data are similar to nominal data but in addition, the elements of data can be ordered or ranked based on preferences. For example, the income of people can be categorized as high, medium or low based on the earnings.</p><p>Texts, videos, images and audio belong to unstructured data.</p><p>Quantitative data is further divided into continuous and discrete data. Continuous data can take any value within a range and generally represented using decimal or float. For example, 1.23, 2.45, etc. Discrete data take values which in general cannot be further subdivided meaningfully, it represents discrete values and represented using whole numbers. For example, count of apples, 10, 20, 22, 34, etc.</p><p>Qualitative data is further divided into interval data and ratio data. Interval data does not have origin or base (absolute zero) and has the characteristics of nominal and ordinal data. So, interval data allows negative values, and supports only addition and subtraction operations only (because of absence of origin or base). For example, the temperature values in Celsius and Fahrenheit but not in Kelvin (Kelvin has absolute zero). Ratio data has characteristics of nominal, ordinal and interval data and in addition, has origin or base. So, it allows all four operations — addition, subtraction, multiplication and division. For example, temperature values in Kelvin.</p><p>In the field of data science, it is also found that data is categorized into four basic types — Numerical data, Categorical data, Time series data and Text.</p><p>Numerical data represent any values which are numbers, and it is further divided into continuous and discrete data which have the same meaning described above.</p><p>Categorical data represents characteristics of nominal and ordinal data described above.</p><p>Time series data represents sequence of numbers collected over some interval or period of time at specific or regular intervals of time. For example, average number of homes sold (sales) for some years. Time series data is not just collection of numbers (numerical data) but they are ordered over time.</p><p>Text data is in general just words. For machine learning and deep learning, the words are usually converted to numbers using different approaches.</p><p><strong>Descriptive Measures of the data</strong></p><p>Descriptive measures give the statistical understanding of the data. They give an understanding of how the data is located and what is the spread of the data. Descriptive statistical analysis is very important step in drawing conclusions from the data. It forms an initial step in understanding the data.</p><p>There are two kinds of descriptive measures of the data, measures of central tendency and measures of spread.</p><p><strong>Measures of Central Tendency</strong></p><p>Mean, median and mode are the measures of central tendency. Tendency of the data to cluster around some value is called central tendency.</p><p>Mean of the sample of data is the sum of all values divided by the number of the values. It is the most commonly used and reliable method of central tendency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*hYYC2rZR_X5eggzubS2sIA.png" /></figure><p>Calculation of the mean is based on every value, so it is very much affected by outliers. So, when there are extreme values then mean is not a good measure of central tendency.</p><p>Median is the middle point in the ordered samples. It is also called the <strong>50th percentile. </strong>Median is much less affected by the outliers or skewed data than the mean.</p><p>Mode is the value which occurs the greatest number of times in the sample. Mode is the only central tendency that can be applied to the categorical variables.</p><p><strong>Measures of variance or spread</strong></p><p>Variance is second important property that describes the data. Variance is the amount of spread or dispersion of the data. Most popular measures of spread are range, inter-quartile range, variance and standard deviation.</p><p>Range is simply the difference between the largest and the smallest values. The smallest value is the minimum of the sample and largest value is the maximum of the sample. It only depends on 2 observations so it useful to represent the dispersion of small data sets.</p><p>Inter-quartile range is the difference between third quartile value and 1st quartile value. Quartiles divide the rank ordered dataset into 4 parts. The values that separate parts are called Q1, Q2, Q3</p><p>IQR is Q3 — Q1</p><p>Variance is the sum of the squares of the difference between the value and the mean divided by the number of samples — 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*8TGgIyIu7mecvznqrt1o4w.png" /></figure><p>Standard deviation is the square root of variance. These two are the most commonly used measures of variation. These statistics tell how the values fluctuate around the mean. If the concentration of the data around the mean is high, then the standard deviation will be low and vice-versa.</p><p><strong>Understanding the relation between Attributes</strong></p><p>Understanding of the relationship between the attributes is important to select the features to be used in the creation of the model. There may a lot of attributes which are redundant or dummy attributes. These attributes need to be removed while training the model. Using redundant attributes increases the time for training as well as the computational load. Also, the data of the attributes may be skewed. The data may not lie in the perfect normal distribution. When the data is skewed the performance of the model will not improve even on the hyper parameter tuning. Relationship between the data can be understood using Pearson’s correlation coefficient and checking the skewed data.</p><p><strong>Pearson’s Correlation Coefficient</strong></p><p>Pearson’s Correlation Coefficient is a statistical value that helps to understand the relationship between a pair of attributes or an attribute and the labels or outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*UdKQ3cPr0ILhjRRkbBoQ-w.png" /></figure><p>where x and y are the 2 attributes and x bar and y bar are the mean of the attributes</p><p>The value of this coefficient can vary between -1 and 1 .</p><ul><li>The value of 0 denotes that there is no relationship between the 2 attributes</li><li>The value of 1 denotes that there is a perfect correlation between the 2 attributes</li><li>The value of -1 denotes there is a negative correlation between the 2 attributes</li></ul><p>If the value of the Pearson’s coefficient is closer to 1 then there is very close correlation between the attributes and having both the attributes in your model will increase the amount of training and compute. You can either omit one of the attributes or features from the model or apply PCA (Principal Component Analysis) to reduce the dimensions of the features.</p><p>Pearson’s coefficient can be applied between attribute and target variable. If the value of coefficient is near 0 then there is no relationship between feature or attribute and the output and we can ignore the feature. If the value of the coefficient is negative value and near to 0 then also it is better to ignore the feature. There are pandas functions to find the Pearson’s correlation coefficient.</p><p><strong>Skewed data</strong></p><p>Generally, data for the attributes is normally distributed. The data usually lies in Bell Curve. Sometimes it happens that there is a skewed data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*-_WRwcQ0xTX_vNUBDQcLaw.jpeg" /></figure><p>Note: This picture is taken from Wikipedia.</p><p>When the data is normally distributed the mean, median and mode are same and the data is evenly distributed on both sides of mean. Sometimes there can be a positive skew or data is skewed towards the left of mean, or a negative skew where the data is skewed towards the right of the mean.</p><p>When we have skewed data the performance of the model does not improve even on the tuning of the hyper parameters. This is because we are deviating from the assumption for the regression that the data is normally distributed. This data needs to be manipulated before training with this data. One of the popular ways of dealing with the skewed data is applying log transformation. Another way of dealing with skewed data is applying box cox transformation.</p><p><strong>Understanding the data with visualizations</strong></p><p>Data visualizations are one of the fastest ways of understanding about the data. Data visualization for the attributes can be done independently or combined with another attribute. The independent visualization of data is done with uni-variate plots and the visualizations done to check the relationship with other attribute/s are multivariate plots.</p><p><strong>Univariate plots</strong></p><p>Univariate plots are used to understand the data of each attribute independently. Histogram, density plot and box plot and whisker plots are some of the univariate plots.</p><p><strong>Histogram</strong></p><p>Histogram is used to get the distribution of data. The data is put into different bins or intervals and frequency of the observations is captured in the plot. The figure below gives an example of the histogram of housing prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*iN7nuqwQuJj_SlftggHeNw.png" /></figure><p>Histogram gives the following information about the data.</p><ul><li>It gives the count of observation</li><li>It gives the distribution of the data.</li><li>It tells if the data is normally distributed or not.</li><li>It indicates if data is skewed.</li><li>It also gives information if there are any outliers in the data.</li><li>It gives the spread of data.</li></ul><p><strong>Density plots</strong></p><p>Density plots visualizes the distribution of data over continuous interval. Unlike the histogram there are no bins assigned for intervals so we can see the continuous distribution of the data. The visual appearance of histogram depends on choice of bin width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*RugCV0a14ksQfP4mdXFyIQ.png" /></figure><p><strong>Box and Whisker Plots</strong></p><p>Box plot can use used to show the shape of distribution, central value and variability. The green middle line shows the median of the data and the edges of the box show the third and first quartile of the data. The lines attached to the box are called whiskers and the ends show the maximum and minimum values of the data. The box plots give the range and the inter quartile range for the data. Box plot also shows the outliers. The points lying above or below the whiskers show the outliers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*UB61aYs3CDVSqdolAUHHYg.png" /></figure><p><strong>Multivariate Plots</strong></p><p>When there are multiple parameters or attributes involved in a plot, they are called multivariate plots. Multivariate plots are used to understand the interdependence of two or more attributes. Correlation matrix plots and scatter plots are some of the plots used to understand the correlation of the attributes in machine learning.</p><p><strong>Correlation Matrix Plot</strong></p><p>Correlation matrix is a table showing the correlation between the variables. Each cell in the matrix shows the correlation between the two variables. Correlation between the variables indicates how the variables are inter-related. It shows how the variable will vary on the variation of the other variable. Correlation can be positive or negative. If a variable change in the same direction as other variable then the variables are positively correlated. When the variable change in opposite direction on the change of the other variable then the 2 variables are negatively correlated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*KZIliqOY_ZgwTh3he-4nuQ.png" /></figure><p>This picture gives the correlation between the variables. Here the houses sold and borough_flag have negative correlation. The borough_flag and number of crimes have no correlation.</p><p>Following things can be learned from the correlation matrix plots</p><p>· Understand the correlation between the variables or attributes.</p><p>· If there is a lot of correlation between the variables the linear regression can have unreliable results so sometimes we can remove one of the variables from the model .</p><p><strong>Scatter Plots</strong></p><p>Scatter plot uses dots to represent values for set of variables x and y. It is basically to determine if there is any statistical relationship between the two variables x and y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*q_YulKTGLwSJVhgZn8K1Ng.png" /></figure><p>The picture above shows a scatter matrix of variables A, B, C,D, E. There can be following relationships between the variables. There can be a positive correlation, negative correlation, non-linear relationship or no correlation between the variables. In the figure above there exists a positive correlation between variables A and B. There is a negative correlation between variables A and C. There is a non-linear correlation between variables A and E. There is no correlation between variables A and D.</p><p>The scatter plots also can identify if there are any outliers in the data.</p><p><strong>Visualization of data of multiple classes</strong></p><p>Sometimes we need to visualize the data for the classification problems where there is data for multiple classes. Many times, the number of dimensions of the attribute data will be very huge and none of the above techniques would help in reducing the dimensions. In those scenarios, PCA, LDA and t-SNE techniques are used for feature extraction and dimension reduction. These techniques reduce the dimension of the data and help us visualize how the data for the different classes are separated.</p><p><strong>Principal Component Analysis (PCA)</strong></p><p>It is an unsupervised linear transformation technique which based on the correlation of data and will identify patterns in data. It is a projection-based method which looks for directions of maximum variance in high dimensional data and transforms the data by projecting it onto a set of orthogonal axes in a new subspace with equal or fewer dimensions. The visualization of PCA with new axes will show projection which spreads the data and which form clusters in some way. Below are the clusters of data after applying PCA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*3dBCKMB9sSWtL6b6LPbJlw.png" /></figure><p>This visualization helps us identify the separation between the data for different classes. If the data is not separated the number of principal components needs to be increased to check if we get the separation. These principal components can now be used in building our model.</p><p><strong>Linear Discriminant Analysis (LDA)</strong></p><p>It is similar to PCA wherein it finds the component axes which maximizes the variance of the data but in addition it preserves as much as class discriminatory information as possible. So the objective of LDA is again to project the original data onto a set of axes in a new subspace with equal or fewer dimensions but in addition the new axes will be such that they maximize the separation between multiple classes. Below are the clusters of data after applying LDA to same data set above for which PCA was applied. It can be seen the class separation is more visible when LDA is used.</p><p>2 Component LDA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*INNmYPwzVenHKRjeNg9qWQ.png" /></figure><p><strong>The t-Distributed Stochastic Neighbor Embedding (t-SNE)</strong></p><p>It is a unsupervised non-linear technique for visualization of data. The main benefit of t-SNE is it preserves the local and global structure within the data. That means the points in the original data which are closer will tend to remain closer in low dimensions. The t-SNE method determines the similarity measure between two pairs of points in the high dimensional space and in low dimensional space and then using a cost function tries to optimize the two similarity measures. Below are the clusters formed after applying t-SNE to data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*NCeSLeOpb7V0nFQHtmQM2w.png" /></figure><p>Data visualization helps in understanding the data and feature selection for the machine learning model.</p><p>Authors</p><p>Srinivas Chakravarthy :srinivas.yeeda@gmail.com</p><p>Chandrasekhar B N : chandru4ni@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1f906664f56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-visualization-for-machine-learning-d1f906664f56">Data Visualization for Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loss Functions in Deep Learning Models]]></title>
            <link>https://srinivas-yeeda.medium.com/loss-functions-in-deep-learning-models-129866be93e?source=rss-43159ab4d110------2</link>
            <guid isPermaLink="false">https://medium.com/p/129866be93e</guid>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Srinivas Chakravarthy]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 09:29:25 GMT</pubDate>
            <atom:updated>2020-04-24T10:48:24.223Z</atom:updated>
            <content:encoded><![CDATA[<p>A Loss function is a method of evaluation about how well your model evaluates the dataset. If model predictions are correct your loss will be less, otherwise your loss will be very high. Any machine learning, neural network or deep learning problem gets trained to reduce this loss from the loss function by variation of the weights.</p><p>Optimization algorithms help in minimizing the loss by varying the weights and biases ( trainable parameters) to achieve the minimum loss.</p><p>The cost or loss function has an important job in that it must faithfully distill all aspects of the model down into a single number in such a way that improvements in that number are a sign of a better model.</p><p>This can be a challenging problem as the function must capture the properties of the problem and be motivated by concerns that are important to the project and stakeholders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*qJwuGpp3_8ORHIehP6mgqg.png" /></figure><p>The picture gives the 3-dimensional representation of simple loss function with 2 features. The loss is minimum at the lowest point of the hyperbole. The goal of the optimization algorithms is to minimize the loss by varying the weights w1 to w2 to reach the lowest point in the hyperbole.</p><p><strong>Gradient Descent</strong></p><p>Gradient descent is one of important optimization algorithms used in deep learning techniques.</p><p>Consider yourself on top of a hill or some place on the hill and your goal is to reach the lowest point in the valley.</p><p>You make nimble steps towards the valley to reach the lowest point on the valley. This is the intuition behind the gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*wixwzaSRCDA8iqBi4zOaGg.png" /></figure><p><strong>Derivative in Gradient Descent</strong></p><p>A Gradient is simply a vector which is a multi-variable generalization of a derivative(dy/dx) which is the instantaneous rate of change of y with respect to x. It is derivative of a function which is dependent on more than one variable or multiple variables. And a gradient is calculated using partial derivatives. Also another major difference between the gradient and a derivative is that a gradient of a function produces a vector field.</p><p>A gradient gives the direction of movement to minimize the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*B94jw-qe7EOLrJdYftKxJQ.jpeg" /></figure><p>Consider the picture above. This gives variation of the cost function J(w). Here at the initial point gradient dy/dx will be high and it gives an indication that you have still move down to reach the minima. A gradient basically is a tangent drawn at that point in the error function. At the minima the gradient will be 0 or lowest giving indication that it is the minima. Once you go the other side of the curve the gradient will be negative giving indication that you are moving in the wrong direction.</p><p><strong>w=w−η⋅∇J(w)</strong></p><p>Here<strong> w</strong> is the weight and <strong>η </strong>is the learning rate and <strong>∇J(w) </strong>is the partial derivative of the cost function or loss function <strong>J(w).</strong></p><p><strong>Optimization Challenges in Deep Learning</strong></p><p>The loss function may not be always as simple as a quadratic equation. It may have many minima and you may reach a local minima. There may a saddle point where the curve remains flat for a long variation of weights before it is going down again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*cQq_0yYnFI5Hzfqj9arW4Q.jpeg" /></figure><p>Consider this curve it has 2 minima B and A. B is the local minima but the point A is the actual minima. When you reach the point B you do not know if we must go further to get the actual minima as the gradient again becomes negative after crossing point B. This is one of the challenges in optimization.</p><p>Another challenge with the optimization is the saddle point. When you reach the point A below in the loss function you may feel that you have reached minima but you need to still go further to get to the actual minima but the gradient will be almost zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*vv1MY9I-Gb4gBwhJTCX8CQ.jpeg" /></figure><p>Another issue with the optimization is the vanishing gradient .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*WhciayBrRluXITvbUazbaA.jpeg" /></figure><p>In this function at point A and B the gradient is almost zero and you may consider this is the minimum but it may not be the lowest point in the cost function.</p><p><strong>Maximum Likelihood</strong></p><p>There are many functions that could be used to estimate the error of a set of weights in a neural network.</p><p>We prefer a function where the space of candidate solutions maps onto a smooth (but high-dimensional) landscape that the optimization algorithm can reasonably navigate via iterative updates to the model weights.</p><p>Maximum likelihood estimation, or MLE, is a framework for inference for finding the best statistical estimates of parameters from historical training data. Maximum likelihood seeks to find the optimum values for the parameters by maximizing a likelihood function derived from the training data.</p><p>We have a training dataset with one or more input variables and we require a model to estimate model weight parameters that best maps examples of the inputs to the output or target variable.</p><p>Given input, the model is trying to make predictions that match the data distribution of the target variable. Under maximum likelihood, a loss function estimates how closely the distribution of predictions made by a model matches the distribution of target variables in the training data.</p><p>One way to interpret maximum likelihood estimation is to view it as minimizing the dissimilarity between the empirical distribution defined by the training set and the model distribution, with the degree of dissimilarity between the two measured by the KL divergence. Minimizing this KL divergence corresponds exactly to minimizing the cross-entropy between the distributions.</p><p>A benefit of using maximum likelihood as a framework for estimating the model parameters (weights) for neural networks and in machine learning in general is that as the number of examples in the training dataset is increased, the estimate of the model parameters improves. This is called the property of “consistency.”</p><p>Under appropriate conditions, the maximum likelihood estimator has the property of consistency, meaning that as the number of training examples approaches infinity, the maximum likelihood estimate of a parameter converges to the true value of the parameter. Now that we are familiar with the general approach of maximum likelihood, we can look at the error function.</p><p><strong>Loss functions for Linear Regression</strong></p><p>The objective of the linear regression is to get an equation or plot of curve which fits the data points. There are various functions to calculate the loss for the linear regression. They are mean squared error mean absolute error.</p><p><strong>Mean Squared error, L2 Loss</strong></p><p>Mean squared error is the most common loss function used for the regression problem. This is the mean of the square of the errors of predicted value with the actual value. It is also called L2 loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*jYUCXRUowlCEUj5dCh7sgw.jpeg" /></figure><p><strong>Mean Absolute Error, L1 Loss</strong></p><p><a href="https://medium.com/@ewuramaminka/mean-absolute-error-mae-sample-calculation-6eed6743838a">Mean Absolute Error</a> (MAE) is another loss function used for regression models. MAE is the sum of absolute differences between our target and predicted variables. So it measures the average magnitude of errors in a set of predictions, without considering their directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*poNnt6xiTjtUSKm8CZZxLg.jpeg" /></figure><p><strong>MSE vs MAE</strong></p><p>It is easier to solve using Mean squared error but mean absolute error is more resilient to the outliers. Let me explain with an example. Consider the following samples for training.</p><p>Let’s consider RMSE ( Root Mean Square Error) to get in same terms with MAE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*YiVKGsozLpV8lQOHgzgtug.jpeg" /></figure><p>Here the MSE is more biased towards the outliers and the prediction is sensitive to the outliers.</p><p>There is one problem with the MAE. The derivative of MAE is a constant so it is does not converge easily. Even if the error is very less the derivative is constant and it difficult to understand if we are near to the actual value. But the MSE converges well.</p><p>L1 loss is robust to outliers but its derivatives are not continuous making it difficult to arrive at the solution. L2 is very sensitive to the outliers but gives a stable and closed form solution (As the derivative is 0 when very close to the solution)</p><p><strong>Loss functions for Classification</strong></p><p>The objective of the classification problem is to predict the probability of the sample to be part of a class. The output is basically probability value f(x) which is called the score of the input x. Generally, magnitude of the score represents the confidence of the prediction. The target variable y is a binary value either 1 ( if it belongs to the class) or 0 ( it does not belong to the class). Binary cross entropy and categorical cross entropy are some loss functions in the classification problem.</p><p><strong>Binary Cross Entropy</strong></p><p>The loss function binary crossentropy is used on yes/no decisions when there are 2 classes. The loss tells you how wrong your model’s predictions are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*lqAsNqI3XMzwfeWnMwqToA.jpeg" /></figure><p>where ŷ is the predicted value.</p><p>Binary crossentropy measures how far away from the true value (which is either 0 or 1) the prediction is for each of the classes and then averages these class-wise errors to obtain the final loss. Cross-entropy loss increases as the predicted probability diverges from the actual label.</p><p><strong>Categorical Cross Entropy</strong></p><p>Categorical cross entropy is used for multiclass classification problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*Y9Iz2W_UiPom5WoAg5gk2Q.jpeg" /></figure><p>where ŷ is the predicted value.</p><p>Categorical crossentropy will compare the distribution of the predictions (the activation in the output layer, one for each class) with the true distribution, where the probability of the true class is set to 1 and 0 for the other classes. To put it in a different way, the true class is represented as a one-hot encoded vector, and the closer the model’s outputs are to that vector, the lower the loss.</p><p><strong>Loss function in Knowledge Distillation Model</strong></p><p>Knowledge distillation is one of the model compression techniques which was detailed in the paper by Geoffrey Hinton, Oriol Vinyals and Jeff Dean in 2015. Model compression reduces the computations and the size of the target model. It makes them usable across many devices including mobiles where the storage requirement is critical. The main theme behind knowledge distillation is use the knowledge of complex or cumbersome or computations intensive model to a simple model. The simple model will mimic the behavior of the cumbersome model. Below picture gives the details of loss function in Knowledge distillation model. The cumbersome model is called the teacher model and the target or simple model is called the student model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*0rG6tBG8w487TEZq8TlEiQ.jpeg" /></figure><p>The softmax function is given by the expression below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*YpGlNZYGAD0HiiUYUfLSAw.jpeg" /></figure><p>It takes the output of the last layer of the model architecture and outputs the probabilities of each class with target class probability being the highest. It does not give more information other than the ground truth provided in the dataset. For example suppose the final prediction is ‘1’, it will have the maximum probability value for this class label. It does not give any other details like how close it is to other closer numbers like ‘7’ or ‘6’ in the dataset. To get this information in the output layer, softmax function with temperature is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*-oKw89Tps_s-ZNu-0h7Uyw.jpeg" /></figure><p>Softmax function with temperature is given by the expression below. It is same as the softmax function above expect that it divides the input logits zi by the temperature T. This parameter T allows the softmax function to become softer and allows to provide more information of other classes which are closer to predicted class. So it not only gives information on the predicted class but also to which class it is closer. For example if the predicted class label is ‘1’, it not gives highest probility value for ‘1’ class, but gives next higher probablity values to numbers closer to ‘1’, like ‘7’ and ‘6’. This is referred to as ‘Dark Knowledge’ by Hinton in his paper on knowledge distillation. The output of softmax function with temperature are called soft targets. And student model is trained to learn to output these soft targets of the teacher model. So the loss function will be cross entropy of soft targets of teacher model and soft predictions of student model. The soft predictions of the student model are obtained by using the softmax function with temperature, with T value same the one used during training the teacher model. This loss is called the distillation loss.</p><p>However to make the student model to perform better, Hinton in his paper tells to train the student model with another loss called the student loss. This loss function will be the softmax function with T=1. It will calculate the loss between the student model predicted class probabilities using the softmax function with T=1 and actual target labels in the dataset.</p><p>Hence the overall loss function (L) for the student model will be summation of distillation loss (L1) and student loss (L2).</p><p>L = L1 + L2 where,</p><p>L1 = Cross Entropy(σ(ZT, T=τ), σ(ZS,T=t)) where,</p><p>σ(ZT, T=t), is the softmax output of the teacher model with T=t and</p><p>σ(ZS,T=t), is the softmax output of the student model with T=t</p><p>L2 = Cross Entropy(y, σ(ZS, T=1)) where,</p><p>σ(ZS,T=t), is the softmax output of the student model with T=1</p><p>The final loss L = (1 — α)L1 + αL2, where α is the hyper parameter during model training.</p><p><strong>Single Shot Multi Box Detection</strong></p><p>Single shot multi box detection model is one of the object detection models used in deep learning. Wei Liu and colleagues introduced SSD model.It is built over the over a base model. The objective of the model is to detect the location of an object in the model and classify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*oLdwOheuthhYmlF8cWX0EA.jpeg" /></figure><p>Consider you have a cat in the image. SSD model detects the location of the cat in the image, builds a bounding box with co-ordinates x, y, width , height and classifies the object with label cat.</p><p>This model is built on a base model such as VGG16 or mobile net.</p><p>There are default anchor boxes created with different scales and the aspect ratios. There are predication layers added over the base model for object detection at different scales. A set of filters are added on the top of convolutional feature maps to predict detections for different aspect ratios and class categories. These are compared with the ground truth boxes.</p><p>The loss for this kind of model is a combination of classification and linear regression. Classification for the class detection and the regression for the localization detection.</p><p>The loss is expressed with the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*TtQvpVfkxei0YZa-rMnVmg.jpeg" /></figure><p>Hence the overall loss of the SSD model is the combination of the confidence loss and the localization loss.</p><p><strong>Generative Adversarial Network (GAN)</strong></p><p>Ian Goodfellow and his colleagues from University of Montreal introduced GAN in 2014. It allowed learning the variations in the dataset using random samples. It is made up of two networks which play a game against each other. The Generator generates fake samples of data and tries to fool the Discriminator. The aim of the Discriminator is to distinguish between the generated and real input. The Generator model is trained to maximize the probability of the Discriminator in making a mistake in finding the difference between real and fake input. The Discriminator is trained to maximize the probabilities of assigning the correct label to both real and fake images. The sample architecture of GAN model is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*K-bPfS5YuhmFckbk1ebiSg.jpeg" /></figure><p>The overall loss function for the GAN model is given by min max (L1, L2).</p><p>L1 is called the discriminator loss and L2 is called the generator loss.</p><p>L1 = maximize (log D(x) + (1 — log D( G(z) )) where,</p><p>G = Generator</p><p>D = Discriminator</p><p>D(x) is the discriminator’s estimate of the probability that real data instance x is real</p><p>G(z) is the generator’s output for the random input z</p><p>D(G(z)) is the discriminator’s estimate of the probability that fake instance is real, so (1 — log D(G(z))) is the inverse probability that fake instance is real.</p><p>L2 = minimize (1 — log D(G(z)))</p><p>So generator loss is to minimize the inverse probability that fake instance is real.</p><p>The minimax loss function can cause the GAN to get stuck in the early stages of GAN training. It may not provide sufficient gradient for G to learn well. This is because during the early stages of GAN learning, generator may perform poor and D can reject samples with high confidence because the generated samples will be too different from the real data.</p><p>To overcome the above problem the modified generator loss is used,</p><p>L2 = maximize ( log D(G(z)))</p><p>With this generator tries to maximize the probability of generated samples are real samples. This loss improves training in early stages by giving better gradient information for updating weights of the generator model.</p><p><strong>Conclusion</strong></p><p>The selection of loss function used for any model depends on the output expected for the problem at hand. The selection of loss function is very important to optimized solution for any deep learning problem.</p><p><strong>Authors</strong></p><p><strong>B N Chandrashekar, </strong><a href="/service/mailto:chandrashekar.nag@wipro.com"><strong>chandru4ni@gmail.com</strong></a></p><p><strong>Srinivas Chakravarthy, srinivas.yeeda@gmail.com</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129866be93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>