<?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 Kaustubh Bhavsar on Medium]]></title>
        <description><![CDATA[Stories by Kaustubh Bhavsar on Medium]]></description>
        <link>https://medium.com/@kaustubhbhavsar?source=rss-3c727e10b97f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V9040t5BbmVhV7aWuUIk4A.png</url>
            <title>Stories by Kaustubh Bhavsar on Medium</title>
            <link>https://medium.com/@kaustubhbhavsar?source=rss-3c727e10b97f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:12:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaustubhbhavsar/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[Prompt Engineering for Arithmetic Reasoning Problems]]></title>
            <link>https://medium.com/data-science/prompt-engineering-for-arithmetic-reasoning-problems-28c8bcd5bf0e?source=rss-3c727e10b97f------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c8bcd5bf0e</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Kaustubh Bhavsar]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 15:42:54 GMT</pubDate>
            <atom:updated>2023-11-18T15:42:54.317Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore various prompt engineering techniques for arithmetic reasoning problems, best practices, and rapid experimentations for production-grade prompts with Vellum.ai</h4><figure><img alt="Architecture of 4 different prompting techniques: Input Output, Chain-of-Thought (CoT), Self Consistency with Chain-of-Thought (CoT), and Tree of Thought (ToT)" src="https://cdn-images-1.medium.com/max/678/1*c8Ntxy8j5G8Xuf2-iZ8FpA.png" /><figcaption>Architecture of four different prompting techniques: Input-Output, Chain-of-Thought (CoT), Self Consistency with Chain-of-Thought (CoT), and Tree of Thought (ToT) (Image from <a href="https://arxiv.org/abs/2305.10601">Yao et el. (2023)</a>)</figcaption></figure><h3><strong>Introduction</strong></h3><p>Large Language Models (LLMs) have been drawing increasing attention from both academic researchers and industry experts due to their proficiency in understanding and generating language. The reason behind their text comprehension skills lies in their training process, which involves exposure to vast amounts of data with the primary goal of predicting subsequent words. To optimize these models for specific tasks, fine-tuning is essential. This can be achieved through two methods: ‘pre-training and fine-tuning’ or ‘prompt fine-tuning’.</p><p>In the conventional ‘pretraining and fine-tuning’ approach, the LLM is fine-tuned on a dataset pertinent to the tasks it will perform later, thereby updating parameters in the fine-tuning phase. Conversely, ‘prompt fine-tuning’ guides the model with a text segment to execute the task.</p><p>A prompt is an input provided by the user that the model is designed to respond to. Prompts can contain instruction, context, question or an output indicator. Prompt engineering is an emerging field dedicated to the development and refinement of prompts for the effective utilization of language models.</p><p>However, a significant challenge lies in ensuring the model can tackle problems necessitating arithmetic and commonsense reasoning. In this article, our focus is specifically on the engineering of prompts for arithmetic problems.</p><h3><strong>Prerequisites</strong></h3><p>No prior knowledge is required. All the demonstrations provided below can be executed either on the <a href="https://platform.openai.com/playground">OpenAI Playground</a> or run through the <a href="https://openai.com/blog/openai-api">OpenAI API</a>. Although this article primarily utilizes OpenAI models, it’s important to note that these are merely prompting techniques that we’ll be exploring, and you’re free to apply any LLM available in the market.</p><h3><strong>Prompt Engineering for Arithmetic Problems</strong></h3><p>All the problems mentioned henceforth are taken from the <a href="https://huggingface.co/datasets/gsm8k">GSM8K</a> dataset and are tested using OpenAI’s <strong>GPT-3.5 Turbo Instruct</strong> model with default configurations.</p><p>We will be testing various techniques specifically on the following arithmetic problem:</p><pre>Jennifer purchased 40 cans of milk at the store before meeting her <br>classmate Mark, who was also buying milk. Jennifer bought 6 additional <br>cans for every 5 cans Mark bought. If Mark purchased 50 cans, how many <br>cans of milk did Jennifer bring home from the store?</pre><p>The correct answer to the above problem is <strong>100 litres</strong>.</p><h3><strong>Zero-Shot Prompting</strong></h3><p>A <strong>shot </strong>essentially refers to <strong>an example</strong>. Zero-shot is a basic prompting technique in which a question is posed to the model without providing any demonstrations. This technique, in general, produces favourable results in larger models that have been trained on extensive amounts of data.</p><h4><strong><em>Prompt:</em></strong></h4><pre>Q: {{ question }}<br>A:</pre><h4><strong><em>Output:</em></strong></h4><pre> Jennifer brought home 76 cans of milk from the store.</pre><p>In the preceding prompt, we didn’t prepend the question with any demonstrations, leading to the models&#39; failure to provide the correct answer for the arithmetic problem. Reasoning and commonsense problems seldom yield satisfactory results with zero-shot prompts. Therefore, it’s essential to include examples when dealing with such problems.</p><h3>Few-Shot Prompting</h3><p>With few-shot prompting, we provide the model with a small number of demonstrations, also known as exemplars. These exemplars serve to guide the model so that the subsequent questions can be similarly handled. The number of demonstrations needed varies based on the complexity of the problem and the specific model in use.</p><h4>Prompt:</h4><pre>Q: Ken created a care package to send to his brother, who was away at boarding school. Ken placed a box on a scale, and then he poured into the box enough jelly beans to bring the weight to 2 pounds. Then, he added enough brownies to cause the weight to triple. Next, he added another 2 pounds of jelly beans. And finally, he added enough gummy worms to double the weight once again. What was the final weight of the box of goodies, in pounds?<br>A: 16<br><br>Q: Mark has a garden with flowers. He planted plants of three different colors in it. Ten of them are yellow, and there are 80% more of those in purple. There are only 25% as many green flowers as there are yellow and purple flowers. How many flowers does Mark have in his garden?<br>A: 35 <br><br>Q: James writes a 3-page letter to 2 different friends twice a week. How many pages does he write a year? <br>A: 624 <br><br>Q: Albert is wondering how much pizza he can eat in one day. He buys 2 large pizzas and 2 small pizzas. A large pizza has 16 slices and a small pizza has 8 slices. If he eats it all, how many pieces does he eat that day?<br>A: 48<br><br>Q: Betty is saving money for a new wallet which costs $100. Betty has only half of the money she needs. Her parents decided to give her $15 for that purpose, and her grandparents twice as much as her parents. How much more money does Betty need to buy the wallet?<br>A: 5<br><br>Q: {{ question }}<br>A:</pre><h4>Output:</h4><pre>76</pre><p>Although this technique works well in tackling difficult problems, the model may still fail to find satisfactory results in arithmetic reasoning problems. This is because the model fails to reason immediate steps.</p><h3><strong>Few-Shot Chain-of-Thought (CoT) Prompting</strong></h3><p><a href="https://arxiv.org/abs/2201.11903">Few-shot chain-of-thought (CoT)</a> prompting equips the model with a few examples to guide it through the process of reaching a solution. This guidance, also known as intermediate reasoning steps, is crucial in assisting the model to work through the steps and generate the desired output logically.</p><h4><strong><em>Prompt:</em></strong></h4><pre>Q: James writes a 3-page letter to 2 different friends twice a week. How many pages does he write a year? <br>A: He writes each friend 3*2=6 pages a week So he writes 6*2=12 pages every week That means he writes 12*52=624 pages a year. The answer is 624.<br><br>Q: {{ question }}<br>A:</pre><h4><strong><em>Output:</em></strong></h4><pre> Jennifer bought 40+6/5*50=40+12*10=40+120=160 cans of milk. The answer is 160.</pre><p>In the above output, the model attempted to reason through the steps but arrived at the incorrect final answer. We observe that this discrepancy may be attributed to the irrelevant example provided. There are two ways to address this issue: either provide the model with more examples or ensure that the examples given are relevant. Below, we attempt to rectify this with a relevant example.</p><h4><strong><em>Prompt:</em></strong></h4><pre>Q: Mark has a garden with flowers. He planted plants of three different colors in it. Ten of them are yellow, and there are 80% more of those in purple. There are only 25% as many green flowers as there are yellow and purple flowers. How many flowers does Mark have in his garden?<br>A: There are 80/100*10=8 more purple flowers than yellow flowers. So in Mark&#39;s garden, there are 10+8=18 purple flowers. Purple and yellow flowers sum up to 10+18=28 flowers. That means in Mark&#39;s garden there are 25/100*28=7 green flowers. So in total Mark has 28+7=35 plants in his garden. The answer is 35.<br><br>Q: {{ question }}<br>A:</pre><h4><strong><em>Output:</em></strong></h4><pre> For every 5 cans Mark bought, Jennifer bought 6 additional cans. So for 50 cans, Jennifer bought 6/5*50=60 additional cans. In total, Jennifer bought 40+60=100 cans of milk. Therefore, Jennifer brought home 100 cans of milk from the store.</pre><p>The final answer obtained is now correct. Consider the task, the choice of the model, and the relevance of examples, as all contribute to arriving at the correct solution.</p><h3>Program-Aided Language Model (PAL)</h3><p>A <a href="https://arxiv.org/abs/2211.10435">program-aided language model (PAL)</a> is not a prompting technique; instead, it is an application of prompt engineering. Similar to CoT, PAL aims to reason out the intermediate steps. However, instead of using regular text as reasoning steps, PAL uses intermediate programmatic steps using programmatic runtime such as Python interpreter.</p><h4><strong><em>Prompt:</em></strong></h4><pre>Q: James writes a 3-page letter to 2 different friends twice a week. How many pages does he write a year? <br>A: #James has<br>number_of_friends=2<br><br>#He writes each friend 3-page letter each time.<br>page_letter_size=3<br><br>#He writes twice to each friend in a week.<br>number_of_times_written_to_friend=2<br><br>#Total pages written in a week to each friend<br>pages_written_to_each_friend_per_week=page_letter_size*number_of_times_written_to_friend=6<br><br>#So, total pages written by him per week,<br>total_pages_each_week=pages_written_to_each_friend_per_week*number_of_friends=12<br><br>#Number of weeks in a year<br>total_weeks_in_a_year=52<br><br>#That means he writes,<br>total_pages_written_in_year=total_pages_each_week*total_weeks_in_a_year=624<br>#pages per year.<br><br>The answer is 624.<br><br>Q: {{ question }}<br>A:</pre><h4><strong><em>Output:</em></strong></h4><pre>#Jennifer initially bought 40 cans of milk.<br>initial_cans_bought=40<br><br>#For every 5 cans Mark bought, Jennifer bought 6 additional cans.<br>additional_cans_bought=6<br>mark_cans_bought=50<br><br>#So, for every 5 cans Mark bought, Jennifer bought 6 additional cans.<br>additional_cans_bought=6<br>mark_cans_bought=50<br><br>#Number of times Mark bought 5 cans<br>number_of_times_mark_bought=mark_cans_bought/5=10<br><br>#Total additional cans bought by Jennifer<br>total_additional_cans_bought=additional_cans_bought*number_of_times_mark_bought=60<br><br>#Total cans of milk brought home by Jennifer<br>total_cans_brought_home=initial_cans_bought+total_additional_cans_bought=40+60=100<br><br>The answer is 100 cans of milk.</pre><p>Even with the irrelevant example that failed to yield a correct answer using the few-shot CoT technique, PAL successfully found the correct final solution.</p><h3>Zero-Shot Chain-of-Thought (CoT) Prompting</h3><p>In a situation where demonstrations for the few-shot chain-of-thought (CoT) technique are not available, a straightforward and effective approach is to ask the model itself to reason through the intermediate steps. This is called the zero-shot chain-of-thought (CoT). You can achieve this by adding a text similar to ‘Let’s think step by step…’ to the prompt question. This simple technique has shown exceptional results.</p><h4><strong><em>Prompt:</em></strong></h4><pre>Q: {{ question }}<br>A: Let&#39;s think step by step...</pre><h4><strong><em>Output:</em></strong></h4><pre><br>1. Jennifer initially bought 40 cans of milk.<br>2. For every 5 cans Mark bought, Jennifer bought 6 additional cans.<br>3. Since Mark bought 50 cans, Jennifer bought 6 additional cans for every 5 cans, which means she bought (6/5) x 50 = 60 cans.<br>4. Therefore, Jennifer brought home a total of 40 + 60 = 100 cans of milk from the store.</pre><p>From the above example, we observe that the model successfully reasons through the steps and arrives at the correct solution without requiring any examples or guidance.</p><h3>Tree-of-Thought (ToT) Prompting</h3><p><a href="https://arxiv.org/abs/2305.08291">Tree-of-thought (ToT)</a> framework involves exploring potential solutions in a manner akin to navigating a tree structure of thoughts, similar to human problem-solving. This approach enables the possibility of retracing steps when needed, mirroring the way humans may reassess and adjust their thinking during the problem-solving process. In essence, ToT aims to replicate the adaptive and iterative nature of human reasoning through trial and error.</p><p>Based on the ToT framework, <a href="https://github.com/dave1010/tree-of-thought-prompting">Dave Hulbert</a> proposed the tree-of-thought prompting. This technique employs a straightforward single-prompt approach, asking the model to assess intermediate steps.</p><h4>Prompt:</h4><pre>Identify and behave as three different experts that are appropriate to answering this question.<br>All experts will write down the step and their thinking about the step, then share it with the group.<br>Then, all experts will go on to the next step, etc.<br>At each step all experts will score their peers response between 1 and 5, 1 meaning it is highly unlikely, and 5 meaning it is highly likely.<br>If any expert is judged to be wrong at any point then they leave.<br>After all experts have provided their analysis, you then analyze all 3 analyses and provide either the consensus solution or your best guess solution.<br><br>Following is the question:<br>Q: {{ question }}<br>A:</pre><h4>Output:</h4><pre><br>Expert 1: Math Expert<br>Step 1: Calculate the total number of cans of milk purchased by Mark.<br>Mark bought 50 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 2: Calculate the number of cans of milk purchased by Jennifer before meeting Mark.<br>Jennifer purchased 40 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 3: Calculate the number of additional cans of milk purchased by Jennifer for every 5 cans Mark bought.<br>For every 5 cans Mark bought, Jennifer bought 6 additional cans.<br>Score: 5 (highly likely)<br><br>Step 4: Calculate the total number of cans of milk purchased by Jennifer.<br>Jennifer bought 40 + (6/5)*50 = 40 + 60 = 100 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 5: Conclusion<br>Jennifer brought home 100 cans of milk from the store.<br>Score: 5 (highly likely)<br><br>Expert 2: Retail Expert<br>Step 1: Determine the average number of cans of milk purchased by customers at the store.<br>Based on previous sales data, the average number of cans of milk purchased by customers is 10.<br>Score: 4 (likely)<br><br>Step 2: Calculate the total number of cans of milk purchased by Mark.<br>Mark bought 50 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 3: Calculate the number of cans of milk purchased by Jennifer before meeting Mark.<br>Jennifer purchased 40 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 4: Calculate the total number of cans of milk purchased by Jennifer.<br>Jennifer bought 40 + (6/5)*50 = 40 + 60 = 100 cans of milk.<br>Score: 5 (highly likely)<br><br>Step 5: Conclusion<br>Jennifer brought home 100 cans of milk from the store.<br>Score: 5 (highly likely)<br><br>Expert 3: Psychology Expert<br>Step 1: Analyze Jennifer&#39;s behavior and decision-making process.<br>Jennifer may have purchased 40 cans of milk based on her own needs and preferences.<br>Score: 4 (likely)<br><br>Step 2: Analyze Mark&#39;s behavior and decision-making process.<br>Mark may have purchased 50 cans of milk based on his own needs and preferences.<br>Score: 4 (likely)<br><br>Step 3: Consider the influence of social norms and peer pressure.<br>Jennifer may have felt pressured to buy more cans of milk after seeing Mark&#39;s purchase.<br>Score: 3 (somewhat likely)<br><br>Step 4: Analyze the impact of Jennifer&#39;s decision to buy additional cans for every 5 cans Mark bought.<br>Jennifer may have made this decision based on a desire to keep up with Mark or to appear generous.<br>Score: 3 (somewhat likely)<br><br>Step 5: Conclusion<br>Jennifer brought home 100 cans of milk from the store, possibly influenced by social norms and peer pressure.<br>Score: 3 (somewhat likely)<br><br>Consensus Solution:<br>Based on the analysis of all three experts, it is highly likely that Jennifer brought home 100 cans of milk from the store. The math expert&#39;s analysis provides a solid calculation, while the retail expert&#39;s analysis takes into account the average number of cans purchased by customers. The psychology expert&#39;s analysis adds a different perspective by considering the influence of social norms and peer pressure. Overall, the consensus solution is that Jennifer brought home 100 cans of milk from the store.</pre><p>The ToT technique employed in the above example yields an accurate solution. It’s worth mentioning that the ToT prompt used is taken from <a href="https://github.com/dave1010/tree-of-thought-prompting/blob/main/tree-of-thought-prompts.txt">Dave Hulbert’s ToT prompts</a>. However, one drawback of this technique is a significant increase in the prompt size.</p><p>Besides the engineering techniques mentioned above, a few additional methods can be adopted for solving arithmetic reasoning problems. However, it’s important to note that these techniques — <a href="https://arxiv.org/abs/2210.03493"><strong>Automatic Chain-of-Thought (Auto-CoT)</strong></a>, <a href="https://arxiv.org/abs/2203.11171"><strong>Self-Consistency</strong></a>, <a href="https://arxiv.org/abs/2303.09014"><strong>Automatic Reasoning and Tool-Use (ART)</strong></a>, and <a href="https://arxiv.org/pdf/2302.12246.pdf"><strong>Active Prompt</strong></a> - are beyond the scope of this article.</p><h3>Best Practices</h3><p>Models perform effectively when fine-tuned with well-designed prompts. <a href="https://www.promptingguide.ai/introduction/elements">Elvis Saravia</a> noted that a prompt may consist of four elements, though not all are necessary each time:</p><ol><li><strong>Instruction: </strong>This specifies a particular task or action you want the model to undertake.</li><li><strong>Context: </strong>External information or additional details that guide the model to generate more accurate responses.</li><li><strong>Input Data:</strong> The specific input or question for which we seek a response.</li><li><strong>Output Indicator:</strong> The expected type or format of the output.</li></ol><p>It is advisable to place the instructions at the beginning, separated from the rest of the prompt using designated separators like ‘#.’</p><p><a href="https://arxiv.org/pdf/2305.11430.pdf">Santu and Feng (2023)</a> introduced a comprehensive taxonomy, TELeR (Turn, Expression, Level of Details, Role), designed to enable more meaningful comparisons among multiple LLMs concerning their performance across various tasks. The prompt taxonomy categorizes prompt directives into six levels based on the level of detail provided. The sixth level can be effectively utilized to optimize the model’s performance based on the given prompt:</p><ol><li>Provide a brief description of the high-level goal.</li><li>Present a detailed bulleted list of sub-tasks.</li><li>Specify the criteria for evaluating the Language Model (LLM) output or include a few shot examples.</li><li>Include additional pertinent information obtained through retrieval-based techniques.</li><li>Request an explicit statement from the LLM, explaining its output.</li></ol><blockquote>In general, it’s advisable to be specific, offer clear details, continuously refine the prompt through iteration, properly format the prompt with clear separations, and mention do’s and not don’ts.</blockquote><p>Let’s revisit the prompt, considering the above-mentioned practices and applying the zero-shot prompting technique.</p><p><strong>Prompt:</strong></p><pre>### INSTRUCTION ###<br>You are required to answer Arithmetic Reasoning questions. Please follow the steps below as you go about solving the problem. <br><br>1. All problems should be solved in as many steps as required and each step should be numbered.<br>2. All calculations should be clear and simple to understand.<br>3. Provide an accurate final answer at the end of your reasoning in the following format: &#39;Answer is &#39;.<br><br>You&#39;ll be evaluated on:<br>- how easier are the calculations done to understand?<br>- how accurate is the answer?<br><br>### INPUT DATA ###<br>Q: {{ question }}<br>A:</pre><p><strong>Output:</strong></p><pre>1. Jennifer bought 40 cans of milk at the store.<br>2. Mark bought 50 cans of milk.<br>3. Jennifer bought 6 additional cans for every 5 cans Mark bought.<br>4. For every 5 cans Mark bought, Jennifer bought 6 additional cans.<br>5. Therefore, for 50 cans Mark bought, Jennifer bought (6/5)*50 = 60 additional cans.<br>6. Total cans of milk Jennifer bought = 40 + 60 = 100 cans.<br>Answer is 100 cans.</pre><p>Initially, the model failed to provide the correct solution using the zero-shot prompting technique. However, with the application of appropriate instructions and formatting, the same model successfully generates the correct response using the zero-shot prompting technique.</p><p><strong>Disclaimer:</strong> The following section provides information about Vellum, a developer platform useful for the rapid productionization of prompts. The mention of Vellum is for informational purposes only and does not constitute an endorsement or promotion. I have no affiliation with Vellum and receive no compensation for its inclusion.</p><h3>Vellum</h3><p>Identifying the appropriate prompt can pose a challenge. The process begins with a basic prompt, which is then incrementally refined through multiple iterations — a task that can be tough to oversee. Spreadsheets might be adequate for a handful of experiments, but they falter when faced with intricate issues that demand a multitude of iterations. So, the question arises — how can we efficiently monitor our prompts? What if our goal is to seamlessly share our prompt experiments with our team? Introducing Vellum - answer to these questions.</p><p><a href="https://www.vellum.ai/">Vellum</a> provides a suite of tools designed for prompt engineering, semantic search, version control, quantitative testing, and performance monitoring to help develop production-grade LLM applications. In the context of prompt engineering, it enables testing and evaluating a given prompt across all major LLMs available in the market. It also facilitates collaboration on prompts.</p><figure><img alt="A screenshot of the prompt engineering tool from Vellum.ai" src="https://cdn-images-1.medium.com/max/1024/1*lLqrjDKb9PD-ziZPKda_-Q.png" /><figcaption>Screenshot of Vellum sandbox (Screenshot by author)</figcaption></figure><p>The image above is a representative screenshot from the <a href="https://app.vellum.ai/prompt-sandboxes">Vellum sandbox</a>. Vellum enables easy switching between text and chat models and allows for effortless adjustment of model parameters. It also offers the advantage of latency tracking and quantitative assessment across four evaluation metrics: exact match, regex match, semantic similarity, and webhook.</p><p><a href="https://www.vellum.ai/">Vellum - Developer platform for LLM applications</a></p><h3>Summary</h3><p>This article begins by introducing prompts and then delves into prompt engineering for arithmetic reasoning problems. We explored various prompt engineering techniques, including zero-shot, few-shot, few-shot chain-of-thought, zero-shot chain-of-thought, program-aided language model, and tree-of-thought.</p><p>Later, we learned some best practices for crafting better prompts. In general, it’s recommended to be specific, provide clear details, refine the prompt continuously through iteration, format it properly with clear separations, and mention dos and not don’ts.</p><p>Finally, to address the challenge of tracking and evaluating prompts, as well as sharing them among team members, we investigated the Vellum tool.</p><p>If you like this article, make sure to follow me <a href="https://medium.com/@kaustubhbhavsar">here</a>. You can connect and reach out to me via <a href="http://www.linkedin.com/in/kaustubhbhavsar">LinkedIn</a> and <a href="https://twitter.com/bhavsarkaustubh">X</a> (formally, Twitter)<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c8bcd5bf0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/prompt-engineering-for-arithmetic-reasoning-problems-28c8bcd5bf0e">Prompt Engineering for Arithmetic Reasoning Problems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stemming: Porter Vs. Snowball Vs. Lancaster]]></title>
            <link>https://pub.towardsai.net/stemming-porter-vs-snowball-vs-lancaster-90b57f5639bc?source=rss-3c727e10b97f------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b57f5639bc</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lemmatization-vs-stemming]]></category>
            <category><![CDATA[lemmatization]]></category>
            <category><![CDATA[stemming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaustubh Bhavsar]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 16:01:19 GMT</pubDate>
            <atom:updated>2022-09-02T16:01:19.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how different popular Stemmers work and how Stemming differs from Lemmatization</h4><figure><img alt="Terms such as connections, connection, connected, and connecting have a common stem — connect." src="https://cdn-images-1.medium.com/max/1024/1*I8vq4bEnlNZdhQ_u0nUTng.png" /><figcaption>Source: Image from <a href="https://www.canva.com/">Canva</a>, edited freely available image by the author.</figcaption></figure><h3><strong>Introduction</strong></h3><p>A common application of Natural Language Processing (NLP) is Information Retrieval (IR). The IR system deals with obtaining related resources that are relevant to the search query from a large collection of those resources. Suppose we want to retrieve the resources for the word ‘connect’. For grammatical reasons, this same word will take on different forms like ‘connected’, ‘connection’, or ‘connecting’<em>.</em> All these words have the same meaning, but depending on the context in which they are used, they all vary in spelling or ending. It makes sense to use only one word to represent a vector of relevant words to search for a set of related resources that are relevant to the search query.</p><p>Why should we use a single word to represent a vector of relevant words?</p><ul><li>The use of a single word to represent a vector of related words will typically improve the performance of an IR system.</li><li>Reducing the number of words will also reduce the overall size and, thus the complexity of the total data in the system.</li></ul><h3><strong>What is Stemming?</strong></h3><p>Stemming is the process of identifying the root form, also called the base form of a word, by either replacing or removing word suffixes. Researcher J.B. Lovins, in her article, “<a href="http://people.scs.carleton.ca/~armyunis/projects/KAPI/Lovins.pdf">Development of a Stemming Algorithm</a>,” defines stemming as:</p><blockquote><strong><em>“A stemming algorithm is a computational procedure which reduces all words with the same root… to a common form, usually by stripping each word of its derivational and inflectional suffixes.”</em></strong></blockquote><p>For example, ‘boat’ is the root of the words: ‘boats’, ‘boater’, or ‘boating’.</p><p>In stem, the root of the word is called the <em>stem</em>.<em> </em>So, in our case, ‘boat’ is called a stem. To make our concept stronger, let’s understand another example; ‘connect’ is the stem for the following words: ‘connect’, ‘connecting’, ‘connection’, ‘connections’, or ‘connected’.</p><p>Prefix stripping is not widely used for stemming; however, it may be useful in certain subjects, such as chemistry.</p><h4><strong>Does it mean that Stemming will always result in a valid root word?</strong></h4><p>No. For example, if we process the word ‘transparent’<em> </em>through the porter stemmer, the root word that we get is ‘transpar<em>’</em>. Similarly, if we process the same word through the Lancaster stemmer, then the root word we get is ‘transp’. C.D. Paice, in “<a href="https://dl.acm.org/doi/abs/10.1145/101306.101310">Another Stemmer</a>,” mentions that it’s usually sufficient for IR systems to map the related words to the same stem; however, the root word doesn’t need to be valid.</p><blockquote><strong><em>“…the process is aimed at mapping for retrieval purposes, the stem need not be a linguistically correct lemma or root.”</em></strong></blockquote><p><strong>Errors in Stemming:</strong></p><ul><li>Over-Stemming: It occurs when two or more unrelated words result in the same stem.</li><li>Under-Stemming: It occurs when two or more related words result in different stems.</li></ul><p>Let’s go through the three most popular stemmers: Porter, Snowball, and Lancaster.</p><p><strong>Note</strong>: Detailed explanation of the working of algorithms is beyond the scope of this article.</p><h4><strong>Porter Stemmer</strong></h4><p>It is one of the most commonly used stemmers, developed by M.F. Porter in 1980. Porter’s stemmer consists of five different phases. These phases are applied sequentially. Within each phase, there are certain conventions for selecting rules. The entire porter algorithm is small and thus fast and simple. The drawback of this stemmer is that it supports only the English language, and the stem obtained may or may not be linguistically correct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97241c374356d463640969b36fc6e9a/href">https://medium.com/media/c97241c374356d463640969b36fc6e9a/href</a></iframe><p>The code snippet shown above will produce:<em> wa</em>,<em> found</em>,<em> mice</em>,<em> run</em>,<em> run</em>,<em> ran</em></p><p>Notice how the stem of ‘was’ is ‘wa’ according to porter algorithm which is linguistically invalid.</p><h4><strong>Snowball Stemmer</strong></h4><p>M.F. Porter also developed snowball stemmer. Snowball is a string processing language that is mainly developed to create stemming algorithms. It was created by Porter as an improvement over his previously created porter algorithm. It supports multiple languages, including English, Russian, Danish, French, Finnish, German, Italian, Hungarian, Portuguese, Norwegian, Swedish, and Spanish. The snowball stemmer presenting the English language stemmer is called <em>Porter2</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24123e176ed9e57bf062869b777a7855/href">https://medium.com/media/24123e176ed9e57bf062869b777a7855/href</a></iframe><p>The code snippet shown above will produce:<em> was</em>,<em> found</em>,<em> mice</em>,<em> run</em>,<em> run</em>,<em> ran</em></p><p>According to M.F. Porter, the stemming of stopwords like ‘being’ to ‘be<em>’</em> is useless because they don’t have any shared meaning, although there could be a grammatical connection between these two words. Snowball provides another parameter called <em>ignore_stopwords</em>, which is set to false by default. If it is set to true, then snowball will not perform the stemming of stopwords.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c9a175179c0869e305f19b8ae9d695/href">https://medium.com/media/d4c9a175179c0869e305f19b8ae9d695/href</a></iframe><p>The code snippet shown above will produce:<em> being</em></p><p>If <em>ignore_stopwords</em> is set to false, then the same code snippet will output: ‘be’<em>. </em>Try it for yourself.</p><h4><strong>Lancaster Stemmer</strong></h4><p>Lancaster stemmer is also called Paice or Husk stemmer. It was developed by C.D. Paice at Lancaster University in 1990. It uses an iterative approach, and this makes it the most aggressive algorithm among the three stemmers described in this article. Due to its iterative approach, it may lead to over-stemming, which may result in the linguistically incorrect roots. It is not as efficient as a porter or snowball stemmer. Also, it only supports the English language.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1a2234781fb79d216a7c8f810a3d98/href">https://medium.com/media/ce1a2234781fb79d216a7c8f810a3d98/href</a></iframe><p>The code snippet shown above will produce:<em> was</em>,<em> found</em>,<em> mic</em>,<em> run</em>,<em> run</em>,<em> ran</em></p><p>As Lancaster stemmer uses a more aggressive approach, the word ‘mice<em>’ </em>gets reduced to ‘mic<em>’</em>.</p><h3><strong>What is Lemmatization? And how does it differ from Stemming?</strong></h3><p>As we have seen so far, a stemming algorithm may or may not return a valid stem. This is not an issue for IR systems; however, can such invalid stems be used in language modeling, where linguistically correct forms are critical? We probably can’t. To overcome this drawback of stemming, we use lemmatization that returns us to a linguistically correct root. Lemmatization identifies inflected forms of a word and returns its linguistically correct root. In the book “<a href="https://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf">An Introduction to Informational Retrieval</a>,” they define lemmatization as:</p><blockquote><strong><em>“Lemmatization usually refers to doing things properly with the use of a vocabulary and morphological analysis of words, normally aiming to remove inflectional endings only and to return the base or dictionary form of a word…”</em></strong></blockquote><p>💡 Inflected form of a word has a changed spelling or ending.</p><p>The root of a word in lemmatization is called lemma. So, for words like ‘run’, ‘runs<em>’</em>, ‘running’, or ‘ran’; ‘run’ is the lemma. For words like ‘mice’, the lemma is ‘mouse<em>’</em>.</p><p>One of the most used lemmatizers is the <strong>WordNet</strong> which is provided by NLTK. To get the precise lemma, we must provide an appropriate part of speech (pos) tag. By default, every word is treated as a noun (n). We’ll pass verb (v) as the value to the pos parameter for all the words in the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eb0c2348b88bb1f4885a0934ca12fad/href">https://medium.com/media/1eb0c2348b88bb1f4885a0934ca12fad/href</a></iframe><p>The code snippet shown above will produce:<em> be</em>,<em> find</em>,<em> mice</em>,<em> run</em>,<em> run</em>,<em> run</em></p><p>Here, we observe that ‘was’, ‘found’, ‘run’, ‘running’, and ‘ran’ are verbs, so the output we get is precise. However, the output for ‘mice’ is ‘mice’. Why? This happened because the word ‘mice’ is a noun, so changing the pos tag to a noun will give us the output as a ‘mouse’. Try it for yourself.</p><h3><strong>Conclusion</strong></h3><p>We saw how stemming, and lemmatization differ, as well as how different stemmers work. There are many more different stemmers and lemmatizers available than the ones mentioned in this article. To summarize the entire article, let’s answer two questions.</p><p>First, should we choose stemming or lemmatization for the preprocessing step? It depends on the application that is being created. Stemming is fast compared to lemmatization. Also, stemming may or may not return a valid stem or root, whereas lemmatization will return a linguistically correct root. So, in applications where speed matters, like search and retrieval systems, stemming could be preferred; and in applications where valid root matters, like in language modeling, lemmatization could be preferred. Remember, the final decision on what should be used for the pre-processing step will always depend on the application being created and the application creator. Try experimenting with both and see how the results differ.</p><p>Secondly, is stemming used only in IR systems? No. Stemming could be used in applications that require the transformation of morphological forms of words to their roots. This means that stemming could be performed in text summarization or even in text categorization.</p><p>Let me know in the comment section if you’ve used or tried experimenting with these stemmers or lemmatizers and how beneficial they were for you!</p><blockquote><em>You can connect and reach out to me via </em><a href="http://www.linkedin.com/in/kaustubhbhavsar"><em>LinkedIn</em></a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b57f5639bc" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/stemming-porter-vs-snowball-vs-lancaster-90b57f5639bc">Stemming: Porter Vs. Snowball Vs. Lancaster</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>