<?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 Amaresh Patnaik on Medium]]></title>
        <description><![CDATA[Stories by Amaresh Patnaik on Medium]]></description>
        <link>https://medium.com/@amareshp72?source=rss-2515722c3c27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*I42KmXJpMN93u-S0.</url>
            <title>Stories by Amaresh Patnaik on Medium</title>
            <link>https://medium.com/@amareshp72?source=rss-2515722c3c27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:30:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amareshp72/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[RAG using GGUF]]></title>
            <link>https://medium.datadriveninvestor.com/rag-using-gguf-a6a1bae49592?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a1bae49592</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 11:54:30 GMT</pubDate>
            <atom:updated>2024-03-05T04:41:02.755Z</atom:updated>
            <content:encoded><![CDATA[<p>A generative AI model generates text on the basis of the data it has been trained on. Over and above that, we can provide the model with new text in the prompt and ask it to come up with answers to questions on the basis of that text. Since the prompt is of limited number of tokens, we cannot provide the content of large PDF files or text files in the prompt. We then break the content of the file into smaller chunks and vectorize the chunks. When we need to answer a question, we vectorize the question (query) too and retrieve (R — Retrieval) the chunk that matches the query the closest. We then augment (A — Augmented) the prompt with the chunk (paragraph) so that the model answers the query using generation (G — Generation). Read this <a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">article</a> for a more detailed explanation of RAG.</p><p>What the above article would also explain is that RAG and generative AI in general would require expensive hardware. <a href="https://medium.com/@phillipgimmi/what-is-gguf-and-ggml-e364834d241c">GGUF</a> (GPT-Generated Unified Format<strong>) </strong>is a file format used for storing models, and these models can then be used on commodity CPUs instead of requiring expensive GPUs. The trade-off is that inference time increases significantly compared to the regular format models. Here we will discuss how to use GGUF to run RAG on commodity hardware.</p><p><strong>LlamaIndex</strong></p><p>RAG requires us to tie many pieces together. Though we can write our code for the purpose it is easier and quicker to use a library like <a href="https://www.llamaindex.ai/">LlamaIndex</a> for the same. Here we will use LlamaIndex to develop an RAG application where we use GGUF for our LLM so that we can run it on a regular CPU.</p><p><strong>The Notebook</strong></p><p>We had discussed a text file where we will be searching against the query and pass relevant chunks to the Large Language Model (LLM). We will use the text file mentioned in <a href="https://docs.llamaindex.ai/en/stable/examples/customization/llms/SimpleIndexDemo-Huggingface_camel.html">here</a>. I am using the free version of Google Colab to run code discussed here.</p><pre>!mkdir -p &quot;data/paul_graham&quot;<br>!wget &quot;https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt&quot; -O &quot;data/paul_graham/paul_graham_essay.txt&quot;</pre><p>Here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2-mdjxjKzKtCo81CsDhLA.png" /><figcaption>Get the File</figcaption></figure><p>Next, we need to install the Python libraries we will be using that are not available by default in Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*na5NzXVHkM8eocEfDlwgTQ.png" /><figcaption>Install Libraries</figcaption></figure><p>Then we import the libraries we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*j4BJ1bJk_Lc_-tIBEYkzwg.png" /><figcaption>Import Libraries</figcaption></figure><p>We were discussing vectorizing the text chunks and the query, so we need to pick up the embedding model. We will also define the string that will be used to query the file for information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*g5v7kawvYDVr5C94CHRz1A.png" /><figcaption>Constants</figcaption></figure><p>Next, we read the text file into a LlamaIndex documents object. The print statement is to cross check the number of documents read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*FaCwNiek_CvCKS3UVTS--w.png" /><figcaption>Read Documents</figcaption></figure><p>Then we specify the embedding model we will use and the LLM we will use. The LLM will be used for the generation part of the RAG. We have loaded the LLM using a model_url that points to GGUF file. We also specify the size of the text chunks the text file will be split into. We use the LlamaIndex Settings variable to specify these globally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwsBPxzPIvj1adNMPVdKJg.png" /><figcaption>Settings</figcaption></figure><p>If you can see the time to the left of the notebook cell it took around a minute to load the model. Regular LLMs will take longer to load than their GGUF counterparts. While loading the model was quick, inference for GGUF will be painfully slow, as we will see later.</p><p>Then we will build our LlamaIndex index. This step will split the text file into chunks, vectorize the chunks, and index the vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*gu3VCY3fe-mls3LioO7jJg.png" /><figcaption>Build the Index</figcaption></figure><p>We can now run the query on the index. For that we create the query engine and query the query engine. Internally these steps vectorize the query, retrieve the closest matching text chunk, augment the prompt with that text chunk, and generate the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*zYKMZ4383FqruNGR5vpmxw.png" /><figcaption>Run Query</figcaption></figure><p>You can see the response to the query at the bottom of the screen. While the quality of the response is quite good, Colab took 32 minutes to come up with the response. That would be an unacceptable wait time if you are building a real time chat application. But the GGUF format lets you run applications like RAG on a CPU, which would otherwise be difficult. You should explore a GPU for production applications.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a1bae49592" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/rag-using-gguf-a6a1bae49592">RAG using GGUF</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Llama 7B on Free Colab]]></title>
            <link>https://medium.datadriveninvestor.com/code-llama-7b-on-free-colab-d695595018ab?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/d695595018ab</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[code-llama]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 02:32:03 GMT</pubDate>
            <atom:updated>2023-12-13T03:05:36.702Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a sequel to <a href="https://medium.datadriveninvestor.com/mistral-7b-on-free-colab-06b42d7b90e3">Mistral 7B on Free Colab</a> and <a href="https://medium.datadriveninvestor.com/zephyr-7b-on-free-colab-d36120f03101">Zephyr 7B on Free Colab</a>, though this article can also be read independently. In this article, we turn our attention to the <a href="https://huggingface.co/codellama/CodeLlama-7b-hf">Code Llama 7B model</a>. This model is designed to generate code. I picked up the code to load the model and the first few code examples by observing <a href="https://generativeai.pub/how-to-run-code-llama-in-free-colab-notebook-a-step-by-step-guide-with-code-f8957f42b4d9">this</a> article, but I do not use a pipeline here. And because we want to run the model on the free version of Google Colab, we pick up the smallest model, which has 7 billion parameters.</p><p><strong>Code Llama 7B</strong></p><p>Code Llama 7B is not an instruction-based model. What that means is that unlike the previous two models Mistral 7B and Zephyr 7B, we do not prompt Code Llama 7B with natural language instructions. Instead, we prompt like “def factorial(n):” and Code Llama completes the code for us.</p><p><strong>The Notebook</strong></p><p>Like my previous two articles, I have connected to the T4 GPU available in the free version of Colab. Let us first install the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kE_ZvAWy-gxhnevO84N3vA.png" /><figcaption>Install Dependencies</figcaption></figure><p>Then we import the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*p_D1rsep6zSuFtPYCz9w8A.png" /><figcaption>Import Dependencies</figcaption></figure><p>The model uses text in the form of tokens and uses the IDs of the tokens instead of the actual values. We will use the following method to convert the response token IDs to their actual values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWyZ7siMsZo57jM3KRaD-g.png" /><figcaption>Response Token IDs to Values</figcaption></figure><p>We will use the following code to generate the code from the prompt to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpH-QBrf7FizfXBAT-YFBQ.png" /><figcaption>Code from Prompt</figcaption></figure><p>Then we get the tokenizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*ovpSLJFipbGN3HlBpEtjNQ.png" /><figcaption>Tokenizer</figcaption></figure><p>Next, we load the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*ywN5R5QqGf9KF7h0yh5DZQ.png" /><figcaption>The Model</figcaption></figure><p>Now that the model is loaded, let us ask it to generate the Fibonacci sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*9j78ZRTFkRprzdUNKUtGug.png" /><figcaption>Fibonacci Sequence</figcaption></figure><p>The first function looks correct and complete. However, as the original <a href="https://generativeai.pub/how-to-run-code-llama-in-free-colab-notebook-a-step-by-step-guide-with-code-f8957f42b4d9">article</a> mentions, the model continues generating code even after it has completed the function. The second function is identical to the first one, only the function name is different.</p><p>Then we prompt the model to generate the code that will generate factorial of a number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*Y7IXdeato6v0Taq0Fxd7iw.png" /><figcaption>Factorial</figcaption></figure><p>Again, it would have sufficed to stop after completing the function.</p><p>Next, we will ask the model to generate code that will remove the last word of a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*KYpEjuT2wfP-MxPizgxiiA.png" /><figcaption>Remove Last Word</figcaption></figure><p>Let us now see if Code Llama can generate Boolean functions too. Can it check if a number is prime?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*pBLSFhXYzib24OJJbgY3PA.png" /><figcaption>Check Prime Number</figcaption></figure><p>Let us then check if Code Llama can generate code in the C programming language. Let us prompt the model accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*VPCWm6LGJzbPjzWp8rOGbw.png" /><figcaption>Fibonacci Sequence in C</figcaption></figure><p>The next prompt will be to generate code in Python to reverse a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*gSNMDFL7PVhIG3YL3lXyMA.png" /><figcaption>Reverse a String</figcaption></figure><p>So far, we have been prompting the model with the function name only. What if we also have in mind the parameters? Like we want our function to add, but add what? We want to decide that in the prompt itself using the parameter list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*BxEjajKHbYBsNcJkkKCKfQ.png" /><figcaption>Add 5 Numbers</figcaption></figure><p>Not being able to stop after generating the required function correctly does not seem to be the only problem. Let us take the second function generated in response to the reverse string prompt (cell 12) and run that code in the same notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*63hnc-AyBPLz2ihckMrZlw.png" /><figcaption>Testing the Code</figcaption></figure><p>Now let us call the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*Tzf_xmX9Ast7PeUOJupRDw.png" /><figcaption>Test Result</figcaption></figure><p>Though the function looks fine, Python strings are immutable, meaning individual characters within a string cannot be reassigned. So, we are required to test the model generated code before using the same for production, but does that not apply to human generated code too? :) I would agree with the assessment in the original <a href="https://generativeai.pub/how-to-run-code-llama-in-free-colab-notebook-a-step-by-step-guide-with-code-f8957f42b4d9">article</a> that the results are good but not amazing.</p><p>I tried running my code multiple times, and I got different, and interesting code generated for the same prompts. I would encourage you to try running these prompts multiple times and also try your own prompts. You will soon get comfortable using code generation LLMs in your own applications.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d695595018ab" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/code-llama-7b-on-free-colab-d695595018ab">Code Llama 7B on Free Colab</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zephyr 7B on Free Colab]]></title>
            <link>https://medium.datadriveninvestor.com/zephyr-7b-on-free-colab-d36120f03101?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36120f03101</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 10:38:59 GMT</pubDate>
            <atom:updated>2023-12-03T12:20:39.772Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a sequel to <a href="https://medium.com/datadriveninvestor/mistral-7b-on-free-colab-06b42d7b90e3">Mistral 7B on Free Colab</a>. In the previous article, I had explained that Large Language Models (LLMs) are resource hungry and running them on limited resources like what is available in the free version of Google Colab is a challenge. I had shown how to run the Mistral 7B LLM on the free version of Colab. In this article, I am showing how to run another LLM, Zephyr 7B, on free Colab and how we can run some interesting examples on this model.</p><p><strong>Zephyr 7B</strong></p><p>Zephyr 7B Beta is a fine-tuned version of <a href="https://medium.com/datadriveninvestor/mistral-7b-on-free-colab-06b42d7b90e3">Mistral 7B</a>, as you can see in the model <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta">card</a>. The model has 7 billion parameters. The official model itself is sharded and can be used in free Colab. I am reusing the code provided <a href="https://gathnex.medium.com/zephyr-7b-beats-chatgpt-huggingface-open-challenge-to-openai-bba2fceecd9c">here</a> for the first few lines of my notebook to access the model and the first example.</p><p><strong>The Notebook</strong></p><p>As in the previous article, I have connected to the T4 GPU available in the free version of Colab. Let us first install the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_B8qbxhd6OcoZ6JvUM6VoQ.png" /><figcaption>Install Dependencies</figcaption></figure><p>Then we import the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*YZaNAafUFJ9YX5CrYOmoUw.png" /><figcaption>Import Dependencies</figcaption></figure><p>We are next defining a method that will buffer the model’s response against instructions given by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwfQ1rZcegvwBsCGyYZWHA.png" /><figcaption>Model Response</figcaption></figure><p>We are creating another method that returns the prompt that can be used with the model against the instructions given by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*s_E7VSHT78S_4tFj29yBZw.png" /><figcaption>Prompt</figcaption></figure><p>The next method will pass the above prompt to the model and return the response from the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRtqJ8xhpG29bqlLuz1D1Q.png" /><figcaption>Model Response</figcaption></figure><p>We are now ready to load the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*KJzznSuwcZ3BGeA70PI8tA.png" /><figcaption>Load the Model</figcaption></figure><p>We will use the buffered method we created earlier to give our first simple instruction to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvAZip_OaCDyb1ckiUl2fw.png" /><figcaption>Streamed Response</figcaption></figure><p>For better readability, I am reproducing the text below.</p><pre>Dear Valued Customer,<br><br>We regret to inform you that there has been a delay in the delivery of your order. The estimated delivery date for your product has been pushed back by 1 day, and it is now scheduled to arrive on December 3, 2023.<br><br>We understand the inconvenience this may cause you and apologize for any inconvenience this may cause. We assure you that we are doing everything possible to expedite the delivery process and minimize any further delays.<br><br>The delay is due to unforeseen circumstances beyond our control, which has affected our logistics and supply chain. We are working closely with our logistics partners to resolve the issue as soon as possible.<br><br>We appreciate your patience and understanding during this time, and we assure you that your order will be delivered as soon as possible. If you have any further queries or concerns, please do not hesitate to contact us.<br><br>Thank you for your continued patronage, and we apologize for any inconvenience caused.<br><br>Best Regards,<br><br>[Your Name]<br><br>[Your Company Name]<br><br>📦 Delivery Delay 📦<br><br>📩 Email Notification 📩<br><br>📅 New Delivery Date: December 3, 2023 📅<br><br>📞 Customer Service Contact 📞<br><br>🤝 Apology and Assurance 🤝<br><br>🔔 Notification Bell 🔔<br><br>📈 Supply Chain Graph 📈<br><br>📊 Logistics Process Flowchart 📊<br><br>📝 Delivery Delay Letter 📝<br><br>📝 Customer Service Contact Letter 📝<br><br>📝 Apology and Assurance Letter 📝<br><br>📝 Supply Chain Graph Letter 📝<br><br>📝 Logistics Process Flowchart Letter 📝<br><br>📝 Delivery Delay Letter with Emojis 📝<br><br>📝 Customer Service Contact Letter with Emojis 📝<br><br>�</pre><p>Let us now use the same prompt to generate a response without buffering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnCnh66kVrNsYxfLpzigKw.png" /><figcaption>Another Response</figcaption></figure><p>I am reproducing the response below.</p><pre>&lt;s&gt; ### Instruction:<br>  Write an email about the product delivery delay for 1 day, which is, 3 December 2023 will be the delivery date<br><br>  ### Response:<br>  <br>Subject: Product Delay Notification<br><br>Dear [Customer Name],<br><br>We apologize for any inconvenience caused regarding the delivery of your recent order. Due to unexpected unforeseen circumstances beyond our control, the expected delivery date of December 2, 2023, will have to be postponed. The new delivery date for your order is December 3, 2023.<br><br>We take full responsibility for the inconvenience this delay has caused you. Our team is working diligently to ensure that we minimize any further delays and that the re-scheduled delivery happens promptly.<br><br>We understand that this delay might affect your schedule, and we are grateful for your patience as we work to deliver your order as soon as possible. We want to assure you that your order is being handled with the utmost care and attention, and it will be shipped out as soon as possible.<br><br>Once again, please accept our sincere apologies for the inconvenience caused. If you have any further questions, please do not hesitate to contact us.<br><br>Thank you for your understanding regarding this matter.<br><br>Best regards,<br><br>[Your Name]<br>[Your Title]<br>[Your Company]<br>[Your Email Address]<br>[Your Contact Number]&lt;/s&gt;</pre><p>Let us run another example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynUhPYYcfYuX4ZawI1eW3g.png" /><figcaption>New York</figcaption></figure><p>Here is the generated list for better readability.</p><pre>&lt;s&gt; ### Instruction:<br>  Write me a numbered list of things to do in New York City.<br><br>  ### Response:<br>  1. Visit the Statue of Liberty: The iconic symbol of freedom stands tall in New York Harbor, welcoming visitors from around the world.<br>  2. Explore Central Park: The sprawling urban oasis boasts landscaped gardens, walking paths, and Central Park Zoo, featuring everything from snow leopards to sea lions.<br>  3. Catch a show on Broadway: The world-renowned theater district is home to blockbusting productions and Tony Award-winning performances.<br>  4. Take a stroll down Fifth Avenue: Window shopping for high-end designer brands, Art Galleries, and grand historic buildings make this road a must-visit place.<br>  5. Bite into a New York-style Pizza: A true experience you cannot miss, with slices toppings that are unique to NYC and served in restaurants or street vendor carts.<br>  6. Go to the Empire State Building: An observation deck on the 86th floor provides awe-inspiring views of the city skyline and its monuments.<br>  7. Take a bike ride through Central Park: Rent a bike and join the throngs of cyclists as you pedal through the park&#39;s green expanse.<br>  8. Splurge in high-end shopping in Soho and Meatpacking districts.<br>  9. Enjoy a pastry or a cupcake: Try out famous cupcakes shop chains like Magnolia Bakery, Crumbs, and Baked By Melissa.<br>  10. Grab a slice of Cheesecake: The cheesecake offered at Junior&#39;s, The Cheesecake Factory, or Cake Boss, etc.<br>  11. Watch a game of Baseball, Basketball, American Football or Tennis at one of the famous stadiums like Yankee stadium, Madison Square Garden, Arthur Ashe, or Billie Jean King National Tennis Centre.<br>  12. Explore the vibrant neighborhoods like Brooklyn, Queens, Harlem, Astoria, etc. <br>  13. Take a stroll through Times Square: The buzzing intersection is home to giant billboards, flashing lights, and neon ads.<br>  14. Walk across Brooklyn Bridge: Admire the dazzling skyline of the downtown Manhattan skyline that unfolds on this historic bridge.<br>  15. Try out street foods like Halal Guys, Nathan Thrasher Shops, Halal Food carts, etc. <br>  16. Visit the World Trade Center Memorial: A solemn reminder of New York City&#39;s tragedy and unity since the 9/11 attacks.<br>  17. Tour the famous institutions and museums such as MoMA, The Guggenheim Museum, Brooklyn Museum, The Metropolitan Museum of Art, The American Museum of Natural History, etc.<br>  18. Take a ferry to the Statue of Liberty &amp; Ellis Island: You can take a round trip ferry ride to be mesmerized by the beautiful views of the city and the harbor.<br>  19. Witness the magic of the New York City Christmas Markets and Light shows or St Patrick&#39;s Day Parade.<br>  20. Visit the High Line: A former elevated railway park is now a beautiful and peaceful walkway above the streets of Manhattan with excellent skyline views.<br>  21. Walk along the Chelsea Market: Shopping and dining complex with various choices of food, souvenirs, and local produce.<br>  22. Explore the famous delis such as Katz&#39;s Deli, 2nd Avenue Deli, Carnegie Deli, etc.<br>  23. Take a Subway, MetroCard at hand, and explore the different boroughs of Manhattan, Queens, or Brooklyn, etc.<br>  24. Stop by the Oculus Transportation Hub at the World Trade Center: Architecturally outstanding with its unique white latticework design and transportation facilities like trains and buses.<br>  25. Wander around in the Washington Square Park, Tompkins Square Park, and Central Park for an array of events, concerts, farmer&#39;s markets, etc.<br>  26. Take a ferry to Liberty Island and Ellis Island National Monuments: Learn about the history of America&#39;s immigrants and the National Park Service&#39;s preservation efforts.<br>  27. Enjoy some time at the Coney Island Beach: Known for its beach, historic amusement park, hot dogs, and cycling route, &quot;Boardwalk&quot;.<br>  28. Marvel at the New York City skyline on the Hudson River: A</pre><p>The next example is to draft an email for a dinner party.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZIhJ7jSXU7F7nVDGNMvcg.png" /><figcaption>Party Invitation</figcaption></figure><p>I am reproducing the draft invitation below for better readability.</p><pre>&lt;s&gt; ### Instruction:<br>  Write a short email inviting my friends to a dinner party on Friday. Respond succintly.<br><br>  ### Response:<br>  <br>Subject: Invitation to Dinner Party<br><br>Dear [Friend’s Name],<br><br>I hope this email meets you in good health and high spirits. I am glad to reach out to you and extend a heartfelt invitation to an intimate dinner party that I am hosting on Friday, 5th August, at my place.<br><br>The menu for the evening will feature a scrumptious three-course dinner followed by a decadent dessert. Our dinner party would consist of an elegant arrangement of dinnerware, crystal stemware and cutlery to create an ambiance perfect for quality conversation and indulgent dining.<br><br>The dress code for the evening is formal. We&#39;d want to create an elegant ambience, and hence I feel that a dress code would add to the charm. I am confident that a gathering of wonderful people, an exquisite dinner and the sound of music in the background would be an evening filled with good cheer and conviviality.<br><br>To RSVP kindly email me at your earliest convenience, and give me an estimate of the number of guests you&#39;d be bringing along.  I&#39;m excited to be hosting this event and I look forward to your RSVP at your earliest convenience.<br><br>Best regards,<br><br>[Your Name]&lt;/s&gt;</pre><p>The next task we are giving the model is to write an essay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdu7sORwGiaZHpddXB-6cA.png" /><figcaption>Essay</figcaption></figure><p>I am reproducing the essay below for better readability.</p><pre>&lt;s&gt; ### Instruction:<br>  Write an essay on the winter season.<br><br>  ### Response:<br>  <br>  The winter season is often regarded as the quietest and most serene time of the year. From the soft snowflakes that blanket the earth, to the cozy evenings by the fireplace, winter is a time when nature slows down and our senses seem to heighten. This essay explores the many facets of winter, including its visual and sensory effects, its impact on the environment, and its cultural significance.<br><br>  One of the most fascinating aspects of winter is the way nature changes in response to the season. The first signs of winter are the leaves that begin to turn yellow and brown, dropping to the ground like a symphony of colors. As the trees shed their leaves, the landscape transforms into a winter wonderland. The snow covers the ground, turning it into a canvas for snowmen, snowflakes, and snowballs. This peaceful, hushed world takes us into an eerie silence that seems almost otherworldly. The stillness is interrupted occasionally by the occasional rustling of branches under the weight of snow, but this quietness is nothing less than spellbinding.<br><br>  Apart from the tranquillity of winter, what also makes it unique is the way it intensifies our senses. The coldness that we usually recoil from in other seasons seems to become a welcome sensation in winter. The chill in the air seeps into our bones, causing our noses to turn red and our breaths to come out in puffs. If you’re in a snowy landscape during the winter nights, one thing you won’t be able to avoid is the bright white snow glistening under a million stars in the sky or the faint light of the crescent moon that casts an enchanting spell on us. Then, the snowflakes that form these snow-scapes, melange into a dance-like play on the sky. The sensuous texture of the snow, the crunching sound of snow beneath your feet- every little aspect of winter evolves into an altogether different world.<br><br>  Winter also has its environmental impacts. The first and foremost impact is the snow that falls during winter, which is both a blessing and a curse at the same time. While it makes the world feel enchanted, the snowfall can lead to transportation issues, causing inconvenience for commuters. The winter chill also causes havoc for wildlife, especially for the migratory birds, which have to fly long distances from their winter habitats through icy skies.<br><br>  It is at this time of coldness and starkness that our spirits are lifted with its cultural and social significance. Winter traditions like sledding, ice skating, Christmas caroling, and visiting Christmas markets and illuminated streets fill the air with cheerful spirit. As the nights lengthen and the holidays approach, people decorate trees and homes with twinkling lights creating enchantment in every nook and corner. The sense of community strengthens as people come together to celebrate the season through various winter traditions.<br><br>  In conclusion, winter, in all its splendor, is a season that touches us in ways we cannot always explain. From its visual and sensory effects, its impact on the environment, and cultural and social significance, winter is a season that teaches us to appreciate the simpler things in life. It is a time of slowing down, introspecting, and enjoying the beauty around us. Indeed, winter leaves a lasting impression on us, compelling us to pause, breathe, and embrace.&lt;/s&gt;</pre><p>The last task we are setting the model is to prepare a speech.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usdxZGe4Sh-e-mpnUanZAA.png" /><figcaption>Speech</figcaption></figure><p>For better readability, I am reproducing the speech below.</p><pre>&lt;s&gt; ### Instruction:<br>  Prepare a motivational speech for students to study well before the examinations.<br><br>  ### Response:<br>  <br>Dear Students,<br><br>   Exams are just around the corner, and we are all filled with different emotions, either excitement or fear. I am here to motivate and inspire you all to buckle down and prepare hard for these exams.<br><br>   Firstly, I want you all to believe that you are capable of achieving great heights. Your past performance should not make you doubt your abilities; instead, it should fuel your motivation to work harder and score better. You all have the potential to excel in your academics, and I am confident that you will prove it to everyone soon.<br><br>   Secondly, it is essential to have a structured study plan, as it helps keep track of how much time you’ve invested in preparing for your exams. Start with listing out your academic goals and your study plan. Identify your weak areas and work on them first. Then, proceed with the areas where you have some confidence.<br><br>   Thirdly, avoid procrastination; it’s an enemy to your success. Allocate ample time, set achievable goals, and work towards accomplishing them. Time management is a crucial component of success.<br><br>   Fourthly, believe in the power of repetition. Revising topics multiple times enables the concepts to become second nature to you. Make revision an integral part of your daily routine.<br><br>   Fifthly, practice mock tests and sample papers, familiarising yourself with the paper patterns, formats, and question types. Analyse your strengths and weaknesses, and take a call on the aspects that require further focus and study.<br><br>   Lastly, remember that your mental and physical well-being is equally vital. Balance your study routine with sufficient sleep, proper nutrition, exercise, and meditation. Maintain a healthy lifestyle that keeps you energised and active.<br><br>   In sum, I implore you all to work hard, adopt a disciplined study routine, eliminate procrastination and negative energy, and stay focussed and motivated. Trust yourself, believe in yourself, and you will emerge victorious.<br><br>   I urge you all to be mentally and physically prepared for these exams. Remember, you can do this; with the power of focussed determination and self-belief, there&#39;s no challenge that you can&#39;t overcome.<br><br>   Good Luck with your exams, and remember, stay calm, stay confident, and stay hopeful!<br><br>   Thank you, and God always bless you.<br><br>[Sign-Off]<br>Thank you very much.<br><br>(Curtain falls)&lt;/s&gt;</pre><p>Now that we are able to give instructions, enjoy trying different prompts on your own. Run them multiple times and observe the different results you get. You will soon get comfortable using LLMs in your own applications.</p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/">Here</a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission">here</a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/">here</a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36120f03101" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/zephyr-7b-on-free-colab-d36120f03101">Zephyr 7B on Free Colab</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mistral 7B on Free Colab]]></title>
            <link>https://medium.datadriveninvestor.com/mistral-7b-on-free-colab-06b42d7b90e3?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/06b42d7b90e3</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[natural-language-processi]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 03:26:10 GMT</pubDate>
            <atom:updated>2023-11-07T03:40:49.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models (LLMs) can perform many natural language processing (NLP) tasks with a surprising degree of near-human performance. This level of performance is achieved by training a large model which has millions of parameters using large amounts of training data. The computing resources and training data that are required to train these models are affordable only to very large corporations. Even the computing resources required to consume and fine tune such models would require expensive GPUs and huge amounts of memory.</p><p>There are efforts to make some of these LLMs usable on commodity hardware. I ran into difficulties while running these models on the free version of Google Colab. I was referring to the articles available on the Web, and I had to struggle to get the model running. This article is an effort to share those experiences so that you can directly start using an open source LLM on free Colab. I would not be explaining the architecture of the models here, as there are already good resources on the Web for the same.</p><p><strong>Mistral 7B</strong></p><p>The model I would be using comes from <a href="https://mistral.ai/">Mistral AI</a>. Mistral-7B-v0.1 is Mistral AI’s first Large Language Model (LLM), which is available from <a href="https://huggingface.co/docs/transformers/main/en/model_doc/mistral">Hugging Face</a>. The Mistral-7B-v0.1 Large Language Model (LLM) is a pretrained generative text model with 7 billion parameters, as can be seen in the Hugging Face <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1">model card</a>. But that original model is resource hungry and we would not be able to load it in the free version of Colab, which comes with memory and GPU restrictions. I tried using the code available in this <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1/discussions/13">link</a>, but I started running out of memory. Pursuing the page further, I found the <a href="https://huggingface.co/someone13574/Mistral-7B-v0.1-sharded">sharded model.</a> Here the model is broken up into 8 files. Downloading the whole model as one single file would require the full model to be loaded into RAM before it gets downloaded onto the disk, and RAM is constrained in the free Colab. With the sharded model, one shard (file) is loaded into RAM to begin with, and once the shard is downloaded on to the disk, RAM is freed. Then the next shard is loaded, and so on. This way we are able to download the full model. See below the memory and disk usage as I ran my code in Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*SoefH1puK3B6DVMKwyrY4A.png" /></figure><p><strong>The Notebook</strong></p><p>As you can see in the screenshot above, you would need to connect to the T4 GPU available in the free version of Colab. Let us first install the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*CLHU7BXpNM_hFkJm_-m13w.png" /></figure><p>Then we import the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*Fmn-0ppbMj91FZJ5aYpdTQ.png" /></figure><p>We will need a configuration where we can load the model in 4 bits as in <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">FP4 quantization</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeL69hbTMOk1OSXPSMcrVQ.png" /></figure><p>We are now ready to load the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vO3dN_AcQz2LJxZlLGhlaA.png" /></figure><p>We prepare the tokenizer next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*eo6xgwOqpXPCIIedK8wcvg.png" /></figure><p>Since Mistral 7B is a language model, we will test out sentence completion by providing a prompt (a hint and requesting the model to complete the sentence). We will first tokenize our sample text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*3SYtvHY94WStSTQGQWqDNQ.png" /></figure><p>We will then use the model to generate text, decode and display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzyAZgnXb7hs8R_vS2cXdw.png" /></figure><p>For better readability, I am pasting the text below.</p><blockquote>Once upon a time, I used to do just that with the people in my group before teaching them this new habit — I used to make them repeat the same things and the same sounds until they did it perfectly.</blockquote><blockquote>I no longer do it as this way does not allow students to progress from a learning standpoint. Instead, allow everyone to go at their own pace. Everyone has a different skill set level, and you are the one to help students to reach their unique goals. Don’t make them repeat things over and over again unnecessarily.</blockquote><blockquote>### Tip 6 — Focus on a Positive Attitude</blockquote><blockquote>I wish I had realized sooner that this was the most important of teaching ESL Tips for Teachers. A positive attitude is an ESL teachers best friend! Make sure your students know how wonderful their progress is, always remember to be kind and smile.</blockquote><blockquote>## What’s Next?</blockquote><blockquote>I hope these ESL teaching tips will help you become a better teacher and</blockquote><p>That is a nice response from a model. Let us now attempt again with a different prompt text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*Ca-O-x1LfRlB5jt3k-UwaQ.png" /></figure><p>And the text comes below.</p><blockquote>Where there is a will there is a way. When I started my own business I worked out that I was earning 33% of what I would earn if I stayed with the firm. After 6 months the balance shifted and I was earning slightly more than I would be had I remained. It was the same at my second business. Initially the hourly rate was less but after about 5 months things had turned around in my favour.</blockquote><blockquote>If you believe, if you prepare yourself, if you have done your market research, if you are sure there is a need, if you have the passion to succeed, then you will find that no matter how unattractive your market is, you have the potential to have better success than your employed peers.</blockquote><blockquote>## 4 How long should I wait?</blockquote><blockquote>This really depends on a situation-by-situation analysis. I waited two weeks. The guy selling the business got sick of me, realised I wasn’t going away, felt he couldn’</blockquote><p>That is neat again. Let us change the prompt and try one more time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*M8RZf-Zx5FLXuirzV1aW6g.png" /></figure><p>And let us examine the text generated.</p><blockquote>The woods are lovely, dark and deep. But I have promises to keep, And miles to go before I sleep.</blockquote><blockquote>I’m sure some of you may know a version of this poem. You may even know that the last two lines were added, according to legend, at the request of a friend of Whitman’s son. This man wanted to be assured that he would not lose his chance to do good works simply because of the length of his life.</blockquote><blockquote>When I had read the poem, I felt inspired. A sense of urgency gripped me. What could I do this day that would make a difference in the lives of others? This was a call to action. However, the next thought that came to me was this: what if each day was not a gift? What if each morning I woke and was simply ungrateful to have the opportunity to live it, to work hard, to be loved, to get back up after my inevitable failures? How often do we get lost in the worry</blockquote><p>The generated text looks near-human again. Should we try another prompt?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*X86feIY0mdTn9d1wkYiYkg.png" /></figure><p>Here is the text generated.</p><blockquote>Promise me that you will never get married. Or be with anyone more than one night. No matter how in love you are.” When Nick asks why, her response is devastating. “Because you will be with the man I love.”</blockquote><blockquote>As if that wasn’t tough enough, the series also delivers the following line as Nick and Zoe, who have just moved in together, are saying their wedding vows: “My vow to you is…to love, honor, and respect my brother Nick Miller.” When the show returns for Season 8, I’m anticipating some emotional, hilarious, and maybe even tear-filled moments.</blockquote><blockquote>I would also like to take this opportunity to say that Season 8 needs to be 52 episodes long, so Nick and Jess, now Nick and Zooey, can be as happy as New Girl deserves.</blockquote><blockquote>New Girl airs on FOX Tuesdays at 9/8c.&lt;/s&gt;</blockquote><p>I tried running my code multiple times, and I got different, and interesting text generated for the same prompts. I would encourage you to try running these prompts multiple times and try your own prompts. You will soon get comfortable using LLMs in your own applications.</p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/">Here</a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission">here</a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/">here</a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06b42d7b90e3" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/mistral-7b-on-free-colab-06b42d7b90e3">Mistral 7B on Free Colab</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoder Decoder Sequences: How Long is Too Long? | Data Driven Investor]]></title>
            <link>https://medium.com/@amareshp72/encoder-decoder-sequences-how-long-is-too-long-data-driven-investor-2b2d1ae14d?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2d1ae14d</guid>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 03:40:42 GMT</pubDate>
            <atom:updated>2020-03-25T11:49:16.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*QLQ32vygT8ALR0SL" /></figure><p>In <a href="https://www.datadriveninvestor.com/glossary/machine-learning/">machine learning</a> many times we deal with the input being a sequence and the output also a sequence. We call such a problem a sequence-to-sequence problem.</p><p>A popular architecture for dealing with the sequence-to-sequence problem is the encoder decoder architecture. The encoder converts the variable length input sequence to a fixed length context <a href="https://www.datadriveninvestor.com/glossary/vector/">vector</a>, and the decoder converts the fixed length context vector to a variable length output sequence. I have been reading enough literature (for an example, take a look at <a href="https://towardsdatascience.com/intuitive-understanding-of-attention-mechanism-in-deep-learning-6c9482aecf4f">this article</a>) that says the disadvantage of the encoder decoder architecture is that irrespective of the length of the input sequence the context vector length is fixed, because of which the system cannot remember longer sequences. Often, it has forgotten the earlier parts of the sequence by the time it reaches the end of the sequence.</p><p>That is right. But exactly how long is a ‘longer’ sequence? After what length does the encoder decoder performance start to deteriorate? I conducted a few experiments with various sequence lengths, and that is what this article is about. You may find my numbers interesting to understand the limitations of your own networks when it comes to sequence lengths. My experiments are based on a <a href="https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/">brilliant post</a> on sequence prediction. I suggest you go through that post before proceeding with the rest of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*4PAWjEqYmdmmyaHd" /></figure><p>To explain the sequence prediction problem we intend to solve, I have reproduced the above image from the post I just referred to. The image above has 10 rows that serve as examples of the problem. Take any one row. ‘X’ is a sequence of six randomly generated numbers. The numbers range from 1 to 50. The sequence we need to predict is indicated by ‘y’. It is the first three numbers from the sequence ‘X’, but reversed. The sequence predicted by our encoder decoder model is indicated by ‘yhat’. You can see for this simple problem, we have 100% accuracy — ‘y’ matches ‘yhat’ exactly in all cases. When I ran this experiment several times that was not the case always. But the lowest accuracy I got over several runs was 98. By ‘simple’ problem I mean the input sequence length is as short as 6.</p><p>The post used 128 LSTM units and a single epoch. I started changing the length of the input sequence (change from the present value of 6), the number of LSTM units (present value 128) and the number of epochs (present value 1), and documented the impact of those changes on accuracy. Here is what I found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*QMzKiwjYDCOy15W6" /></figure><p>The first row is the data that is already present in the post — I have documented my lower accuracy of 98 instead of 100. When you have only one LSTM unit, the number of variable parameters in the network is too small to express the sequence, and hence accuracy is zero, even when you increase the epochs to 100. When I increased the input length to 30 (the output length remained 3 throughout the rows in this table), accuracy dropped from 98 to 0 for a single epoch. That meant for ‘long’ sequences the encoder decoder architecture actually starts forgetting the sequence. When I increased the epochs to 30, which is when I started getting a decent accuracy of 85.</p><p>Then I increased the input length to a sequence of 60 numbers. Accuracy stayed at zero when I ran 50 epochs, and even when I increased the number of LSTM units to 256 and the epochs to 70 that still remained the same — zero accuracy. I could have further increased the LSTM units and epochs — but was discouraged as it is not as if I my present accuracy is 45 or 55 — the accuracy was at zero with the network configuration matching what we find in most literature. To compare, here are the 10 sample rows from the last row of the above table.</p><p>X = [21, 1, 48, 8, 41, 49, 27, 40, 17, 15, 12, 31, 38, 31, 8, 43, 45, 6, 40, 3, 44, 4, 27, 27, 46, 45, 43, 11, 29, 23, 30, 25, 3, 30, 15, 20, 29, 21, 13, 2, 43, 15, 8, 16, 33, 47, 9, 13, 8, 29, 28, 40, 26, 43, 3, 21, 29, 31, 44, 2] y = [48, 1, 21], yhat = [2, 48, 13]</p><p>X = [15, 27, 30, 10, 8, 12, 47, 41, 31, 42, 34, 5, 35, 26, 46, 5, 24, 4, 9, 19, 5, 2, 21, 29, 22, 42, 27, 38, 34, 42, 19, 7, 45, 31, 15, 22, 18, 10, 20, 36, 17, 9, 40, 49, 16, 16, 12, 32, 37, 36, 49, 42, 21, 37, 31, 48, 13, 33, 33, 45] y = [30, 27, 15], yhat = [6, 41, 40]</p><p>X = [14, 42, 28, 5, 28, 42, 33, 3, 24, 49, 10, 23, 32, 38, 34, 32, 29, 24, 37, 43, 40, 48, 44, 30, 3, 6, 18, 48, 44, 43, 4, 25, 39, 46, 28, 4, 43, 25, 22, 42, 7, 12, 49, 26, 17, 28, 6, 30, 2, 17, 17, 33, 20, 9, 23, 48, 44, 46, 13, 40] y = [28, 42, 14], yhat = [16, 25, 41]</p><p>X = [37, 2, 28, 38, 41, 25, 17, 36, 28, 8, 30, 38, 43, 44, 21, 30, 23, 46, 13, 29, 35, 37, 20, 42, 33, 42, 7, 29, 10, 50, 45, 20, 29, 38, 19, 50, 24, 24, 38, 40, 36, 36, 35, 49, 20, 33, 42, 8, 21, 23, 22, 35, 44, 43, 23, 25, 26, 30, 42, 41] y = [28, 2, 37], yhat = [11, 7, 3]</p><p>X = [38, 1, 27, 37, 2, 12, 20, 41, 24, 6, 31, 49, 26, 46, 11, 15, 17, 37, 10, 15, 18, 37, 8, 39, 21, 1, 3, 50, 35, 12, 42, 36, 6, 40, 6, 6, 34, 44, 23, 14, 50, 45, 15, 3, 47, 9, 23, 34, 11, 32, 25, 3, 32, 36, 37, 32, 1, 24, 31, 34] y = [27, 1, 38], yhat = [37, 12, 42]</p><p>X = [6, 46, 11, 20, 1, 48, 17, 6, 39, 18, 49, 33, 46, 6, 18, 4, 39, 19, 35, 49, 10, 39, 29, 14, 42, 35, 30, 16, 35, 36, 39, 18, 27, 4, 24, 31, 11, 39, 8, 11, 12, 47, 24, 42, 21, 25, 36, 50, 11, 25, 20, 47, 4, 27, 41, 9, 29, 5, 11, 35] y = [11, 46, 6], yhat = [20, 10, 10]</p><p>X = [11, 28, 33, 14, 38, 8, 27, 45, 1, 30, 7, 10, 28, 6, 2, 38, 4, 22, 47, 18, 36, 39, 39, 7, 23, 31, 6, 20, 42, 33, 16, 26, 21, 7, 24, 43, 49, 47, 20, 14, 15, 15, 13, 3, 9, 25, 29, 13, 46, 27, 7, 50, 47, 8, 47, 17, 45, 15, 9, 36] y = [33, 28, 11], yhat = [4, 42, 5]</p><p>X = [17, 14, 50, 16, 49, 11, 23, 31, 41, 2, 19, 40, 23, 10, 34, 4, 10, 49, 8, 23, 8, 46, 10, 48, 41, 20, 11, 43, 22, 10, 24, 42, 28, 15, 24, 17, 35, 45, 18, 11, 10, 17, 37, 39, 44, 18, 17, 3, 44, 42, 5, 28, 31, 50, 25, 6, 9, 48, 11, 43] y = [50, 14, 17], yhat = [40, 40, 23]</p><p>X = [43, 37, 48, 36, 6, 8, 49, 18, 25, 38, 49, 14, 49, 45, 12, 28, 12, 13, 49, 7, 28, 25, 13, 26, 20, 11, 10, 7, 32, 18, 20, 46, 10, 29, 30, 34, 44, 12, 3, 10, 3, 12, 4, 3, 34, 5, 17, 3, 6, 48, 46, 19, 3, 45, 37, 21, 12, 30, 2, 48] y = [48, 37, 43], yhat = [46, 35, 42]</p><p>X = [36, 28, 17, 42, 29, 10, 23, 22, 38, 37, 25, 37, 43, 7, 50, 42, 8, 43, 39, 11, 26, 14, 36, 17, 2, 38, 47, 25, 37, 20, 5, 22, 13, 43, 26, 35, 26, 30, 20, 5, 25, 17, 20, 10, 27, 32, 10, 23, 36, 22, 1, 15, 49, 5, 11, 29, 32, 40, 19, 32] y = [17, 28, 36], yhat = [23, 6, 10]</p><p>It is obvious that when sequence length increases, the encoder decoder network is not able to remember the first three elements of the sequence. Is it able to remember the last three elements of the sequence? I carried out a series of experiments to find that out. I changed the problem in the referred post to predict the last three numbers of the sequence, reversed. Here is the table for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*Gof9PNjW5jXkWUtd" /></figure><p>Here are 10 sample rows for the experiment indicated by the last row in the above table.</p><p>X = [14, 27, 10, 28, 17, 26, 42, 31, 43, 4, 22, 7, 4, 20, 26, 43, 4, 35, 26, 3, 39, 13, 46, 23, 36, 4, 25, 37, 24, 27, 46, 5, 34, 10, 31, 50, 8, 23, 23, 50, 50, 33, 49, 25, 37, 5, 4, 28, 37, 9, 49, 13, 9, 37, 35, 18, 13, 18, 47, 16] y = [16, 47, 18], yhat = [16, 47, 18]</p><p>X = [26, 2, 26, 7, 22, 46, 11, 14, 11, 12, 9, 28, 42, 3, 37, 36, 2, 50, 22, 15, 28, 30, 10, 13, 4, 12, 46, 18, 16, 9, 4, 6, 16, 45, 24, 43, 40, 13, 28, 6, 17, 35, 17, 5, 43, 30, 11, 39, 8, 10, 32, 8, 45, 21, 40, 29, 42, 15, 5, 12] y = [12, 5, 15], yhat = [12, 5, 15]</p><p>X = [2, 10, 19, 19, 11, 25, 6, 50, 37, 8, 34, 49, 30, 39, 17, 30, 6, 30, 1, 16, 9, 22, 35, 7, 8, 39, 42, 3, 11, 36, 28, 48, 24, 36, 32, 19, 38, 8, 16, 31, 50, 26, 23, 49, 28, 1, 2, 26, 49, 35, 39, 24, 39, 30, 39, 47, 43, 1, 46, 38] y = [38, 46, 1], yhat = [38, 46, 1]</p><p>X = [14, 5, 2, 6, 2, 5, 9, 37, 14, 18, 32, 20, 41, 48, 6, 5, 47, 13, 27, 15, 36, 3, 28, 15, 47, 1, 32, 10, 31, 16, 3, 25, 41, 25, 23, 41, 40, 43, 41, 49, 27, 45, 29, 27, 45, 31, 18, 27, 44, 21, 12, 2, 5, 34, 44, 32, 20, 3, 31, 4] y = [4, 31, 3], yhat = [4, 31, 3]</p><p>X = [22, 34, 23, 17, 28, 22, 2, 15, 50, 26, 40, 6, 22, 46, 25, 38, 36, 21, 13, 18, 40, 46, 15, 44, 30, 32, 10, 21, 41, 2, 46, 39, 16, 34, 45, 13, 48, 16, 10, 2, 1, 44, 28, 24, 4, 42, 36, 9, 9, 44, 36, 25, 35, 32, 24, 20, 23, 45, 15, 33] y = [33, 15, 45], yhat = [33, 15, 45]</p><p>X = [30, 28, 47, 2, 18, 27, 6, 39, 32, 24, 15, 37, 50, 37, 10, 1, 41, 48, 15, 22, 17, 47, 7, 46, 1, 45, 6, 43, 47, 15, 31, 32, 22, 34, 28, 9, 46, 13, 45, 25, 27, 42, 44, 29, 40, 18, 7, 43, 17, 16, 15, 28, 45, 50, 41, 50, 48, 41, 3, 30] y = [30, 3, 41], yhat = [30, 3, 41]</p><p>X = [35, 20, 4, 33, 15, 32, 21, 4, 12, 27, 38, 6, 22, 46, 25, 27, 1, 45, 26, 35, 22, 46, 37, 48, 29, 28, 39, 38, 10, 28, 6, 33, 16, 38, 16, 39, 31, 49, 21, 6, 3, 32, 32, 1, 20, 35, 36, 23, 5, 19, 34, 1, 39, 39, 23, 2, 32, 34, 44, 20] y = [20, 44, 34], yhat = [20, 44, 34]</p><p>X = [17, 41, 10, 19, 7, 2, 50, 23, 41, 23, 22, 41, 36, 16, 2, 23, 24, 4, 18, 25, 17, 12, 45, 27, 18, 2, 5, 35, 3, 33, 49, 8, 21, 20, 14, 8, 20, 2, 22, 15, 23, 14, 13, 42, 48, 46, 41, 29, 26, 37, 34, 39, 35, 38, 35, 39, 29, 24, 39, 11] y = [11, 39, 24], yhat = [11, 39, 24]</p><p>X = [7, 46, 7, 10, 9, 9, 40, 20, 41, 45, 14, 28, 12, 28, 36, 46, 38, 46, 12, 7, 37, 32, 17, 1, 14, 37, 42, 18, 9, 36, 15, 42, 39, 4, 27, 11, 2, 41, 38, 28, 26, 21, 32, 36, 9, 12, 34, 15, 11, 46, 20, 42, 6, 2, 33, 14, 34, 7, 33, 18] y = [18, 33, 7], yhat = [18, 33, 7]</p><p>X = [13, 35, 46, 48, 15, 49, 32, 46, 22, 35, 39, 36, 48, 9, 3, 9, 40, 47, 21, 6, 12, 12, 31, 32, 42, 50, 22, 37, 8, 22, 19, 4, 41, 5, 18, 26, 13, 47, 42, 28, 47, 11, 32, 29, 31, 16, 14, 12, 46, 42, 24, 16, 11, 27, 37, 1, 32, 2, 40, 45] y = [45, 40, 2], yhat = [45, 40, 2]</p><p>The experiments were conducted using Google Colab notebooks. Here are my conclusions from the experiments so far.</p><ol><li>A simple encoder decoder network with only one LSTM unit will not be able to remember even the simplest sequences.</li><li>Somewhere between sequence lengths of 30 and 60, the simple encoder decoder network starts forgetting the first few elements of the sequence. It does not look like having a combination of more LSTM units and more epochs can rectify the situation, as to the limits of reasonable hardware, the accuracy does not move beyond zero.</li><li>As we process element after element of the sequence, the fixed length context vector finds it easy to retain the last three numbers of the sequence but finds it difficult to retain the first three numbers of the sequence.</li></ol><p>The experiments here are not based on <a href="https://www.datadriveninvestor.com/glossary/natural-language-processing/">NLP</a>. If you are using character encoding in NLP, the results should be in comparable range as you would one hot encode more than around 50 characters. If you are using word encoding and using any of the popular word embedding schemes, the system has the advantage of advanced embedding techniques but will have to figure out language semantics. I stuck to numbers as there is no subjectivity to the results unlike NLP. For your NLP use cases, I hope the tables presented here will give rough starting points and I would encourage you to carry out your experiments for specific use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/0*hZxMiA9Advd8Z0q1" /></figure><p>Amaresh is a researcher in the areas of Machine Learning and Natural Language Processing. Additionally he works in the area of learning and development for professionals in the IT services industry. He uses Python and TensorFlow for his research work. In these columns he shares his experiences with the intention of helping the reader understand concepts and solving problems. He is based out of Mumbai, India.</p><p><em>Originally published at </em><a href="https://www.datadriveninvestor.com/2020/03/24/encoder-decoder-sequences-how-long-is-too-long/"><em>https://www.datadriveninvestor.com</em></a><em> on March 25, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2d1ae14d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Math in ML: Cosine Similarity | Data Driven Investor]]></title>
            <link>https://medium.com/@amareshp72/the-math-in-ml-cosine-similarity-data-driven-investor-dfb0a058f5ac?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb0a058f5ac</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 09:37:02 GMT</pubDate>
            <atom:updated>2019-11-20T09:37:48.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*7B9r1NCWlNSZ7NPu" /></figure><p>In <a href="https://www.datadriveninvestor.com/glossary/machine-learning/">Machine Learning</a>, we frequently express the similarity between two vectors as cosine similarity. What exactly does that mean? What has ‘cosine’ got to do with similarity?</p><p>Well, there is Math in ML and cosine similarity between vectors has everything to do with Math. Let us refresh what is a <a href="https://www.datadriveninvestor.com/glossary/vector/">vector</a>, and then we come to what is the cosine between two vectors.</p><p><strong>What is a </strong><a href="https://www.datadriveninvestor.com/glossary/vector/"><strong>Vector</strong></a><strong>?</strong></p><p>A vector is a column of numbers enclosed in brackets, like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*HuO8cm1XsPmaukal" /></figure><p>As a special case, a two dimensional vector is a column of two numbers enclosed in brackets, like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/0*x_qJqBYa0ggnVsos" /></figure><p>When you use a variable to represent a vector, you typically differentiate that variable from the variable used to represent a scalar (a normal number) by using a boldface letter while using print or electronic media (for example, <strong>u</strong>) and using an arrow above the letter while using handwriting.</p><p>A two dimensional vector is represented by an arrow in the two dimensional Cartesian space, like this.</p><p>Two vectors in Cartesian space are considered to be equal if</p><ol><li>Both have the same length</li><li>Both are in the same direction and are parallel to each other</li></ol><p>Hence, we can have another arrow in the same Cartesian space equal to <strong>u</strong> if it is of the same length and in the same direction, and parallel to <strong>u</strong>. It could start at a point other than O.</p><p>Similarly, a three dimensional vector is represented by an arrow in the three dimensional Cartesian space, like this.</p><p>Like two dimensions, here also any other vector that is of the same length as <strong>u</strong>, parallel to<strong> u </strong>and has the same direction would be considered equal to <strong>u</strong> even if it starts at a point other than O.</p><p>For any positive integer n greater than or equal to 1, an n-dimensional vector is a column of n numbers enclosed in brackets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*5BedKwxVvSPnKaUq" /></figure><p>An n-dimensional vector still exists, though we are unable to represent it using an arrow in the Cartesian space for n greater than 3.</p><p><strong>Vector Addition</strong></p><p>The addition of two vectors is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*wtceIsh4H3u-OCbO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*_3oY98duFoRNaDXE" /></figure><p>You can see the triangle law of vector addition in the above diagram. You can plot them in two or three dimensions and convince yourself that the x, y (and z, if present) components of the vectors indeed add up this way.</p><p><strong>Vector Subtraction</strong></p><p>Vector subtraction is defined very similar to vector addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*aonsaDn9T_yvZjJt" /></figure><p>In two and three dimensions, the subtraction of two vectors follows from the way we do addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*UqUNqWcRmYfHuYuu" /></figure><p><strong>Length of a Vector</strong></p><p>Let us come back to a two dimensional vector. We said a two dimensional vector can be represented by an arrow. What will be the length of that arrow?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*hlPM0rLSJGF8vK9e" /></figure><p>By Pythagoras theorem, length of <strong>u</strong>, which is denoted by || <strong>u</strong>||, will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*u6Sqan4S1pEImebj" /></figure><p>What about a three dimensional vector?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*zxu9BeA-Vuf2cICa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*CNQ5aVD8uwVPdpMO" /></figure><p>Let us return to the n dimensional vector <strong>u</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*MprTeath-QS7dmg4" /></figure><p>We have already seen that for n = 2 and for n = 3, the above equation actually represents the length of the arrow represented by <strong>u</strong>. But for n &gt; 3, the length of the vector is just a definition.</p><p><strong>Cosine of the Angle between Vectors</strong></p><p>Let us start with the simple case of two dimensional vectors, which can be represented by arrows. Because they can be represented by arrows, the angle between them can be visualized and we can find out the cosine of that angle by using geometry. We will be using the <a href="https://en.wikipedia.org/wiki/Law_of_cosines">cosine rule</a> of trigonometry. The Wikipedia article I have linked to in the previous sentence contains the mathematical proof of the rule and the diagram below is also from the same article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*S6WfkV0ld14XiqXp" /></figure><p>The image below applies the same cosine rule to two dimensional vectors <strong>u </strong>and <strong>v</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*0JaV_2LDGMQZ4sRD" /></figure><p>The quantity u 1v 1 + u 2v 2 is called the dot product of the two vectors <strong>u </strong>and <strong>v</strong>.</p><p>So the equation from the diagram becomes,</p><p>What if <strong>u </strong>and <strong>v </strong>are three dimensional vectors? Cosine rule applied to vector difference in the diagram above will still hold true.</p><p>Let us start with that premise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*wqui-jythDFC07UX" /></figure><p>Hence the equation from the diagram becomes</p><p>Which is the same as what it was for two dimensions.</p><p>So both for two dimensions and for three dimensions,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/0*I98ZBHLogyYyFmwB" /></figure><p>For the n dimensional vectors <strong>u </strong>and <strong>v</strong>, the dot product of the two vectors is defined as,</p><p>For n dimensional vectors, we cannot draw arrows representing those vectors and so we cannot visualize the angle between them. Then we simply define the cosine of the angle between the two vectors to be just like what we have in two and three dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*zpgrx2yAeKGSlD-a" /></figure><p>The definition will be valid, if, as per trigonometry law, the cosine is less than or equal to 1, and greater than or equal to -1. That is actually the case, is proven by <a href="https://brilliant.org/wiki/cauchy-schwarz-inequality/">Cauchy-Schwarz inequality</a>. The article I have linked to also provides proof of the inequality.</p><p>Cosine similarity of two vectors is just the cosine of the angle between two vectors. Two vectors with the same orientation have the cosine similarity of 1 (cos 0 = 1). Two vectors with opposite orientation have cosine similarity of -1 (cos π = -1) whereas two vectors which are perpendicular have an orientation of zero (cos π/2 = 0). So the value of cosine similarity ranges between -1 and 1.</p><p>It is also important to remember that cosine similarity expresses just the similarity in orientation, not magnitude. So if <strong>u </strong>and <strong>v </strong>are parallel to each other but <strong>u </strong>is twice of <strong>v</strong> in magnitude, cosine similarity will still be 1.</p><p><strong>Back to ML</strong></p><p>The <a href="https://www.datadriveninvestor.com/glossary/python/">Python</a> scikit-learn library provides a function to calculate the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html">cosine similarity</a>. Let us use that library and calculate the cosine similarity between two vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*SFxAI0iSF_rFQ4bd" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*4eNirN4fkwfPsazw" /></figure><p>The scikit-learn method takes two matrices instead of two vectors as parameters and calculates the cosine similarity between every possible pair of vectors between the two parameters and returns the result as a matrix. Since we have only two vectors and the result is a scalar, we used square brackets to pass parameters as matrices and get the return value as a scalar.</p><p>Just to reiterate, if two vectors are parallel (in the example below, the second one is just twice the first one), the cosine similarity is 1 except for the rounding off error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*_s3errNIHQWr8x8J" /></figure><p>To summarize, we looked at what are vectors, how to add and subtract vectors, what is the length of a vector, and all of this resulted in understanding how to calculate the angle between two vectors by defining the dot product between two vectors. We cross-checked that the programming results for the cosine similarity match what we calculated using Maths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/0*8_aMmIdpHllbfav7" /></figure><p><em>Originally published at </em><a href="https://www.datadriveninvestor.com/2019/11/20/the-math-in-ml-cosine-similarity/"><em>https://www.datadriveninvestor.com</em></a><em> on November 20, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb0a058f5ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network: A Counter Example]]></title>
            <link>https://medium.com/@amareshp72/neural-network-a-counter-example-9760fff9b571?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/9760fff9b571</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 05:56:24 GMT</pubDate>
            <atom:updated>2019-07-30T05:56:24.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural networks find pattern in your data and help you with unseen examples using the pattern they have discovered. What if there is no pattern in your data and your data is just random? The best neural network also will not be able to find anything then and your accuracy would then be in doldrums. In this article I take a successful neural network model and turn the data around so that it becomes a counter example.</p><p>I am using the code from this <a href="https://pythonprogramming.net/introduction-deep-learning-python-tensorflow-keras/">article</a>. I get 97%+ accuracy when I implement the code myself. I made a small change after that — I shuffled the ‘y’ values for both the training and the test data sets. Because of the random nature of shuffling, the ‘ideal’ labels for each row of the training and test sets become random. As a result, training is not able to detect anything. Let me produce the code, and you refer to the original article for an explanation of the code, if desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*JSbd24pyXJCzk_64COKJ-g.png" /><figcaption>Get libraries and data</figcaption></figure><p>Then comes my only code that is different from the original article — shuffling the ‘y’ values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*2Mg6kNVb2fp5sKCVtEdEHw.png" /><figcaption>Shuffle</figcaption></figure><p>The rest of the code is from the original article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ZVHhwZJ0-iyWQM06DrtYQg.png" /><figcaption>Check ‘x’ values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*AM0Uf1Cu-du5FNQyFdsCJQ.png" /><figcaption>Display values</figcaption></figure><p>Note that the ‘x’ value is the handwriting for ‘5’ and because of the shuffling, the corresponding ‘y’ value is ‘4’. Owing to the random nature of shuffling, you may get something other than ‘4’ when you run my code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*cIZzzW0nXteaU9asi5ukdw.png" /><figcaption>Show values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG-pkEh-htK0hfkNbYV_rg.png" /><figcaption>The model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*mP5-YwvXI3xzHF_dP5tM3A.png" /><figcaption>The results</figcaption></figure><p>Note that the accuracy values are just over 11%. In MNIST, you have to recognize handwritten digits. There are 10 digits — ‘0’ to ‘9’. If you make a guess, you are 1 / 10 = 10% likely to be right and the accuracy values you are getting here is in that range.</p><p>I have retained the model from the original article, which gives over 97% accuracy, and only changed the data. Even the best model does not work well on all possible kinds of data. If there is no pattern, the neural network cannot find any pattern. While you tune your network, just make sure your data is proper — if your data is not right, even the best tuned network will not give you good scores.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9760fff9b571" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network: Check Before You Run]]></title>
            <link>https://medium.datadriveninvestor.com/neural-network-check-before-you-run-25443f700abb?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/25443f700abb</guid>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 08:59:56 GMT</pubDate>
            <atom:updated>2019-07-08T12:51:58.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*xO6Rlxdm7rI77qn2" /></a></figure><p>Your neural network is not giving you the accuracy and performance you expected? Since a lot of the neural network is a black box hidden behind a lot of mathematics, debugging a neural network is not trivial. In this article I am giving you a couple of checks that you can run to see if your network would be doing fine if you train it on real-world data.</p><p>I am reusing the code I had presented in one of my <a href="https://medium.com/datadriveninvestor/getting-reproducible-results-in-tensorflow-3705536aa185">previous</a> articles. Though this article is not exactly a continuation, you may want to check the previous article for a better understanding of why I am coding certain parts of the network in a certain way. I am first building a good network for the MNIST data set and then I am deliberately making mistakes to compare and show a couple of points I recommend you check in your own networks.</p><p><a href="https://www.datadriveninvestor.com/2019/03/01/the-myth-of-ais-predictive-power/">The Myth of AIs&#39; Predictive Power | Data Driven Investor</a></p><p>The first five cells of our notebook initialize some variables and fetch data. I am initializing a variable _EPSILON to a very small number. Inspiration from this variable comes from going through the source code for TensorFlow Keras for gradient clipping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*34EfYtfZ1vx06NkL1QRDAQ.png" /><figcaption>Initialize and fetch data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*CchG5vgJlmWLokg9vbpwVw.png" /><figcaption>Variables for results</figcaption></figure><p>Here we will be attempting to find out the values that are output by the hidden nodes of the network after their activation functions are applied. We are creating a set of variables to hold the outputs of the hidden nodes, accuracy and loss values as the network goes from epoch to epoch.</p><p>We will be using the Glorot initializer for initializing our network weights. Next I am running a cell to indicate that the TensorFlow Glorot uniform initializer is the same as the random uniform initializer if you use specific formulas to calculate the upper and lower limits. Since this is just a demonstration, we will create a small matrix of shape 3 x 3, which you can imagine to be the weights of an imaginary layer of a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdGnJAtgvXeCeXCcyqY0uw.png" /><figcaption>Glorot uniform initializer</figcaption></figure><p>We then build a network for MNIST with two hidden layers. The weights are initialized using a random uniform initializer with the same formula as Glorot, so we can consider that to be the same as Glorot initialization. This is my example of a ‘good’ network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*aBTWYc9FFOYWhQpZm6u11g.png" /><figcaption>Network with Glorot initialization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Fik1no1E9zjJnZLchfdfiA.png" /><figcaption>Accuracy</figcaption></figure><p>Next, write the code to calculate the accuracy of the network.</p><p>Then we train the network. Note that while running the TensorFlow session, we record the values of the hidden layers in addition to the loss and predicted values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCLnPULBIyBDRzzzMQkwnA.png" /><figcaption>Train the network</figcaption></figure><p>The textbook says the predicted values should not be too small or too large, and since we are using softmax in the output layer for the prediction, the predicted values should not be close to zero or one. Notice in the previous screenshot that for the first epoch and the first batch, we have saved the values of the prediction. If the initialization is done properly, the result of the matrix multiplications and activation functions should not give very high or low values. For the subsequent batches and epochs, the weights and biases would be modified due to training. So essentially we are checking for correct initialization when we are checking the values of the predictions for the first batch of the first epoch. In softmax, when the output is close to zero or one, the gradient becomes very low/high and hence training becomes unreliable. Here we define close to zero as less than _EPSILON and close to one as greater than one minus _EPSILON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*XzTREW7uJrbUjvF_FtNcAg.png" /><figcaption>Checking for small and large values</figcaption></figure><p>We will now repeat the experiment for a ‘bad’ network where we deliberately initialize the weights to a high value — a truncated normal initialization with a standard deviation of 0.5, which is quite high for weights of sizes like 784 or 128.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXBCJpoXVG8TP2_XIvUKEQ.png" /><figcaption>The next network</figcaption></figure><p>Running this network is similar to the previous network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4RDaro_sSGG87fqBXCoAA.png" /><figcaption>Running the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*ONHZoR_JvTW1JQOsu6_A7Q.png" /><figcaption>Checking for very small and very large values</figcaption></figure><p>Notice that this network has 80% very small or very large values in the very first prediction, which was 0% for the previous network. This is not a good sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*5ZmoKSKRpiqKlLaf7e7cIQ.png" /><figcaption>Plot loss and accuracy</figcaption></figure><p>Now write code to plot the loss and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*7lE93FnSGLq6HEFeM86CiQ.png" /><figcaption>Loss and accuracy plot</figcaption></figure><p>Note that loss is lower for Glorot initialization — the ‘good’ network and higher for the truncated normal initialization with 0.5 standard deviation — the ‘bad’ network. Similarly, accuracy looks better for the ‘good’ network compared to the ‘bad’ network.</p><p>We will now plot the values of the hidden nodes we had collected. Notice that for the ‘good’ network, the hidden node outputs are comfortably below 1 (and above zero). For the ‘bad’ network, the first hidden nodes are less than one whereas the second hidden nodes are staying above one. That is not desirable, as you can see the training is trying to bring those values down. In comparison, training is trying to increase the values of the hidden nodes in the ‘good’ network. You need to be careful with the relu activation function for the hidden layers. Though there is a reason we now use relu, unlike softmax it does not bring the output of the hidden nodes back to the zero to one range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*uzbg4QFjUZPxmCZpT-_jAg.png" /><figcaption>Hidden nodes</figcaption></figure><p>This effect is more prominent when you have more hidden layers. We will be repeating these experiments with three hidden layers now. You will need more variables as you will have more hidden layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*lB80DVbW-zNUoXazP9UPrQ.png" /><figcaption>Initialize variables</figcaption></figure><p>Next, we will build the ‘good’ network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMHPtzwTBCnKHQTeM_QBRw.png" /><figcaption>Build the network</figcaption></figure><p>Then we add the loss, optimization and accuracy calculations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*ZPLrbfLn4oferI6IOTvr4g.png" /><figcaption>Complete the network</figcaption></figure><p>Let us now run this network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*XPK_YTq4lZKuj78kNAaFzg.png" /><figcaption>Run the network</figcaption></figure><p>Check for extreme values and build the next network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KL0mNurfG_AM-OI1LMkcKA.png" /><figcaption>Next network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*utN73Ef0jH9au6z_XXM2UQ.png" /><figcaption>Loss and optimizer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*q6UD_3hqfWLEcaXnpQYYog.png" /><figcaption>Run the network</figcaption></figure><p>Note that 99% of the predicted values are now very small or large, not a good sign again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Al-BgRuUuS1B-opqBm-EBQ.png" /><figcaption>Plot loss and accuracy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*CZdey65OHEwYKS1AS2llOA.png" /><figcaption>Loss and Accuracy</figcaption></figure><p>All the three hidden nodes start at small values for the ‘good’ network, and increase with epochs but stay below 1. All the hidden nodes for the ‘bad’ network start at higher values and reduce with training. The first hidden nodes are below 1, but the subsequent ones go higher and higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*_aykcBdLcidOXT1BenjFIw.png" /><figcaption>Hidden nodes</figcaption></figure><p>This effect is even more pronounced when there are more hidden layers. Let us now see what happens when we have four hidden layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*cHtP0gDIBuMuuup12A67Bw.png" /><figcaption>Initialize variables</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai4wWxuWIouGLmP66_v49w.png" /><figcaption>Build the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*tndaxRB_cnWH_DZ0oEZATw.png" /><figcaption>Loss, optimizer and accuracy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lh9xzulTB8hNYLMf_DtsVw.png" /><figcaption>Run the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*_lL2juGkFdpmW5VekMgjRw.png" /><figcaption>High and low values</figcaption></figure><p>Let us now build the ‘bad’ network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWpkSNA-wSyeMyo7240I6Q.png" /><figcaption>Build the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMNaU-5vylMATfpDQhcF6Q.png" /><figcaption>Run the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*MjFEu_fmMQrrMrqYCOjnzQ.png" /><figcaption>Large and small values</figcaption></figure><p>Note that now 100% of the values in the first prediction are too large or too small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*SU7BEoX4siiXt8rYf7FeiA.png" /><figcaption>Loss and accuracy</figcaption></figure><p>Note that the four hidden nodes of the ‘good’ network stay at comfortably low values but the hidden nodes of the ‘bad’ network see to be ‘running away’, with the last hidden nodes hitting very high values. This is undesirable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CB8i4K8lIgqozMwqHJp4VQ.png" /><figcaption>Hidden nodes</figcaption></figure><p>To summarize, check the following couple of things before you train your neural network in production:</p><ol><li>Check for the output values (predictions) in the first batch of the first epoch. There should be a few high/low values.</li><li>Check for the output values of your hidden nodes. As far as possible they should stay below one. The later layers ‘running away’ to very high values is a sign of trouble.</li></ol><p>Note that these checks are necessary but may not be sufficient. I have seen networks that pass the above two checks but still fail to do well in the training metrics. You may need to dig deeper to find what could be wrong.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25443f700abb" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/neural-network-check-before-you-run-25443f700abb">Neural Network: Check Before You Run</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradients in TensorFlow]]></title>
            <link>https://medium.datadriveninvestor.com/gradients-in-tensorflow-9257d7bc5610?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/9257d7bc5610</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Wed, 03 Jul 2019 10:06:38 GMT</pubDate>
            <atom:updated>2019-07-04T14:17:32.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Rx9L0gA406NturOA" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XTvwwf7tYtIkbZEH" /><figcaption>Photo by <a href="https://unsplash.com/@lanceanderson?utm_source=medium&amp;utm_medium=referral">Lance Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A neural network starts with an initial set of weights and calculates its first output as per the architecture of the network. It then compares the output with the expected output present in the data and calculates the loss. To reduce the loss, the network calculates the gradients of loss with respect to the various trainable variables and uses these gradients to recalculate the trainable variables, and then again calculate the output iteratively.</p><p>If your network does not perform as expected, checking the values of these gradients may be a good way to find out what is going wrong. Here we discuss how do you find out the values of your gradients if you are using TensorFlow to build and run your neural network.</p><p><a href="https://www.datadriveninvestor.com/2019/03/03/editors-pick-5-machine-learning-books/">DDI Editor&#39;s Pick: 5 Machine Learning Books That Turn You from Novice to Expert | Data Driven Investor</a></p><p>I am extending the code presented in one of my previous <a href="https://medium.com/datadriveninvestor/getting-reproducible-results-in-tensorflow-3705536aa185">articles</a> and adding the code to display the gradients. The first five cells are the same as the previous article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*kYK3e70_JYCnyRMNoqYuMw.png" /><figcaption>Get training data</figcaption></figure><p>Next we build the TensorFlow graph just as in the previous article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*UbNuA_q2lZoIp6Tm5kUTpQ.png" /><figcaption>Build TensorFlow graph</figcaption></figure><p>Normally we minimize the loss after this. Minimizing the loss consisting of computing the gradients and applying the gradients. Instead of calling the minimize method of the optimizer as in the previous article, call the compute gradient and apply gradient methods one after the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*1jrsZ_z3y2fzGvhCuvjRmQ.png" /><figcaption>Gradients</figcaption></figure><p>Calculating the accuracy is the same as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*RpQXRZA5-y3R2JXpresmsA.png" /><figcaption>Accuracy</figcaption></figure><p>The compute gradients method extracts the gradients and variables as tuples, which we run inside a TensorFlow session to get the values into Python. Here there are six variables which will be trained — three weights and three biases — weights1, weights2, weights3, biases1, biases2, and biases3. The gradients are the partial derivatives of the loss with respect to each of the six variables. TensorFlow presents the gradient and the variable of which it is the gradient, as members of a tuple inside a list. We display the shapes of each of the gradients and variables to check that is actually the case. We then also display the means of the gradients and variables for the first batch, though you can do the same for the entire data set if you are interested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZii1nRoRJnjsEmLdSBVDg.png" /><figcaption>Run the network</figcaption></figure><p>I am showing the output for the first epoch. Output for the remaining two epochs is similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Gs5I_cu8hi-59iH52XZ0Kw.png" /><figcaption>Output</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9257d7bc5610" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/gradients-in-tensorflow-9257d7bc5610">Gradients in TensorFlow</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Match TensorFlow and Keras: Sigmoid]]></title>
            <link>https://medium.datadriveninvestor.com/match-tensorflow-and-keras-sigmoid-64732a96cdc0?source=rss-2515722c3c27------2</link>
            <guid isPermaLink="false">https://medium.com/p/64732a96cdc0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Amaresh Patnaik]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 06:24:42 GMT</pubDate>
            <atom:updated>2019-06-27T13:47:45.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*vAwBzq-NJQ-ZM2uA" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rmuG-vOU3QgIhJHz" /><figcaption>Photo by <a href="https://unsplash.com/@hjrc33?utm_source=medium&amp;utm_medium=referral">Héctor J. Rivas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For the same neural network, you should get the same results whether you use TensorFlow or you use Keras to implement your network. We saw that in my previous <a href="https://medium.com/@amareshp72/match-tensorflow-results-and-keras-results-ccbf80f2f68f">article</a>. We used softmax as the activation function in the last layer and used the corresponding sparse softmax cross entropy loss function in TensorFlow and sparse categorical cross entropy loss function in Keras. That is what you typically do when you have a single-label classification, i.e., one row of data can be classified into only one label. That is the case with the MNIST data set, where one handwritten digit can only be one of the ten digits.</p><p>There will however be cases where one row of data can be classified into more than one label simultaneously and we call that to be a multi-label case. If we are working on a multi-label use case, we typically use sigmoid as the activation function in the output layer. The corresponding loss function is sigmoid cross entropy in TensorFlow and binary cross entropy in Keras. In this article, we will use the sigmoid activation function and the corresponding loss function and tally the results between TensorFlow and Keras. Though ideally, I should have taken a use case having multi-label classification, I will use the MNIST example for continuity and the concepts will hold good for another use case too. This article is a continuation of my previous article, so please go through my previous article first.</p><p><a href="https://www.datadriveninvestor.com/2019/03/03/editors-pick-5-machine-learning-books/">DDI Editor&#39;s Pick: 5 Machine Learning Books That Turn You from Novice to Expert | Data Driven Investor</a></p><p>Let us first write the TensorFlow code. The first five cells in the notebook are based on my previous article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*VqF4alnPBnAzbsHmwmPQEQ.png" /><figcaption>Initialize and get data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*rbwTmXgGAyPJZ9Gc5acOrA.png" /><figcaption>Binarize</figcaption></figure><p>Since there is a likelihood the labels could be multiple per data row, we will binarize the input so that there could be multiple ones per row in the binarized data.</p><p>We will now build the network. Note that due to binarization, the placeholder for the labels is now having different dimensions compared to my last article. Also, note that we have now changed the activation function to sigmoid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xs1FRfoXiLkOPQ7mnOEuwA.png" /><figcaption>Build the network</figcaption></figure><p>Now calculate the loss and create the optimizer. Note there is a different loss function now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*76T7Iwf_SxtBU9d2mSBFIQ.png" /><figcaption>Loss and optimizer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*qDrZpzeySfvAhqBSvE823g.png" /><figcaption>Accuracy</figcaption></figure><p>The calculation for accuracy will also be different considering that the labels are now binarized and fed to the network.</p><p>Run the network now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyKC0o6jLPOCiLuWL7_xBw.png" /><figcaption>Run network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*lcSi7xxJLJzWN1jPzIHDWQ.png" /><figcaption>Output</figcaption></figure><p>And here is the output.</p><p>Now let us write the equivalent code in Keras. The first seven cells are either as per my previous article or the TensorFlow code part of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_TEHgvsdGT3GUANM3mjXQ.png" /><figcaption>Initialize and get data</figcaption></figure><p>Build the model. Note the activation function in the last layer and the loss function while compiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p4ziJiRLtfZc3_WxWWtGA.png" /><figcaption>Build and compile the model</figcaption></figure><p>Fit the model. Tally the loss and accuracy values with the output of the TensorFlow code. The values match except for rounding off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdyU7BiUkCeap7awv_gI4g.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64732a96cdc0" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/match-tensorflow-and-keras-sigmoid-64732a96cdc0">Match TensorFlow and Keras: Sigmoid</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>