<?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 Prasoon Singh on Medium]]></title>
        <description><![CDATA[Stories by Prasoon Singh on Medium]]></description>
        <link>https://medium.com/@prasoonsingh.lucknow?source=rss-1b889e554b8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5Nh5wDETGR4MGI2k1yQh4g.jpeg</url>
            <title>Stories by Prasoon Singh on Medium</title>
            <link>https://medium.com/@prasoonsingh.lucknow?source=rss-1b889e554b8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:19:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prasoonsingh.lucknow/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[A Simple Introduction to Sequence to Sequence Models]]></title>
            <link>https://medium.com/analytics-vidhya/a-simple-introduction-to-sequence-to-sequence-models-b34ebdf113a5?source=rss-1b889e554b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b34ebdf113a5</guid>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prasoon Singh]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 07:00:14 GMT</pubDate>
            <atom:updated>2020-09-09T06:18:39.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYo4QF_FMBSGW5GsZBRfsw.gif" /></figure><h3>Overview</h3><p>In this article, I would give you an overview of sequence to sequence models which became quite popular for different tasks like machine translation, video captioning, image captioning, question answering, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6i8zvWmaXpXx48yl.jpg" /></figure><p><em>Prerequisites: The reader should already be familiar with neural networks and, in particular, recurrent neural networks (RNNs). In addition, knowledge of LSTM or GRU models is preferable. If you are not familiar with LSTM I would prefer you to read </em><a href="https://medium.com/analytics-vidhya/lstm-long-short-term-memory-5ac02af47606"><em>LSTM- Long Short-Term Memory</em></a><em>.</em></p><h3>Introduction:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*EuUcrUwNMDEf_x3d.jpg" /></figure><h3>Use Cases of the Sequence to Sequence Models</h3><p>Sequence to sequence models lies behind numerous systems that you face on a daily basis. For instance, seq2seq model powers applications like Google Translate, voice-enabled devices, and online chatbots. The following are some of the applications:</p><ul><li><em>Machine translation</em> — a 2016 <a href="https://arxiv.org/pdf/1409.3215.pdf">paper</a> from Google shows how the seq2seq model’s translation quality “approaches or surpasses all currently published results”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*7b2qzUwUYRLBkNXy.png" /></figure><ul><li><em>Speech recognition </em>— another Google <a href="https://www.isca-speech.org/archive/Interspeech_2017/pdfs/0233.PDF">paper</a> that compares the existing seq2seq models on the speech recognition task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*vWsikdfobYuM2DoH.jpg" /></figure><p>These are only some applications where seq2seq is seen as the best solution. This model can be used as a solution to any sequence-based problem, especially ones where the inputs and outputs have different sizes and categories.</p><p>We will talk more about the model structure below.</p><h3>Encoder-Decoder Architecture:</h3><p>The most common architecture used to build Seq2Seq models is Encoder-Decoder architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJHsFRb6emNfZ1Qb.png" /></figure><p><a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Sutskever%2C+I">Ilya Sutskever</a> model for Sequence to Sequence Learning with Neural Networks</p><p>As the name implies, there are two components — an encoder and a decoder.</p><h4>Encoder :</h4><ul><li>Both encoder and the decoder are LSTM models (or sometimes GRU models)</li><li>The encoder reads the input sequence and summarizes the information in something called the <strong>internal state vectors</strong> or <strong>context vector</strong> (in case of LSTM these are called the hidden state and cell state vectors). We discard the outputs of the encoder and only preserve the internal states. This context vector aims to encapsulate the information for all input elements in order to help the decoder make accurate predictions.</li><li>The hidden states <em>h_i </em>are computed using the formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*wlQo78PHSEYnn-4T.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*6kOiIylTsRZeUpKu.png" /></figure><p>The LSTM reads the data, one sequence after the other. Thus if the input is a sequence of length ‘t’, we say that LSTM reads it in ‘t’ time steps.</p><p>1. Xi = Input sequence at time step i.</p><p>2. hi and ci = LSTM maintains two states (‘h’ for hidden state and ‘c’ for cell state) at each time step. Combined together these are internal state of the LSTM at time step i.</p><p>3. Yi = Output sequence at time step i. Yi is actually a probability distribution over the entire vocabulary which is generated by using a softmax activation. Thus each Yi is a vector of size “vocab_size” representing a probability distribution.</p><h4>Decoder :</h4><ul><li>The decoder is an LSTM whose initial states are initialized to the final states of the Encoder LSTM, i.e. the context vector of the encoder’s final cell is input to the first cell of the decoder network. Using these initial states, the decoder starts generating the output sequence, and these outputs are also taken into consideration for future outputs.</li><li>A stack of several LSTM units where each predicts an output y_t at a time step t.</li><li>Each recurrent unit accepts a hidden state from the previous unit and produces and output as well as its own hidden state.</li><li>Any hidden state <em>h_i </em>is computed using the formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*Gxw-YefM5l2_R9AF.png" /></figure><ul><li>The output <em>y_t</em> at time step <em>t</em> is computed using the formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*pl57H41--vLxBOS3.png" /></figure><ul><li>We calculate the outputs using the hidden state at the current time step together with the respective weight W(S). <a href="https://www.youtube.com/watch?v=LLux1SW--oM">Softmax</a> is used to create a probability vector which will help us determine the final output (e.g. word in the question-answering problem).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*Jtdv0rQNWABf5aDO.png" /></figure><p>We will add two tokens in the output sequence as follows:</p><h4>Example:</h4><p>“<strong>START_</strong> John is hard working<strong> _END</strong>”.</p><p>The most important point is that the initial states (h0, c0) of the decoder are set to the final states of the encoder. This intuitively means that the decoder is trained to start generating the output sequence depending on the information encoded by the encoder.</p><p>Finally, the loss is calculated on the predicted outputs from each time step and the errors are backpropagated through time in order to update the parameters of the network. Training the network over a longer period with a sufficiently large amount of data results in pretty good predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*dO-zaIZc87T6Ci1K.png" /></figure><p>Overall Encoder-Decoder Architecture</p><ul><li>During inference, we generate one word at a time.</li><li>The initial states of the decoder are set to the final states of the encoder.</li><li>The initial input to the decoder is always the START token.</li><li>At each time step, we preserve the states of the decoder and set them as initial states for the next time step.</li><li>At each time step, the predicted output is fed as input in the next time step.</li><li>We break the loop when the decoder predicts the END token.</li></ul><h4>Drawbacks of Encoder-Decoder Models :</h4><p>There are two primary drawbacks to this architecture, both related to length.</p><ol><li>Firstly, as with humans, this architecture has very limited memory. That final hidden state of the LSTM, which we call <strong>S or W</strong>, is where you’re trying to cram the entirety of the sentence you have to translate.<strong>S or W</strong> is usually only a few hundred units (read: floating-point numbers) long — the more you try to force into this fixed dimensionality vector, the lossier the neural network is forced to be. Thinking of neural networks in terms of the “lossy compression” they’re required to perform is sometimes quite useful.</li><li>Second, as a general rule of thumb, the deeper a neural network is, the harder it is to train. For recurrent neural networks, the longer the sequence is, the deeper the neural network is along the time dimension.This results in vanishing gradients, where the gradient signal from the objective that the recurrent neural network learns from disappears as it travels backward. Even with RNNs specifically made to help prevent vanishing gradients, such as the LSTM, this is still a fundamental problem.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*tz6m62tl4-sDDS-a.png" /></figure><p>Furthermore, for more robust and lengthy sentences we have models like <strong>Attention Models</strong> and <strong>Transformers</strong>.</p><p>Here <a href="https://github.com/prasoons075/Deep-Learning-Codes/tree/master/Encoder%20Decoder%20Model"><strong><em>this</em></strong></a> is my GitHub repository for complete word level as well as character level encoder-decoder Model.</p><h3>References</h3><p>1. <a href="https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html">https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html</a></p><p>2. <a href="https://arxiv.org/abs/1409.3215">https://arxiv.org/abs/1409.3215</a></p><p>3. <a href="https://arxiv.org/abs/1406.1078">https://arxiv.org/abs/1406.1078</a></p><p>4. <a href="https://towardsdatascience.com/word-level-english-to-marathi-neural-machine-translation-using-seq2seq-encoder-decoder-lstm-model-1a913f2dc4a7">https://towardsdatascience.com/word-level-english-to-marathi-neural-machine-translation-using-seq2seq-encoder-decoder-lstm-model-1a913f2dc4a7</a></p><p><em>Originally published at </em><a href="https://www.analyticsvidhya.com/blog/2020/08/a-simple-introduction-to-sequence-to-sequence-models/"><em>https://www.analyticsvidhya.com</em></a><em> on August 31, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b34ebdf113a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-simple-introduction-to-sequence-to-sequence-models-b34ebdf113a5">A Simple Introduction to Sequence to Sequence Models</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics for developing a custom Alexa skill with AWS lambda as backend.]]></title>
            <link>https://medium.com/analytics-vidhya/basics-for-developing-a-custom-alexa-skill-with-aws-lambda-as-backend-5ac115c2919?source=rss-1b889e554b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac115c2919</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[alexa-skills]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prasoon Singh]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 13:10:20 GMT</pubDate>
            <atom:updated>2020-04-06T07:28:19.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Build A Custom Amazon Alexa Skill with AWS Lambda as a backend.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGUDW3LisNhiFhATjAxiDw.jpeg" /><figcaption>Welcome to the Alexa Skills Kit, you can say hello!</figcaption></figure><p>Hello everyone, a came across developing this Alexa skill project for my company and was struggling to get a smooth head start so I write this blog so as to help others. Hope this helps you. :)</p><h3>Setting Up the ASK SDK</h3><p>This guide describes how to install the ASK SDK for Python in preparation for developing an Alexa skill. I have used the AWS lambda function for backend because you can debug here as compared to the Alexa developer console and lots of other cool things.</p><h3>Prerequisites</h3><p>The ASK SDK for Python requires <strong>Python 2 (&gt;= 2.7)</strong> or <strong>Python 3 (&gt;= 3.6)</strong>. Before continuing, make sure you have a supported version of Python installed. To show the version, from a command prompt run the following command:</p><pre>$ python --version<br>Python 3.6.5</pre><h3>Adding the ASK SDK for Python to Your Project</h3><p>Many Python developers prefer to work in a virtual environment, so do I, so in this blog, I’ll proceed with that only. The virtual environment is an isolated Python environment that helps manage project dependencies and package versions. The easiest way to get started is to install the SDK in a virtual environment.</p><pre>$ pip install virtualenv</pre><p>Next, create a new folder for your Alexa skill and navigate to the folder:</p><pre>$ mkdir skill<br>$ cd skill</pre><p>Next, create a virtual environment called skill_env by issuing the following command:</p><pre>$ virtualenv skill_env</pre><p>Next, activate your virtual environment and install the SDK.</p><p>Run the following command to activate your virtual environment:</p><pre>$ skill_env\Scripts\activate</pre><p>The command prompt should now be prefixed with <em>(skill_env)</em>, indicating that you are working inside the virtual environment. Use the following command to install the ASK Python SDK:</p><pre>(skill_env)$ pip install ask-sdk</pre><p>The SDK will be installed in the skill\Lib\site-packages folder. The site-packages folder is populated with directories including:</p><pre>ask_sdk<br>ask_sdk_core<br>ask_sdk_dynamodb<br>ask_sdk_model<br>boto3<br>...</pre><h3>Developing Your First Skill</h3><h3>Prerequisites</h3><p>In addition to an installed version of the ASK SDK for Python you need:</p><ul><li>An <a href="https://developer.amazon.com/">Amazon Developer</a> account. This is required to create and configure Alexa&#39;s skills.</li><li>An <a href="https://aws.amazon.com/">Amazon Web Services (AWS)</a> account. This is required for hosting a skill on AWS Lambda.</li></ul><h3>Creating Hello World</h3><p>You’ll write your Hello World in a single python file named hello_world.py. In the skill the folder that you have created earlier, use your favorite text editor or IDE to create a file named hello_world.py.</p><h3>Implementing Hello World</h3><h3>Request handlers</h3><p>A custom skill needs to respond to events sent by the Alexa service. For instance, when you ask your Alexa device (e.g. Echo, Echo Dot, Echo Show, etc.) to “open hello world,” your skill needs to respond to the LaunchRequest that is sent to your Hello World skill. With the ASK SDK for Python, you simply need to write a request handler, which is code to handle incoming requests and return a response. Your code is responsible for making sure that the right request handler is used to process incoming requests and for providing a response.</p><p>Start by creating a skill builder object. The skill builder object helps in adding components responsible for handling input requests and generating custom responses for your skill.</p><p>Type or paste the following code into your hello_world.py file.</p><pre>from ask_sdk_core.skill_builder import SkillBuilder</pre><pre>sb = SkillBuilder()</pre><p>To use handler classes, each request handler is written as a class that implements two methods of the AbstractRequestHandler class; can_handle and handle.</p><p>The can_handle the method returns a Boolean value indicating if the request handler can create an appropriate response for the request. The can_handle method has access to the request type and additional attributes that the skill may have set in previous requests or even saved from a previous interaction. The Hello World skill only needs to reference the request information to decide if each handler can respond to an incoming request.</p><h3>LaunchRequest handler</h3><p>The following code example shows how to configure a handler to be invoked when the skill receives a <a href="https://developer.amazon.com/en-US/docs/alexa/custom-skills/request-types-reference.html#launchrequest">LaunchRequest</a>. The LaunchRequest event occurs when the skill is invoked without specific intent.</p><p>Type or paste the following code into your hello_world.py file, after the previous code.</p><pre>from ask_sdk_core.dispatch_components import AbstractRequestHandler<br>from ask_sdk_core.utils import is_request_type, is_intent_name<br>from ask_sdk_core.handler_input import HandlerInput<br>from ask_sdk_model import Response<br>from ask_sdk_model.ui import SimpleCard</pre><pre>class LaunchRequestHandler(AbstractRequestHandler):<br>    def can_handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; bool</em><br>        return is_request_type(&quot;LaunchRequest&quot;)(handler_input)</pre><pre>    def handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; Response</em><br>        speech_text = &quot;Welcome to the Alexa Skills Kit, you can say hello!&quot;</pre><pre>        handler_input.response_builder.speak(speech_text).set_card(<br>            SimpleCard(&quot;Hello World&quot;, speech_text)).set_should_end_session(<br>            False)<br>        return handler_input.response_builder.response</pre><p>The can_handle function returns <strong>True</strong> if the incoming request is a LaunchRequest. The handle function generates and returns a basic greeting response.</p><h3>HelloWorldIntent handler</h3><p>The following code example shows how to configure a handler to be invoked when the skill receives an intent request with the name HelloWorldIntent. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>class HelloWorldIntentHandler(AbstractRequestHandler):<br>    def can_handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; bool</em><br>        return is_intent_name(&quot;HelloWorldIntent&quot;)(handler_input)</pre><pre>    def handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; Response</em><br>        speech_text = &quot;Hello World&quot;</pre><pre>        handler_input.response_builder.speak(speech_text).set_card(<br>            SimpleCard(&quot;Hello World&quot;, speech_text)).set_should_end_session(<br>            True)<br>        return handler_input.response_builder.response</pre><p>The can_handle function detects if the incoming request is an <a href="https://developer.amazon.com/en-US/docs/alexa/custom-skills/request-types-reference.html#intentrequest">IntentRequest</a>, and returns <strong>True</strong> if the intent name is HelloWorldIntent. The handle function generates and returns a basic “Hello World” response.</p><h3>HelpIntent handler</h3><p>The following code example shows how to configure a handler to be invoked when the skill receives the built-in intent <a href="https://developer.amazon.com/en-US/docs/alexa/custom-skills/standard-built-in-intents.html#available-standard-built-in-intents">AMAZON.HelpIntent</a>. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>class HelpIntentHandler(AbstractRequestHandler):<br>    def can_handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; bool</em><br>        return is_intent_name(&quot;AMAZON.HelpIntent&quot;)(handler_input)</pre><pre>    def handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; Response</em><br>        speech_text = &quot;You can say hello to me!&quot;</pre><pre>        handler_input.response_builder.speak(speech_text).ask(speech_text).set_card(<br>            SimpleCard(&quot;Hello World&quot;, speech_text))<br>        return handler_input.response_builder.response</pre><p>Similar to the previous handler, this handler matches an IntentRequest with the expected intent name. Basic help instructions are returned, and .ask(speech_text) causes the user&#39;s microphone to open up for the user to respond.</p><h3>CancelAndStopIntent handler</h3><p>The CancelAndStopIntentHandler is similar to the HelpIntent handler, as it is also triggered by the built-In <a href="https://developer.amazon.com/en-US/docs/alexa/custom-skills/standard-built-in-intents.html#available-standard-built-in-intents">AMAZON.CancelIntent or AMAZON.StopIntent Intents</a>. The following example uses a single handler to respond to both intents. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>class CancelAndStopIntentHandler(AbstractRequestHandler):<br>    def can_handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; bool</em><br>        return is_intent_name(&quot;AMAZON.CancelIntent&quot;)(handler_input)<br>                or is_intent_name(&quot;AMAZON.StopIntent&quot;)(handler_input)</pre><pre>    def handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; Response</em><br>        speech_text = &quot;Goodbye!&quot;</pre><pre>        handler_input.response_builder.speak(speech_text).set_card(<br>            SimpleCard(&quot;Hello World&quot;, speech_text)).set_should_end_session(True)<br>        return handler_input.response_builder.response</pre><p>The response to both intents is the same, so having a single handler reduces repetitive code.</p><h3>SessionEndedRequest handler</h3><p>Although you cannot return a response with any speech, card or directives after receiving a <a href="https://developer.amazon.com/en-US/docs/alexa/custom-skills/request-types-reference.html#sessionendedrequest">SessionEndedRequest</a>, the SessionEndedRequestHandler is a good place to put your cleanup logic. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>class SessionEndedRequestHandler(AbstractRequestHandler):<br>    def can_handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; bool</em><br>        return is_request_type(&quot;SessionEndedRequest&quot;)(handler_input)</pre><pre>    def handle(self, handler_input):<br>        <em># type: (HandlerInput) -&gt; Response</em><br>        <em># any cleanup logic goes here</em></pre><pre>        return handler_input.response_builder.response</pre><h3>Implementing exception handlers</h3><p>The following sample adds a <em>catch-all</em> exception handler to your skill, to ensure the skill returns a meaningful message for all exceptions. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>from ask_sdk_core.dispatch_components import AbstractExceptionHandler</pre><pre>class AllExceptionHandler(AbstractExceptionHandler):</pre><pre>    def can_handle(self, handler_input, exception):<br>        <em># type: (HandlerInput, Exception) -&gt; bool</em><br>        return True</pre><pre>    def handle(self, handler_input, exception):<br>        <em># type: (HandlerInput, Exception) -&gt; Response</em><br>        <em># Log the exception in CloudWatch Logs</em><br>        print(exception)</pre><pre>        speech = &quot;Sorry, I didn&#39;t get it. Can you please say it again!!&quot;<br>        handler_input.response_builder.speak(speech).ask(speech)<br>        return handler_input.response_builder.response</pre><h3>Creating the Lambda handler</h3><p>The <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html">Lambda handler</a> is the entry point for your AWS Lambda function. The following code example creates a Lambda handler function to route all inbound requests to your skill. The Lambda handler function creates an SDK skill instance configured with the request handlers that you just created. Type or paste the following code into your hello_world.py file, after the previous handler.</p><pre>sb.add_request_handler(LaunchRequestHandler())<br>sb.add_request_handler(HelloWorldIntentHandler())<br>sb.add_request_handler(HelpIntentHandler())<br>sb.add_request_handler(CancelAndStopIntentHandler())<br>sb.add_request_handler(SessionEndedRequestHandler())</pre><pre>sb.add_exception_handler(AllExceptionHandler())</pre><pre>handler = sb.lambda_handler()</pre><p>Once you’ve created your AWS Lambda function, it’s time to give the Alexa service the ability to invoke it. To do this, navigate to the <strong>Triggers</strong> tabs in your Lambda’s configuration, and add <strong>Alexa Skills Kit</strong> as the trigger type. Once this is done, upload the skill.zip the file produced in the previous step and fill in the <em>handler</em> information with module_name.handler which is hello_world.handler for this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lT1B3lohRhBSHaeexf9Eog.png" /></figure><h3>Configuring and testing your skill</h3><p>Now that the skill code has been uploaded to AWS Lambda, you can configure the skill with Alexa.</p><ul><li>Create a new skill by following these steps:</li></ul><ol><li>Log in to the <a href="https://developer.amazon.com/alexa/console/ask">Alexa Skills Kit Developer Console</a>.</li><li>Click the <strong>Create Skill</strong> button in the upper right.</li><li>Enter “mark1” as your skill name and click Next.</li><li>For the model, select <strong>Custom</strong> and click <strong>Create skill</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqrcm86q5b0wY6eYs_TyZA.png" /><figcaption>Here the skill name is “mark1”.</figcaption></figure><ul><li>Next, define the interaction model for the skill. Select the <strong>Invocation</strong> option from the sidebar and enter “greeter” for the <strong>Skill Invocation Name</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5Qk3SmlBjiudOKE7oKUwQ.png" /><figcaption>Invocation name “mark one”.</figcaption></figure><ul><li>Next, add an intent called HelloWorldIntent to the interaction model. Click the <strong>Add</strong> button under the Intents section of the Interaction Model. Leave <strong>Create custom intent</strong> selected, enter <strong>HelloWorldIntent</strong> for the intent name, and create the intent. On the intent detail page, add some sample utterances that users can say to invoke the intent. For this example, consider the following sample utterances, and feel free to add others.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVBnBR7NadRS7f8-2v4eMQ.png" /></figure><ul><li>Since AMAZON.CancelIntent, AMAZON.HelpIntent, and AMAZON.StopIntent are built-in Alexa intents, you do not need to provide sample utterances for them.</li><li>Once you are done editing the interaction model, be sure to save and build the model.</li><li>Next, configure the endpoint for the skill. To do this, follow these steps:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5J0iIfv0h7ixnlc39Dgug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5J0iIfv0h7ixnlc39Dgug.png" /></figure><p>Open the AWS Developer Console in a new tab.</p><p>Navigate to the AWS Lambda function created in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4S1zFzWLhEU-4-uH_qIvAg.png" /></figure><p>From the <strong>Designer</strong> menu, add the <strong>Alexa Skills Kit</strong> trigger menu, and scroll down to paste the skill ID into the <strong>Skill ID Verification</strong> configuration. Click <strong>Add and save</strong> once completed to update the AWS Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m74wBeDb1EaGbR8pIxEecg.png" /></figure><p>Copy the AWS Lambda function <strong>ARN</strong> from the top right corner of the page. An ARN is a unique resource number that helps Alexa service identify the AWS Lambda function it needs to call during skill invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7td8w_RDrLZTCtITG8Vbg.png" /></figure><p>Navigate to the Alexa Skills Kit Developer Console, and click on your <strong>mark1 </strong>skill.</p><p>Under your skill, click <strong>Endpoint</strong> tab, select <strong>AWS Lambda ARN</strong> and paste in the ARN under <strong>Default Region</strong> field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmcmKqBhsgtVMMTyrpBYwQ.png" /></figure><p>The rest of the settings can be left at their default values. Click <strong>Save Endpoints</strong>.</p><p>Click <strong>Invocation</strong> tab, save and build the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0EUIes0CEaKP6K1GyW2VA.png" /></figure><p>At this point, you can test the skill. In the top navigation, click <strong>Test</strong>. Make sure that the <strong>Test is enabled for this skill</strong> option is enabled. You can use the Test page to simulate requests, in text and voice form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*INxqBRgVy5BihB-857aWqw.png" /></figure><p>Use the invocation name along with one of the sample utterances as a guide. For example, <em>tell greeters to say hello</em> should result in your skill responding with “Hello World” voice and “Hello World” card on devices with a display. You can also open the Alexa app on your phone or at <a href="https://alexa.amazon.com/">https://alexa.amazon.com</a> and see your skills listed under <strong>Your Skills</strong>.</p><p>Feel free to start experimenting with your intents as well as the corresponding request handlers in your skill code. Once you’re finished iterating, optionally move on to getting your skill certified and published so it can be used by customers worldwide.</p><p>You can find the full code of the above <a href="https://github.com/prasoons075/Alexa-Skill/blob/master/hello_world.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac115c2919" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basics-for-developing-a-custom-alexa-skill-with-aws-lambda-as-backend-5ac115c2919">Basics for developing a custom Alexa skill with AWS lambda as backend.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSTM- Long Short-Term Memory]]></title>
            <link>https://medium.com/analytics-vidhya/lstm-long-short-term-memory-5ac02af47606?source=rss-1b889e554b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac02af47606</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prasoon Singh]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 04:37:46 GMT</pubDate>
            <atom:updated>2020-01-14T04:40:22.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3aobLAmfePsS26QhY3YFQ.jpeg" /><figcaption>I’m Batman</figcaption></figure><p>Long Short Term Memory networks — usually just called “LSTMs” — are a special kind of RNN, capable of learning long-term dependencies. They were introduced by <a href="http://www.bioinf.jku.at/publications/older/2604.pdf">Hochreiter &amp; Schmidhuber (1997)</a> and were refined and popularized by many people in the following work. They work tremendously well on a large variety of problems and are now widely used.</p><p>LSTMs are explicitly designed to avoid the long-term dependency problem. Remembering information for long periods of time is practically their default behavior, not something they struggle to learn!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vcM4KAieoUCDa4Xp.png" /></figure><p>We’ll walk through the LSTM diagram step by step later. For now, let’s just try to get comfortable with the notation we’ll be using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Gu0SeGRj6t6Vhf0g2JT0nA.png" /></figure><p>In the above diagram, each line carries an entire vector, from the output of one node to the inputs of others. The pink circles represent pointwise operations, like vector addition, while the yellow boxes are learned neural network layers. Lines merging denote concatenation, while a line forking denotes its content being copied and the copies going to different locations.</p><h3>Step-by-Step LSTM Walk Through</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*Gwpe2UYn8Iws8_8LEviDeg.png" /></figure><ol><li><strong>Forget Gate</strong>(weights corresponding to W_f):<br> First, we have the forget gate(W_f). This gate decides what information should be thrown away or kept. Information from the previous hidden state(h(t-1)) and information from the current input(x(t)) is passed through the sigmoid function. Values come out between 0 and 1. The closer to 0 means to forget, and the closer to 1 means to keep.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*QeCVt60RU5M5BhQieE6Cnw.png" /></figure><p><strong>2. Input Gate</strong>(weights corresponding to W_i):<br> To update the cell state, we have the input gate. First, we pass the previous hidden state(h(t-1)) and current input(x(t)) into a sigmoid function. That decides which values will be updated by transforming the values to be between 0 and 1. 0 means not important, and 1 means important. You also pass the hidden state(h(t-1)) and current input(x(t)) into the tanh function to squish values between -1 and 1 to help regulate the network. Then you multiply the tanh output with the sigmoid output. The sigmoid output will decide which information is important to keep from the tanh output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*DPAqmwfbhJeJuN9sW1-iog.png" /></figure><p><strong>3. Cell State</strong><br> Now we should have enough information to calculate the cell state. First, the cell state gets pointwise multiplied by the forget vector. This has the possibility of dropping values in the cell state if it gets multiplied by values near 0. Then we take the output from the input gate and do a pointwise addition which updates the cell state to new values that the neural network finds relevant. That gives us our new cell state(c(t)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*A-wTgSHfXNcNm9UNWiKR1A.png" /></figure><p><strong>4. Output Gate</strong><br> Last we have the output gate. The output gate decides what the next hidden state should be. Remember that the hidden state contains information on previous inputs. The hidden state is also used for predictions. First, we pass the previous hidden state and the current input into a sigmoid function. Then we pass the newly modified cell state to the tanh function. We multiply the tanh output with the sigmoid output to decide what information the hidden state should carry. The output is the hidden state. The new cell state and the new hidden is then carried over to the next time step.</p><p>To review, the Forget gate decides what is relevant to keep from prior steps. The input gate decides what information is relevant to add from the current step. The output gate determines what the next hidden state should be.</p><h3>References:</h3><p><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">Understanding LSTM Networks</a></p><p><a href="https://en.wikipedia.org/wiki/Long_short-term_memory">https://en.wikipedia.org/wiki/Long_short-term_memory</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac02af47606" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/lstm-long-short-term-memory-5ac02af47606">LSTM- Long Short-Term Memory</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Word2Vec]]></title>
            <link>https://medium.com/analytics-vidhya/deep-dive-into-word2vec-7fcefa765c17?source=rss-1b889e554b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fcefa765c17</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Prasoon Singh]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 18:39:20 GMT</pubDate>
            <atom:updated>2019-09-17T11:48:32.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGxKvELB8t0Q2AUUh15yyQ.png" /></figure><blockquote><strong>Word2vec</strong> is a group of related models that are used to produce word embeddings. These models are shallow, two-layer neural networks that are trained to reconstruct linguistic contexts of words. Word2vec takes as its input a large corpus of text and produces a vector space, typically of several hundred dimensions, with each unique word in the corpus being assigned a corresponding vector in the space. Word vectors are positioned in the vector space such that words that share common contexts in the corpus are located close to one another in the space. In this article we will see how embedding help to find similar/dissimilar words.</blockquote><h3>Why word vectors?</h3><p>To start off first we need to know why do we need to convert a word into a vector? So what is a vector?</p><blockquote><strong>Vector</strong>- A quantity having direction as well as magnitude, especially as determining the position of one point in space relative to another.</blockquote><p>Now if something has magnitude and direction we can possibly do math with it and if we could do math with a vectorized form of a word then it creates possibilities of comparing one word to another in an N-dimensional space.</p><p>Ok, that might be a lot to take at the start, let me take an easy example to demonstrate how math can do wonders when words are considered as numbers instead of simply a combination of letters for the machine learning.</p><p><strong>Animal similarity and simple linear algebra</strong></p><p>We’ll begin by considering a small subset of English: words for animals. Our task is to be able to find similarities among these words and the creatures they designate. To do this, we might start by making a spreadsheet of some animals and their characteristics. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*0GaAusRXkWUCRDXqYdicbg.png" /></figure><p>This spreadsheet associates a handful of animals with two numbers: their cuteness and their size, both in a range from zero to one hundred. (The values themselves are taken randomly.)</p><p>These values give us everything we need to make determinations about which animals are similar (at least, similar in the properties that we’ve included in the data). Now if we try to answer a question: Which animal is most similar to a capybara? You could go through the values one by one and do the math to make that evaluation, but visualizing the data as points in 2-dimensional space makes finding the answer very intuitive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*lDd5kPhw7yPtok2QKPguPA.png" /></figure><p>The plot shows us that the closest animal to the capybara is the panda bear (again, in terms of its subjective size and cuteness). One way of calculating how “far apart” two points are is to find their <em>Euclidean distance</em>.</p><p>You can understand this arrow as being the <em>relationship</em> between a tarantula and a hamster, in terms of their size and cuteness. In the same diagram, I’ve also transposed this same arrow (this time in red) so that its origin point is “chicken.” The arrow ends closest to “kitten.” What we’ve discovered is that the animal that is about the same size as a chicken but much cuter is… a kitten. To put it in terms of an analogy:</p><pre>Tarantulas are to hamsters as chickens are to kittens.</pre><p>Now that we have the basic idea that why we need to convert a word to a vector we move on to understand how do we get a vector of a word in an N-dimensional space.</p><h3>Where Do Word Vectors Come From?</h3><p>An excellent question at this point is, <em>Where do these dimensions and weights come from?!</em> There are two common ways through which word vectors are generated:</p><ol><li>Counts of word/context co-occurrences</li><li>Predictions of context given word (skip-gram neural network models, i.e. word2vec)</li></ol><h3><strong>How are these words represented in an N-dimensional matrix?</strong></h3><blockquote><strong><em>Step 1-</em></strong> We one-hot encode each word. Here suppose the vocabulary is 10K words and each word is represented in with one-hot encoding with dimension as (1*10k).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQdMQ1nAkUKKoLHtk-R8Rw.png" /></figure><p>Example — Man(5391) when represented in one hot encoding has only 1 at a single place as rest are all other words. It is also represented as O5391.</p><p>Now if we have a matrix where each word is categorized and represented with a numerical rating based upon its dimension. For instance, man- gender is categorized for male as -1 and to female as +1. Likewise, the king has male as its gender so will have a negative value and queen being female would be having a positive value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsKkCAn87nFrZtR7Hg5zPw.png" /></figure><p>So here we had rows corresponding to the dimension which had numerical values corresponding to its columns but in reality, the rows like gender, royal and all are hard to interpret but they are evolved with this concept only.</p><blockquote><strong>Visualizing Word Embedding in 2D :</strong> This can be done using TSNE which is used for dimensionality reduction.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLi8sROXPKNuEuXawwl08Q.png" /></figure><blockquote><strong>Step 2- </strong>When we have to find a N-dimensional vector corresponding to word we multiply the embedded matrix to the one-hot encoded form of a word and the output we get is an N-dimensional vector of that word.</blockquote><p>Here to find a 300 dimensional vector corresponding to a word we multiply this embedded matrix to the one hot representation of that word which is 10k*1 and as the 1-hot representation will have only “1” present only once as 10k was a combination of unique words, so when multiplied with this embedded matrix we will have a (300*1) matrix which will have the values of all 300 dimension (how distant a word is from other dimensions). So, whenever we need such representation of a word we use such methodology.</p><blockquote>E.Oj=ej (E=embedded matrix, O=1-hot representation)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDIascaXjzMuoY7dmmLwJg.png" /></figure><p>Now that we have got a hold on word embedding we can dive into the concept of Word2Vec.</p><h3><strong>Word2Vec :</strong></h3><p>We will keep the corpus simple as it helps us to understand each step with ease plus we can visualize the relationship clear to make it more concrete. <strong>CBOW (Continuous Bag Of Words) and Skip-Gram</strong> are two most popular frames for word embedding. In CBOW the words occurring in context (surrounding words) of a selected word are used as inputs and middle or selected word as the target. Its the other way round in Skip-Gram, here the middle word tries to predict the words coming before and after it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DidClA6gbkKp9w46P3GJA.png" /></figure><p>Consider a text consisting of characters from ‘a’ to ‘z’ sequentially [a, b,c, d, e, f, g, h, i, j, k,l, m, n, o, p, q, r,s, t, u, v, w, x, y, z], further let integers 0 to 25 represent the respective letters. Implementing CBOW keeping the window size of 2, we can see that ‘a’ is related to ‘b’ and ‘c’, ‘b’ to ‘a’, ‘c’ and’ ‘d’ and so forth. It follows that one hot vector representing input words will be of dimension [26, 1]. With the help of the model, we will find the dense and distributed vector of size [10, 1]. The size of the embedding vector is selected arbitrarily.</p><p>The diagram below illustrates the context and target words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEzwA77YB9J9q-0GvWyQFw.png" /><figcaption>Left. Arrangement of CBOW and Skip-gram models. Right. Character and corresponding integers grouped into lists of input and targets. For each, the first column represents the input character and the remaining items in each sub-lists are targets for the input.</figcaption></figure><p>It is easy to visualize the pattern of relationship. When they occur together within a span of 2 characters they are related or co-occurrence is true. The pattern is depicted in table and map below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXS35mdm6mSISUw9rkTPEw.png" /><figcaption>Left. Characters appearing together (not fully visualized). Right. The black color region implies no co-occurrence and white region implies characters occurring together given windows size of 2 #Also note the diagonal symmetry — implying that co-occurrence from a to b means co-occurrence from b to a but these relationships are depicted different axes.</figcaption></figure><p>Word2Vec is a probabilistic model. Key components of this model are 2 weight matrices. The rows of the first matrix (w1) and the columns of the second matrix (w2) embed the input words and target words respectively. The product of these two word vectors is then used to get the probabilities for being a target word, given the selected input word. Upon training these embedding vectors are optimized using gradient descent such that probabilities for true targets are maximized. It is obvious that the matrices w1 and w2 are factorization a probability matrix which closely resembles the co-occurrence matrix.</p><p>Model is illustrated and explained in the figures below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /><figcaption>Schematic diagram of Word2Vec model. Input and Output vectors are of size V, while hidden vector (embedding) is of size N. (Source: <a href="https://lilianweng.github.io/lil-log/2017/10/15/learning-word-embedding.html">https://lilianweng.github.io/lil-log/2017/10/15/learning-word-embedding.html</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vPEYQa6jXJjCZcYW.png" /><figcaption>In this illustration, the model is learning to embed 6 characters (‘a’ to ‘f’) into a 3-dimensional embedding vector. <strong>A.</strong> Co-occurrence Matrix of these characters with a window size of 2, co-occurrence is expressed as either present or absent. (size 6, 6) <strong>B.</strong> Weight matrix w1 — transposed. Each row of matrix w1 is embedding vector for the one word as one-hot vector uniquely selects the corresponding row of w1 (or col of W1 transpose) <strong>C.</strong> Matrix of one-hot vector, each column represents one word/item <strong>D.</strong> Product of w1 and input matrix results in matrix h (hidden layer). Here the whole input matrix is as an identity matrix and simply passes weight matrix w1 as hidden matrix h. However it is not necessary to be an identity matrix, the order and size of the input matrix(and hence hidden layer) could be different <strong>E. </strong>Weight matrix w2 — transposed (size 6,3). Each column of matrix w2 closely represents represents the target words <strong>F.</strong> Hidden layer — h, identical to w1 as described before <strong>G. </strong>Each row of w2 — transposed products with a column of hidden (that embeds an input word ) outputting scores of length of the size vocab <strong>H.</strong> As mentioned all rows of w2_transposed interacting with 1 column of hidden — results in one column of Score Matrix , total product of w2_transposed and ‘h’ is the matrix S (size 6, 6) <strong>I.</strong> Softmax is applied to score matrix. Each entry in a column is converted into probabilities <strong>J.</strong> Probability matrix — each item in a column of this matrix represents probabilities for being a target word given an input word <strong>L.</strong> Error — Probability at the position of true indices are to be maximized, error is computed comparing this probability assigned to the index corresponding to true targets <strong>M. </strong>Back prop — At the start weights are initialized randomly and resulting probabilities are low and similar for all targets. After training, backpropagation of gradients and optimization of weights, probabilities are dense around targets and close to 0 at other places.</figcaption></figure><p><strong>Cosine Similarity</strong></p><p>Among different distance metrics, cosine similarity is more intuitive and most used in word2vec. It is normalized dot product of 2 vectors and this ratio defines the angle between them. Two vectors with the same orientation have a cosine similarity of 1, two vectors at 90° have a similarity of 0, and two vectors diametrically opposed have a similarity of -1, independent of their magnitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*P8MAOCL1lyiVbANHNmFGHA.png" /><figcaption>Top left: Equation for cosine distance Top right: Cosine distance varies from 1 to -1 and the corresponding angle varies from 0 to 180 degrees. Bottom left: Cosine distances from ‘c’ to all the characters. Bottom right: Same distances expressed as angles. Note ‘c’ is most similar to itself.</figcaption></figure><h3><strong>Reference:</strong></h3><ul><li><a href="https://towardsdatascience.com/introduction-to-word-embedding-and-word2vec-652d0c2060fa">Introduction to Word Embedding and Word2Vec</a></li><li><a href="https://dzone.com/articles/introduction-to-word-vectors">Introduction to Word Vectors - DZone AI</a></li><li><a href="https://towardsdatascience.com/word2vec-made-easy-139a31a4b8ae">Word2vec Made Easy</a></li></ul><p>Understanding Word Vectors by Allison Parrish: <a href="https://gist.github.com/aparrish/2f562e3737544cf29aaf1af30362f469">https://gist.github.com/aparrish/2f56...</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fcefa765c17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deep-dive-into-word2vec-7fcefa765c17">Deep Dive Into Word2Vec</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of Bag Of Words and TF-IDF]]></title>
            <link>https://medium.com/analytics-vidhya/fundamentals-of-bag-of-words-and-tf-idf-9846d301ff22?source=rss-1b889e554b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9846d301ff22</guid>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[bag-of-words]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Prasoon Singh]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 06:56:49 GMT</pubDate>
            <atom:updated>2020-02-15T05:04:43.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBqHP8rkCY6S4j0CzSt2SQ.jpeg" /></figure><p>This post will take you to basic understanding concepts of how a machine checks if given two sentences are having a similar meaning or not. It involves some basic concepts of NLP.</p><p><strong>Natural-language processing</strong> (<strong>NLP</strong>) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to fruitfully process large amounts of natural language data.</p><p>In simple terms, Natural language processing (NLP) is the ability of computers to understand human speech as it is spoken. NLP helps to analyze, understand, and derive meaning from human language in a smart and useful way.</p><h3><strong>Why do we need such models to check similarity between sentences?</strong></h3><p>A problem with modeling text is that it is messy, and techniques like machine learning algorithms prefer well defined fixed-length inputs and outputs.</p><p>Machine learning algorithms cannot work with the raw text directly; the text must be converted into numbers. Specifically, vectors of numbers.</p><p><strong>Concept: Similar text must result in closer vector.</strong></p><blockquote>“In language processing, the vectors x are derived from textual data, in order to reflect various linguistic properties of the text.”</blockquote><p>Popular and simple method of feature extraction with text data which are currently used are:</p><ol><li>Bag-of-Words</li><li>TF-IDF</li><li>Word2Vec</li></ol><h3>Bag Of Words (BOW):</h3><p>The <strong>bag-of-words model</strong> is a simplifying representation used in <a href="https://en.wikipedia.org/wiki/Natural_language_processing">natural language processing</a> and <a href="https://en.wikipedia.org/wiki/Information_retrieval">information retrieval</a> (IR). In this model, a text (such as a sentence or a document) is represented as the <a href="https://en.wikipedia.org/wiki/Multiset">bag (multiset)</a> of its words, disregarding grammar and even word order but keeping <a href="https://en.wikipedia.org/wiki/Multiplicity_(mathematics)">multiplicity</a>.</p><p>The bag-of-words model is commonly used in methods of <a href="https://en.wikipedia.org/wiki/Document_classification">document classification</a> where the (frequency of) occurrence of each word is used as a <a href="https://en.wikipedia.org/wiki/Feature_(machine_learning)">feature</a> for training a <a href="https://en.wikipedia.org/wiki/Statistical_classification">classifier</a>.</p><p>The bag-of-words model is simple to understand and implement and has seen great success in problems such as language modeling and document classification.</p><p>It involves two things:</p><ol><li><strong>A vocabulary of known words:</strong> This step revolves around constructing a document corpus which consists of all the unique words in the whole of the text present in the data provided. It is sort of like a dictionary where each index will correspond to one word and each word is a different dimension.</li></ol><blockquote>Example: If we are given 4 reviews for an Italian pasta dish.</blockquote><blockquote>Review 1 : This pasta is very tasty and affordable.</blockquote><blockquote>Review 2: This pasta is not tasty and is affordable.</blockquote><blockquote>Review 3 : This pasta is delicious and cheap.</blockquote><blockquote>Review 4: Pasta is tasty and pasta tastes good.</blockquote><p>Now if we count the number of unique words in all the four reviews we will be getting a total of 12 unique words. Below are the 12 unique words :</p><ol><li>‘This’</li><li>‘pasta’</li><li>‘is’</li><li>‘very’</li><li>‘tasty’</li><li>‘and’</li><li>‘affordable’</li><li>‘not’</li><li>‘delicious’</li><li>‘cheap’</li><li>‘tastes’</li><li>‘good’</li></ol><p><strong>2. A measure of the presence of known words : </strong>Now if we take the first review and plot count of each word in the below table we will have where row 1 corresponds to the index of the unique words and row 2 corresponds to the number of times a word occurs in a review. (Here review 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*xt00ncNuHRjveh-xeLr1eQ.png" /></figure><p>We will make a sparse vector of d-unique words and for each document (review) we will fill it will number of times the corresponding word occurs in a document.</p><p><strong>Review 4: Pasta is tasty and pasta tastes good.</strong></p><p>For example in review 4 “pasta” has count 2 whereas in review 1 it is 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*XgoX_DiHVG-QBEFc8-Aoow.png" /></figure><p>After converting the reviews into such vectors we can compare different sentences and calculate the Euclidean distance between them so as to check if two sentences are similar or not. If there would be no common words distance would be much larger and vice-versa.</p><p>BOW doesn’t work very well when there are small changes in the terminology we are using as here we have sentences with similar meaning but with just different words.</p><p>This results in a vector with lots of zero scores called a sparse vector or sparse representation.</p><p>Sparse vectors require more memory and computational resources when modeling and the vast number of positions or dimensions can make the modeling process very challenging for traditional algorithms.</p><p>As such, there is pressure to decrease the size of the vocabulary when using a bag-of-words model.</p><p>There are simple<strong> text cleaning techniques</strong> that can be used as a first step, such as:</p><blockquote><strong>·</strong> Ignoring case</blockquote><blockquote><strong>·</strong> Ignoring punctuation</blockquote><blockquote><strong>·</strong> Ignoring frequent words that don’t contain much information, called stop words, like “a,” “of,” etc.</blockquote><blockquote><strong>·</strong> Fixing misspelled words.</blockquote><blockquote><strong>·</strong> Reducing words to their stem (e.g. “play” from “playing”) using stemming algorithms.</blockquote><h3><strong>N-grams Model:</strong></h3><p>A more sophisticated approach is to create a vocabulary of grouped words. This changes both the scope of the vocabulary and allows the bag-of-words to capture a little bit more meaning from the document.</p><p>In this approach, each word or token is called a “<strong>gram</strong>”. Creating a vocabulary of two-word pairs is, in turn, called a <strong>bigram</strong> model. Again, only the bigrams that appear in the corpus are modeled, not all possible bigrams.</p><blockquote><em>An N-gram is an N-token sequence of words: a 2-gram (more commonly called a bigram) is a two-word sequence of words like “please turn”, “turn your”, or “your homework”, and a 3-gram (more commonly called a trigram) is a three-word sequence of words like “please turn your”, or “turn your homework”.</em></blockquote><p><strong>Code for BOW:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*KdtPDhRaA72aB2NDtwuqUA.jpeg" /></figure><h3>TF-IDF:</h3><p><strong>tf–idf</strong> or <strong>TFIDF</strong>, short for <strong>term frequency-inverse document frequency</strong>, is a numerical statistic that is intended to reflect how important a word is to a <a href="https://en.wikipedia.org/wiki/Document">document</a> in a collection or <a href="https://en.wikipedia.org/wiki/Text_corpus">corpus</a>.The tf–idf value increases <a href="https://en.wikipedia.org/wiki/Proportionality_(mathematics)">proportionally</a> to the number of times a word appears in the document and is offset by the number of documents in the corpus that contain the word, which helps to adjust for the fact that some words appear more frequently in general. tf–idf is one of the most popular term-weighting schemes today; 83% of text-based recommender systems in digital libraries use tf–idf.</p><p>This concept includes:</p><blockquote>· <strong>Counts</strong>. Count the number of times each word appears in a document.</blockquote><blockquote>· <strong>Frequencies</strong>. Calculate the frequency that each word appears in a document out of all the words in the document.</blockquote><h3><strong>Term frequency :</strong></h3><p>Term frequency (TF) is used in connection with information retrieval and shows how frequently an expression (term, word) occurs in a document. Term frequency indicates the significance of a particular term within the overall document. It is the number of times a word wi occurs in a review rj with respect to the total number of words in review rj.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*dl_epsnVXAblq7rzcVklhg.jpeg" /></figure><p>TF can be said as what is the probability of finding a word in a document (review).</p><h3>Inverse document frequency:</h3><p>The inverse document frequency is a measure of how much information the word provides, i.e., if it’s common or rare across all documents. It is used to calculate the weight of rare words across all documents in the corpus. The words that occur rarely in the corpus have a high IDF score. It is the logarithmically scaled inverse fraction of the documents that contain the word (obtained by dividing the total number of documents by the number of documents containing the term, and then taking the logarithm of that quotient):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*JwV9bRi_r-jUdzCdyuYPsA.jpeg" /></figure><h3><strong>Term frequency–Inverse document frequency:</strong></h3><p>TF–IDF is calculated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*5N3UB1mG4wWpMa0ck3SamA.jpeg" /></figure><p>A high weight in tf–idf is reached by a high term <a href="https://en.wikipedia.org/wiki/Frequency_(statistics)">frequency</a> (in the given document) and a low document frequency of the term in the whole collection of documents; the weights hence tend to filter out common terms. Since the ratio inside the IDF&#39;s log function is always greater than or equal to 1, the value of IDF (and tf–idf) is greater than or equal to 0. As a term appears in more documents, the ratio inside the logarithm approaches 1, bringing the IDF and tf–idf closer to 0.</p><p>TF-IDF gives larger values for less frequent words in the document corpus. TF-IDF value is high when both IDF and TF values are high i.e the word is rare in the whole document but frequent in a document.</p><p>TF-IDF also doesn’t take the semantic meaning of the words.</p><p><strong>Let’s take an example to get a clearer understanding.</strong></p><p>Sentence 1: The car is driven on the road.</p><p>Sentence 2: The truck is driven on the highway.</p><p>In this example, each sentence is a separate document.</p><p>We will now calculate the TF-IDF for the above two documents, which represent our corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*laEhq0Xj9zP01eKdKTVsjQ.png" /></figure><p>From the above table, we can see that the TF-IDF of common words was zero, which shows they are not significant. On the other hand, the TF-IDF of “car”, “truck”, “road”, and “highway” are non-zero. These words have more significance.</p><p><strong>Reviewing</strong>- TFIDF is the product of the TF and IDF scores of the term.</p><p><strong>TF</strong> = number of times the term appears in the doc/total number of words in the doc</p><p><strong>IDF</strong> = ln(number of docs/number docs the term appears in)</p><p>Higher the TFIDF score, the rarer the term is and vice-versa.</p><p>TFIDF is successfully used by search engines like Google, as a ranking factor for content.</p><p>The whole idea is to weigh down the frequent terms while scaling up the rare ones.</p><p><strong>Code for TF-IDF:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*eXE3qg69oQk--UM6UmCJRw.jpeg" /></figure><p>TFIDF is successfully used by search engines like Google, as a ranking factor for content.</p><p>The whole idea is to weigh down the frequent terms while scaling up the rare ones.</p><h3>Word2Vec :</h3><p>Word2Vec model is used for learning vector representations of words called “word embeddings”. This is typically done as a preprocessing step, after which the learned vectors are fed into a discriminative model (typically an RNN) to generate predictions and perform all sorts of interesting things. It takes the semantic meaning of words. I would include this Word2Vec in my next blog in an exhaustive manner. — <a href="https://medium.com/analytics-vidhya/deep-dive-into-word2vec-7fcefa765c17">https://medium.com/analytics-vidhya/deep-dive-into-word2vec-7fcefa765c17</a></p><p><em>References :</em></p><ul><li><a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">tf-idf - Wikipedia</a></li><li><a href="https://machinelearningmastery.com/gentle-introduction-bag-words-model/">A Gentle Introduction to the Bag-of-Words Model - Machine Learning Mastery</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9846d301ff22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/fundamentals-of-bag-of-words-and-tf-idf-9846d301ff22">Fundamentals of Bag Of Words and TF-IDF</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>