<?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 Sohaib Ahmed Abbasi on Medium]]></title>
        <description><![CDATA[Stories by Sohaib Ahmed Abbasi on Medium]]></description>
        <link>https://medium.com/@SohaibAhmedAbbasi?source=rss-f3627a85be27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZTU6cfaLOh0J3DpCALyYNA.jpeg</url>
            <title>Stories by Sohaib Ahmed Abbasi on Medium</title>
            <link>https://medium.com/@SohaibAhmedAbbasi?source=rss-f3627a85be27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SohaibAhmedAbbasi/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[Low Agency Traps]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/low-agency-traps-7aece2412ab1?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aece2412ab1</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[procrastination]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 06:42:51 GMT</pubDate>
            <atom:updated>2025-04-25T06:43:29.726Z</atom:updated>
            <content:encoded><![CDATA[<p>In a recent episode of Chris Williamson’s Modern Wisdom Podcast, guest George Mack talked about the idea of <em>agency</em> — happening to life, rather than life happening to you. Among other ideas, they discussed the traps that keep us stuck in low-agency behavior, that stood out to me:</p><h4>1. The Vague Trap</h4><blockquote>“General ambition will give you anxiety. Specific ambition will give you direction.”</blockquote><p>“I want to do something big,” “I want to earn more money,” and “I want to become a content creator” all sound nice, but they’re too vague to act on. You can’t move confidently toward something if you don’t know exactly what it is. Vagueness is a source of anxiety. The solution is specificity — turning “I want to start writing” into “I’ll brainstorm some rough points for a blog post on agency traps tonight.” Clarity cuts through anxiety.</p><h4>2. The Midwit Trap</h4><p>This is the trap of overcomplication. It’s when people try to seem overly smart and create complex solutions instead of taking simple, obvious actions. Often, the simplest ideas are the ones that give you the most mileage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*8GRTT27mP88MOZmc.png" /></figure><h4>3. The Attachment Trap</h4><p>We often cling to what’s familiar, even when it’s suboptimal. This trap shows up in habits, routines, relationships — anything we continue doing because it feels safe.</p><p>Chris Will mentioned how some people hold on to familiar routines or identities, like watching the same YouTube channels or shows repeatedly. Even if they don’t particularly enjoy them or they don’t benefit them, they stick with it because familiarity feels safe. I’ve personally noticed this in myself — rewatching the same shows because trying new ones feels like effort and risk.</p><h4>4. The Rumination Trap</h4><p>This trap is all about staying in your head. You overthink, overanalyze, and mentally loop around problems — but never actually do anything about them.</p><blockquote>“A bias to action is the antidote to anxiety.”</blockquote><p>When you’re anxious, it’s often because your mind is full of untested hypotheticals. Action brings clarity, even if it means failing. We often spend so much time overthinking problems that we could have used to stress-test different paths, which would give us clarity. A useful tip here comes from Ali Abdaal, who suggests treating decisions as “experiments.” For example, if you’re thinking about quitting your day job to become a YouTuber, instead of overthinking whether it would work or what kind of videos to make, tell yourself you’re just going to start making and posting videos for six months. Consider it not as your ultimate final source of income, but as an experiment. And the cool thing about experiments is that they’re just tests: if it’s successful, you’ve made a new discovery; if it fails, you’ve gained new knowledge about what doesn’t work, which can help you in the future.</p><h4>5. The Overwhelm Trap</h4><p>You feel like there’s too much to do, so you do nothing. A way to escape this is to adopt the mindset of video game designers. Video games are great at keeping people hooked for hours and days, and a lot of it has to do with their level-based approach, where you start with something incredibly simple and slowly increase the difficulty. Imagine a game starting at level 56 — you’d give up and not play. But we often treat our tasks this way. For example, you might decide you want to learn how to make websites, but you keep procrastinating because it sounds impossible. The way out? Think about what level 1 looks like — the smallest first step. Then, based on that, think about what the next few levels might look like. Use these small levels as momentum and a source of motivation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aece2412ab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 2367:  Number of Arithmetic Triplets — Solution Explanation]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/leetcode-2367-number-of-arithmetic-triplets-solution-explanation-1cf1e6a98ab0?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cf1e6a98ab0</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 19:04:05 GMT</pubDate>
            <atom:updated>2025-04-23T19:04:05.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 2367: Number of Arithmetic Triplets — Solution Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ss-F38eeppa9HzAUAWjGKg.png" /></figure><p>In this problem, given an integer array nums and an integer diff, we have to count the number of triplets where the difference between consecutive elements is equal to diff. For the full problem statement, visit <a href="https://leetcode.com/problems/number-of-arithmetic-triplets/">https://leetcode.com/problems/number-of-arithmetic-triplets/</a>.</p><h3>Reframing The Problem</h3><p>The problem wants us to find 3 numbers (i, j , k) such that:</p><ul><li>i &lt; j &lt; k</li><li>nums[j] - nums[i] == diff, and</li><li>nums[k] - nums[j] == diff.</li></ul><p>We can rearrange the last 2 constraints to define nums[j] and nums[k] in terms of nums[i] as follows:</p><ul><li>nums[j] - nums[i] == diff➡️<strong>nums[j] = nums[i] + diff</strong></li><li>nums[k] - nums[j] == diff➡️nums[k] = nums[j] + diff</li></ul><p>Substituting nums[j] = nums[i] + diff in the above equation, we get:</p><ul><li>nums[k] = (nums[i] + diff) + diff ➡️<strong>nums[k] = nums[i] + (2 * diff)</strong></li></ul><h3>The Solution Explained</h3><p>So now we can just iterate over the array, considering one index (i) at a time, and look for indexes j and k such that i &lt; j &lt; k, index j’s value is nums[i] + diff and index k&#39;s value is nums[i] + (2 * diff). To speed up and simplify the looking up work, we can convert the nums array into a set (hashmap) data structure which has O(1) look up time complexity.</p><p>Additionally, because the numbers in original array are sorted, if for any index i we find nums[i] + diff and nums[i] + (2 * diff) in the set, we can be sure that they exist at indexes that satisfy the constraint of i &lt; j &lt; k since any value greater than current index number’s value would be at a higher index than current index <em>(nums[i] + diff and nums[i] + (2 * diff) will always be greater indexes than nums[i] since according to problem constraints 1 &lt;= diff &lt;= 50)</em>.</p><h3>Code:</h3><pre>class Solution:<br>    def arithmeticTriplets(self, nums: List[int], diff: int) -&gt; int:<br>        answer = 0  # to count number of arithemetic triplets<br>        lookup = set(nums)  # for faster searching<br>        <br>        for i, n in enumerate(nums):<br>            if ((n + diff) in lookup) and ((n + (2 * diff)) in lookup):<br>                answer += 1<br>        <br>        return answer</pre><h3>Time and Space Complexity Analysis</h3><p><em>(N = number of elements in array nums)</em></p><ul><li><strong>Time Complexity: O(N)</strong> — Converting nums to set is O(N), the for loop is O(N), and searching for elements in set (inside if condition) is O(1).</li><li><strong>Space Complexity: O(N) </strong>— Using one set which can contain maximum N elements</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cf1e6a98ab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do We Need Agents? — Agentic AI Series Part 1/4]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/why-do-we-need-agents-agentic-ai-series-part-1-4-837e47e6f05b?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/837e47e6f05b</guid>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 06:38:27 GMT</pubDate>
            <atom:updated>2024-07-29T06:38:27.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Do We Need Agents? — Agentic AI Series Part 1/4</h3><p>The notion of “agents” or “agentic AI” is a recent development in artificial intelligence that significantly enhances the power and robustness of Large Language Models (LLMs) applications.</p><p>To understand why the need for Agents arose, we first need to understand the differences between traditional programming and AI-driven programming. This comparison will highlight the shortcomings of current AI processes and explain how agents are designed to address these issues.</p><h3>Traditional Software Development</h3><p>Traditional software development, which was the norm before the recent rise of generative AI, relies on humans providing explicit instructions to computers to dictate how tasks should be executed. These instructions are rigid, following a predefined sequence of steps, often referred to as algorithms. The flow of a traditional program can be structured as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*wX5jjik0GQr4JtSu" /></figure><p>For instance, starting from point A, depending on various input values, the algorithm may move to point B, C, or D, as shown in the diagram. The algorithm follows a fixed set of paths, resulting in predictable and well-defined outcomes.</p><h3>AI-Driven Software Development</h3><p>AI-driven software development involves usage of generative AI models to perform tasks. Unlike traditional methods, these systems do not rely on explicit instructions or a fixed sequence of steps for every scenario. Instead, they operate based on a description of the task and leverage past data and patterns to transform inputs, make decisions, and generate predictions. An example of flow of an AI application is illustrated below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*fi_eApI7RpGVBMkT" /></figure><p>As the diagram shows, AI-driven systems have no fixed paths. Within a certain boundary, they can produce any output from the possible options, such as A, B, C, or D, as shown in the diagram.</p><h3>Differences Between Traditional &amp; AI-Driven Software Development</h3><p>AI-driven software development differs from traditional software development primarily in that its aspects — inputs, transformations, and outputs — are <strong>fuzzy, </strong>meaning flexible and not well-defined. While traditional programming is deterministic, with predictable results, AI-driven approaches yield probabilistic results, allowing for variability and adaptation.</p><p>In traditional programming, inputs and outputs are precisely defined by their quantity, size, and data types (e.g., text, integer, float). In contrast, AI-based software can handle input in various formats such as plain text, markdown, and tabular data, and produce outputs in varying formats such as bullet-point lists, JSON, and markdown.</p><p>Similarly, transformations in traditional programs typically involve mathematical computations, string operations, conditional logic, and iterative processes. AI software, however, performs transformations such as keywords extraction, ideas generation, and summarization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ebuel1S6r0CiUsRx" /></figure><h3>Limitations Of Traditional Programming</h3><p>Traditional programming faces some challenges that makes it less suitable for every scenario such as:</p><ul><li><strong>Need for Definitive Steps:</strong> Requires detailed and explicit instructions for every scenario.</li><li><strong>Limited Adaptability:</strong> Struggles with varying types of inputs and scenarios.</li><li><strong>Deep Problem Understanding:</strong> Necessitates a thorough understanding of the problem to define appropriate steps.</li></ul><p>These problems call for more flexible approaches, which AI-driven software development provides, by not requiring explicit step-by-step definitions.Instead, AI software leverages patterns and data to adapt and perform tasks more flexibly and efficiently.</p><h3>Limitations of AI-Driven Workflows</h3><p>AI-driven workflows themselves are not without limitations. They often produce results that may not meet expectations or be in the desired format. Issues often arise with ambiguous inputs or contexts that differ from what the model was trained on.</p><p>While the probabilistic nature of AI allows for flexibility and adaptation — enabling a single LLM model to perform a range of tasks such as content summarization, code writing, brainstorming, and teaching — this same variability can lead to unpredictable results.</p><p>To obtain the desired output from AI software like ChatGPT, iterative prompting is often required. For instance, if you ask the AI to “write briefly about the history of Pakistan,” it may initially provide a detailed essay. You might then prompt it to summarize the information into bullet points, but the result could still be too lengthy for your liking. This iterative process continues until you achieve the desired result. This method demands human intervention and ongoing adjustments, which is not ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*FeOEEzdgUfcxs1k3" /></figure><p>This approach requires human intervention and presence, but ideally, we would want as little human involvement as possible in an AI-based system — here’s where agents come in.</p><h3>Role Of AI Agents</h3><p>To address these challenges, AI agents are introduced. Simply put, AI agents replace the human in the iterative prompting cycle with an autonomous reasoning system. This system continuously works to refine the output until it meets the desired criteria. An AI agent takes an input, processes it through the LLM, evaluates the output, and if it’s not satisfactory, repeats the process until the output aligns with the requirements. This approach minimizes the need for human intervention, making the AI-based system more efficient and effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*EO0TCeSIVpPoeNXzjbta4Q.png" /></figure><h3>Why Use Agents?</h3><p>AI agents enhance traditional AI-based software by addressing issues such as unpredictability, unreliability, fuzziness, and the need for iterative adjustments, while also reducing human involvement. They offer the following key advantages:</p><ol><li><strong>Predictability: </strong>Agents produce results that are more consistent and aligned with the desired outcomes.</li><li><strong>Reflection: </strong>Agents can evaluate and adjust their results as needed to improve performance.</li><li><strong>Collaboration: </strong>Agentic systems can involve multiple agents with distinct roles working together to achieve better results.</li></ol><p>The next part of this Agentic AI series of articles will dive into the inner working of agents and what makes them tick.</p><h3>Acknowledgements:</h3><p>Most of the knowledge and content in this article is derived from the “Multi-AI Agent Systems with CrewAI” course offered by deeplearning.ai. For more information, visit: <a href="https://learn.deeplearning.ai/courses/multi-ai-agent-systems-with-crewai/">https://learn.deeplearning.ai/courses/multi-ai-agent-systems-with-crewai/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=837e47e6f05b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graph RAG — An Overview]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/graph-rag-e383fe6f7e9f?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/e383fe6f7e9f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 18:19:46 GMT</pubDate>
            <atom:updated>2024-07-11T18:36:59.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>Graph RAG — An Overview</h3><p>Retrieval Augmented Generation (RAG) is a key technique in enabling Large Language Model (LLM) applications to operate on private data, i.e. information not present in their training datasets, such as events occurring after the model’s training or niche information that isn’t widely available. While RAG does significantly improve responses of LLMs for specific tasks, it has some limitations.</p><p><strong>Graph RAG</strong>, a recent innovation by Microsoft, aims to <strong>improve upon traditional RAG and overcome its shortcomings</strong>. This article provides a high-level overview of how Graph RAG works and improves upon traditional RAG.</p><p><em>Note: This article is based on and references the research paper introducing Graph RAG, available for access </em><a href="https://arxiv.org/abs/2404.16130"><em>here</em></a><em>. The usage of content from the research paper complies with the terms of the Creative Commons Attribution 4.0 International License. Details of the license can be found </em><a href="https://creativecommons.org/licenses/by/4.0/"><em>here</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FP2QevlpxZKsaYKyU2SMw.png" /></figure><h3>Traditional RAG</h3><p>RAG addresses knowledge gaps of LLMs for specific tasks by adding relevant information from external sources to user queries.</p><p>It involves a pre-processing step of creating an <strong>index</strong> from the private dataset being used. This is done by breaking down the private dataset into <strong>fixed-size chunks</strong>, which are <strong>stored in a vector database</strong> along with their corresponding <strong>embeddings</strong> — basically a bunch of numbers that capture and represent the semantic meaning of the text.</p><p>Then at the time of <strong>querying</strong>, a certain amount of <strong>relevant chunks are retrieved </strong>from the index, those that are closely related to the query (determined by closeness of numerical embeddings of chunks to the embeddings of the query), and <strong>added to the query</strong>. This selective retrieval ensures that the prompt has relevant information while remaining within the context window size of the LLM being used.</p><p>All this helps in producing more relevant, accurate, and up-to-date responses.</p><h3>Where Traditional RAG Falls Short</h3><h4>Complex Relationships Across Documents</h4><p>RAG struggles to address queries for which relevant content spans multiple sections of a dataset that are interrelated but not directly related to the query. For example, if a query pertains to content on page 3 of a document, which references information on page 27, which in turn cites some content on page 11, RAG may only retrieve the content from page 3 since the content on page 11 and 27 are not directly related to the wording of the query. This incomplete data passed to the LLM could result in inadequate responses.</p><h4>Addressing Holistic Queries</h4><p>RAG also falls short in responding to queries that require a holistic view or global understanding of the dataset, such as “summarize the entire document” or “list the top 5 themes of the document”. Since RAG only fetches limited amounts of chunks from the original dataset, it cannot effectively address such comprehensive queries about the entire dataset.</p><h3>Graph RAG At A High Level</h3><p>Graph RAG mainly differs from RAG in the type of index used. Instead of a vector database of text chunks, it uses an <strong>LLM-generated graph-based index</strong>. This index involves multiple levels of semantic granularity across its hierarchy. Lower levels focus more on descriptions of individual entities present in the dataset and the relationships between them, whereas higher levels focus on more broader overviews of groups of related entities. This results in a potentially better semantic representation of the dataset.</p><p>Given a user query, initially partial responses are generated using the higher-level overviews. These partial responses are then used to formulate a final response.</p><h3>Steps Of Graph RAG pipeline</h3><p>The Graph RAG pipeline consists of 6 main steps, the first 5 of which are involved in index creation and the final step pertains to response generation. The steps are as follows:</p><h4>1. Chunking</h4><p>Divide the input texts into chunks.</p><h4>2. Extracting Graph Elements (Entities &amp; Relationships)</h4><p>From each chunk, identify and extract graph elements, i.e. nodes and edges, using a LLM. <strong>Nodes represent entities</strong> whereas <strong>edges represent relationships</strong> between those entities. For each element, a description is also generated.</p><p>As an example, here are some elements that could be derived from a dataset</p><ul><li><strong>Entities</strong>: <br> — Alex<br> — Bob<br> — X University<br> — Research paper Y<br>…</li><li><strong>Relations:</strong><br> — Alex <strong>studies in</strong> X University<br> — Bob <strong>teaches in</strong> X University<br> — Bob <strong>authored </strong>research paper Y<br> — Alex <strong>co-authored</strong> research paper Y<br>…</li></ul><h4>3. Summarizing Graph Elements</h4><p>Generate a summary of each graph element (entity nodes and relation edges). A summary of an element is basically a single block of text describing that element and its related elements.</p><p>Continuing on the previous example, here’s a potential summary for the entity ‘Alex’:</p><ul><li>Alex, a student of X University, co-authored research paper Y.</li></ul><h4>4. Grouping Into Communities</h4><p>Group together nodes of the graph that are strongly related to each other into communities (or clusters). This leads to a multi-hierarchical clustered graph.</p><h4>5. Summarizing Communities</h4><p>Perform another round of summarization, this time on the level of communities. These summaries are like “reports” according to the <a href="https://arxiv.org/abs/2404.16130">research paper,</a> and they give a high level overview of related concepts from the text. The main power of Graph RAG lies in these summaries, as underscored by the following excerpt from the <a href="https://arxiv.org/abs/2404.16130">research paper</a>, which highlights their usefulness even on their own :</p><blockquote>“These summaries are independently useful in their own right as a way to understand the global structure and semantics of the dataset, and may themselves be used to make sense of a corpus in the absence of a question. For example, a user may scan through community summaries at one level looking for general themes of interest, then follow links to the reports at the lower level that provide more details for each of the subtopics”</blockquote><h4>6. Generating Responses</h4><p>Given a user query, first generate community-level answers using chunks of multiple community-level summaries. Then, use those community-level answers to form a final global answer, which is returned to the user. Here’s a more detailed breakdown of the process:</p><ol><li>Shuffle community summaries around, to avoid all relevant content to be concentrated in a single context window.</li><li>Divide the summaries into chunks of size that can fit in the context window of the LLM being used along with the user query.</li><li>Generate community-level answers from each chunk in parallel, along with a score from 0–100 to indicate how well the answer addresses the user query.</li><li>Discard answers with score 0.</li><li>Sort the answers in descending order of scores.</li><li>Pick the top-ranked answers that collectively fit within the context window alongside the user query.</li><li>Generate final global answer using those top-ranked answers.</li></ol><p>Not only theoretically, but Graph RAG also outperforms traditional RAG in practice, at least as demonstrated by the few evaluations in the <a href="https://arxiv.org/abs/2404.16130">research paper</a>. However, due to frequent utilization of LLMs in both index generation and response generation, it is a highly resource-intensive technique.</p><h3>Further Reading And Resources</h3><ul><li><strong>Research paper:</strong> <a href="https://arxiv.org/abs/2404.16130">https://arxiv.org/abs/2404.16130</a></li><li><strong>Research blog</strong>: <a href="https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/">https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/</a></li><li><strong>Get-started guide</strong>: <a href="https://microsoft.github.io/graphrag/posts/get_started/">https://microsoft.github.io/graphrag/posts/get_started/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e383fe6f7e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Transactions]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/database-transactions-65bc953b0989?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bc953b0989</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql-database]]></category>
            <category><![CDATA[relational-databases]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 10:35:33 GMT</pubDate>
            <atom:updated>2024-01-30T10:35:33.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ou7brfRSlj9O0qrSG2Isg.png" /></figure><p>Transactions in relational databases are a way to make sets of operations reliable and predictable. They’re particularly useful for concurrent access, ensuring interactions by multiple processes don’t have conflicts or leave the database in inconsistent states. To ensure all that, transactions have 4 properties acronymized as <strong>“ACID”</strong> . They are:</p><ul><li><strong>A</strong>tomicity: All operations within a transaction are treated as a single unit of work that can’t be broken down. Either the entire unit of work (i.e. all the operations within the transaction) happens completely or it does not at all. To an outside observer all the parts of a transaction seem to happen all at once.</li><li><strong>C</strong>onsistency: The operations leave the database in a consistent state, that is they ensure no constraints are violated.</li><li><strong>I</strong>solation: Transactions take place independently without being interfered by other operations.</li><li><strong>D</strong>urability: If a transaction is complete, the changes are definitely persisted even in case of failures within the database such as power outages.</li></ul><p>To understand how transactions can be useful, lets go over an example.</p><h3>Example</h3><p>Consider a stock trading application with 3 tables:</p><h4><strong>Stocks</strong></h4><p><em>Represent stocks, their prices, and how many are available currently</em></p><pre>| name | price | quantity |<br>|------|-------|----------|<br>| ABC  | 5.00  | 3        |<br>| XYZ  | 3.00  | 11       |<br>| DEF  | 1.00  | 5        |</pre><h4>Users</h4><p><em>Represent users of the app and their cash balance.</em></p><pre>| username   | balance |<br>|------------|---------|<br>| Alex       | 10.00   |<br>| Bob        | 15.00   |</pre><h4>Activities</h4><p><em>Record buying and selling of stocks.</em></p><pre>| username | stock_name | quantity |<br>|----------|------------|----------|<br>| Alex     | ABC        | 20       |<br>| Alex     | ABC        | -30      |<br>| Bob      | XYZ        | 25       |</pre><p>Let’s consider a specific scenario. When a user purchases some stocks, for example Bob buys 2 stocks of ABC, the following SQL queries may be run:</p><pre>-- remove 2 stocks of ABC<br>UPDATE &quot;stocks&quot;<br>SET &quot;quantity&quot; = &quot;quantity&quot; - 2<br>WHERE &quot;name&quot; = &#39;ABC&#39;;<br><br>-- subtract balance of Bob by amount of 2 ABC stocks<br>UPDATE &quot;users&quot;<br>SET &quot;balance&quot; = &quot;balance&quot; - (<br>  SELECT &quot;price&quot; * 2<br>  FROM &quot;stocks&quot;<br>  WHERE &quot;name&quot; = &#39;ABC&#39;<br>)<br>WHERE &quot;username&quot; = &#39;Bob&#39;;<br><br>-- add stocks to Bob&#39;s holding by recording an activity<br>INSERT INTO &quot;activities&quot; (&quot;username&quot;, &quot;stock_name&quot;, &quot;quantity&quot;)<br>VALUES (&#39;Bob&#39;, &#39;ABC&#39;, 2);</pre><h4>Potential Pitfalls</h4><p>Well, there are a few things that can go wrong here. For instance, if Bob didn’t have the balance to cover the purchase, we would only realize this after subtracting 2 stocks of ABC from our system when the second set of queries attempts to deduct the balance, resulting in a constraint violation error since balance can’t be negative, and leaving the database in an inconsistent state.</p><p>One may think that to solve this issue we can perform the balance deduction part before subtracting stocks, but that could lead to the reverse issue, that is we could realize we don’t have enough amount of stocks required for the transaction after subtracting the user’s balance.</p><p>There could be an even more dangerous situation. Consider Bob decides to purchase 6 stocks of ABC, despite the total price of 6 stocks being 30and his current balance being 15, i.e. lower than what’s required, and the system having just 3 stocks available (as depicted by the data in the tables above). He does so cleverly by using 2 computers, simultaneously buying 3 stocks from each of them, as by setting up the purchases and hitting “buy” at the same time on both computers. Well, in this case there would be no error if the operations happen to run in the following order:</p><pre>| Time |          Computer 1            |          Computer 2             |<br>|------|--------------------------------|---------------------------------|<br>|  t1  | check stocks available? -&gt; yes |                -                |<br>|  t2  |                -               | check stock available? -&gt; yes   |<br>|  t3  |      subtract 3 stocks         |                -                |<br>|  t4  |                -               |      subtract 3 stocks          |<br>|  t5  |check balance sufficient? -&gt; yes|                -                |<br>|  t6  |                -               |check balance sufficient? -&gt; yes |<br>|  t7  |      subtract balance          |                -                |<br>|  t8  |                -               |      subtract balance           |<br>|  t9  |      record activity           |                -                |<br>| t10  |                -               |      record activity            |</pre><p>And what will end up happening is that effectively we would’ve given Bob 6 stocks of ABC for the price of 3 stocks when we actually have only 3 stocks available!</p><p>The above situation is what’s known as a <strong>race condition.</strong></p><h4>Race Condition</h4><p>A race condition is a situation where multiple entities access a share resource, causing unpredictable and potentially undesired outcome, due to the order of execution.</p><p>A shared resource is one that is accessible and modifiable by multiple entities. In our example, shared resources include quantity of stocks and user balances. Race conditions for these resources could lead to dangerous consequences, such as users ending up with inaccurate balances or obtaining more stocks than available.</p><p>Due to their isolated nature, transactions protect against race conditions by executing operations on shared data sequentially, effectively preventing the chance of inconsistencies. Sequential execution is achieved through <strong>locks</strong>.</p><h4>Locks</h4><p>Locks of different levels are used by transactions to ensure sequential execution and avoid race conditions.</p><ul><li><strong>Exclusive Lock:</strong> Obtained by an entity attempting to update or write to a shared resource. Ensures that only the entity with the exclusive lock has access to the resource and no other entity is allowed to obtain either an exclusive or a shared lock (i.e., write or read), for that resource</li><li><strong>Shared Lock</strong>: Obtained by an entity trying to read from a shared resource. Allows other entities to obtain a shared lock (i.e., read), but not an exclusive lock (i.e., update or write), for that resource.</li></ul><p>If no one is accessing the database, it is said to be in <strong>unlocked</strong> state.</p><h3>Transactions Syntax</h3><p>To encapsulate a set of queries within a transaction, all we have to do is wrap them with the BEGIN TRANSACTION; and COMMIT; statements For the stocks buying example discussed previously, it would be as follows:</p><pre>BEGIN TRANSACTION;<br><br>-- remove 2 stocks of ABC<br>UPDATE &quot;stocks&quot;<br>SET &quot;quantity&quot; = &quot;quantity&quot; - 2<br>WHERE &quot;name&quot; = &#39;ABC&#39;;<br><br>-- subtract balance of Bob by amount of 2 ABC stocks<br>UPDATE &quot;users&quot;<br>SET &quot;balance&quot; = &quot;balance&quot; - (<br>  SELECT &quot;price&quot; * 2<br>  FROM &quot;stocks&quot;<br>  WHERE &quot;name&quot; = &#39;ABC&#39;<br>)<br>WHERE &quot;username&quot; = &#39;Bob&#39;;<br><br>-- add stocks to Bob&#39;s holding by recording an activity<br>INSERT INTO &quot;activities&quot; (&quot;username&quot;, &quot;stock_name&quot;, &quot;quantity&quot;)<br>VALUES (&#39;Bob&#39;, &#39;ABC&#39;, 2);<br><br>COMMIT;</pre><p>BEGIN TRANSACTION; tells the DBMS that the following SQL statements are to be run as a transaction, adhering to the ACID principles. At the end, the COMMIT; statement finalizes the transaction and saves the changes made by the statements to the database. If any of the queries in the transaction throw an error, the whole transaction is rolled back and the changes aren’t reflected in the database. This approach ensures that the set of queries is run in isolation and sequentially, preventing adversary attacks like the one discussed previously.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bc953b0989" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning OpenAI’s GPT Models — A Beginners’ Guide]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/fine-tuning-openais-gpt-models-a-beginners-guide-2095464084b7?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/2095464084b7</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 14:26:51 GMT</pubDate>
            <atom:updated>2023-04-04T14:26:51.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fine-Tuning OpenAI’s GPT Models — A Beginners’ Guide</h3><p>AI tools are the talk of the town nowadays, and OpenAI’s tools are at the forefront of this rapidly emerging field. Tools like ChatGPT, DALL·E, the GPT-3 based GithubCopilot, and more are being used by almost everyone on a daily basis. OpenAI not only offers these tools but also allows users to fine-tune their GPT-3 based language models for various types of tasks. This article will provide an overview of OpenAI’s Fine-Tuning feature, along with a step-by-step tutorial to demonstrate how it can be used to make a model that can predict the rating score of a product review given the review text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t5IaNDCC2SiUYvRv.png" /></figure><h3>Introduction To Fine-Tuning</h3><p>OpenAI’s GPT language models have been trained on a lot of text which helps them perform any task that one may want them to do by generating the most plausible response to the user’s inputs and examples, which is referred to as “few-shot learning”. Fine-tuning enhances few-shot learning by training on a much larger number of task-specific examples than what can be accommodated in a single prompt, resulting in a more focused and specialized model. Fine-tuning has the following advantages:</p><ul><li>Higher quality results than prompt design</li><li>Ability to train on more examples than can fit in a prompt</li><li>Token (and hence cost) savings due to shorter prompts</li><li>Lower latency requests</li><li>Ability to incrementally fine-tune a model with additional data without starting from scratch.</li></ul><p>The base models davinci, curie, babbage, and ada can be fine-tuned, listed in order of most to least powerful.</p><h3>Fine-Tuning Steps</h3><p>The following steps summarize the process of fine-tuning an OpenAI model, which will be explained in detail in the next section:</p><ol><li>Prepare training data</li><li>Train a new fine-tuned model</li><li>Use the model</li></ol><h3>Detailed Fine-Tuning Guide</h3><p>To see how exactly fine-tuning can be done, let’s go through a detailed example. We’ll be making a model that takes a product review as input and predicts the corresponding rating score.</p><h4>Pre-requisites</h4><p>Before getting started we’ll need an OpenAI account and an OpenAI API key. If you don’t have an OpenAI account, go to <a href="https://platform.openai.com/">https://platform.openai.com/</a> and sign up for a new one. Next, go to <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>, click “Create a new secret key”, and save the generated key as an environment variable. This API key will be used for API calls to OpenAI. You’ll also need Python version 3, and OpenAI’s CLI tools which can be installed with the following command:</p><pre>pip install --upgrade openai</pre><h4>Prepare Training Data</h4><p>The data preparation step is the longest and most important one in making a fine-tuned model; the rest of the steps are fairly quick and straightforward.</p><p>For this tutorial, we’ll be using the “Amazon Product Reviews” dataset from Kaggle <em>(</em><a href="https://www.kaggle.com/datasets/arhamrumi/amazon-product-reviews"><em>source</em></a><em>), </em>which is a dataset of reviews of various products sold on Amazon. This is what part of the dataset looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Wil11MKnN7rFbCATFfzQ.png" /></figure><p><strong>Training data is how the model learns what you’d like to say</strong> and OpenAI requires it to be in a specific format: in the form of prompt-completion pairs, where prompts are inputs and completions are outputs. The training dataset file should also be in <a href="https://jsonlines.org/"><em>JSONL </em></a>format with each line being a prompt-completion pair, like so:</p><pre>{“prompt”: “&lt;prompt text&gt;”, “completion”: “&lt;ideal generated text&gt;”}<br>{“prompt”: “&lt;prompt text&gt;”, “completion”: “&lt;ideal generated text&gt;”}<br>…</pre><p>You can use <a href="https://platform.openai.com/docs/guides/fine-tuning/cli-data-preparation-tool">OpenAI’s CLI data preparation tool</a> to format your data into the required form. Further guidance for preparing your data can be found <a href="https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset">here</a>. It is recommended to have at least 200 training examples for good performance.</p><p>We only require 3 columns from the dataset: Summary (summary of the review), Text (actual text of the review), and Score (product rating). The dataset is quite large and will require a lot of time and cost to train, hence we can take a sample of random 5000 rows which should be good enough to train the model. We can do the aforementioned preprocessing and find some information related to the dataset with the following code:</p><pre># read dataset<br>data = pd.read_csv(&#39;Reviews.csv&#39;)<br><br># preprocess<br>data = data[[&#39;Summary&#39;, &#39;Text&#39;, &#39;Score&#39;]]  # extract the columns we need<br>data = data.dropna()  # drop rows with missing values<br>data = data.sample(n=5000, random_state=42)  # get random sample of 5000 rows<br>data = data.reset_index(drop=True)  # drop old index and replace with new sequential index<br><br>print(f&quot;Size of data: {data.shape[0]} rows, {data.shape[1]} columns&quot;)<br>print(f&quot;Review score types: {sorted(data[&#39;Score&#39;].unique())}&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*XFLXZRcrXoCj0VvkWFwAiA.png" /></figure><p>Next, let’s write our dataset to a JSONL file in the required prompt-completion pairs form. In our case the format would be:</p><p>{&quot;prompt&quot;: “Summary: &lt;Summary&gt;\nText: &lt;Text&gt;\n Rating:&quot;, &quot;completion&quot;: &quot; &lt;Score&gt;&quot;}</p><p>The following code creates our dataset in the desired format:</p><pre>import json<br><br>with open(&#39;reviews.jsonl&#39;, &#39;w&#39;) as f:<br>    for i in range(data.shape[0]):<br>        prompt = f&quot;Summary: {data[&#39;Summary&#39;][i]}\nText: {data[&#39;Text&#39;][i]}\nRating:&quot;<br>        completion = f&quot; {data[&#39;Score&#39;][i]}&quot;<br>        f.write(json.dumps({&quot;prompt&quot;: prompt, &quot;completion&quot;: completion}))<br>        f.write(&#39;\n&#39;)</pre><p>Note that we have added a separator “\nRating:” for each prompt and each completion starts with a whitespace, as per the <a href="https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset">data preparation guidelines.</a></p><p>The final thing to do to prepare the dataset is to run the <a href="https://platform.openai.com/docs/guides/fine-tuning/cli-data-preparation-tool">CLI data preparation tool</a>:</p><pre>openai tools fine_tunes.prepare_data -f &lt;formatted_data_file_path&gt;</pre><p>The tool gives some recommendations; we allow all of them except the one to split the dataset into training and validation sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSje_78r870V1KYJwC8Qrg.png" /></figure><h4>Train a new fine-tuned model</h4><p>To train a new fine-tuned model all that needs to be done is to start a fine-tuning job using OpenAI’s CLI using the following general syntax:</p><pre>openai api fine_tunes.create -t &lt;TRAIN_FILE_ID_OR_PATH&gt; -m &lt;BASE_MODEL&gt;</pre><p>where BASE_MODEL is one of the base models:davinci, curie, babbage, and ada. We will be using the least powerful but the cheapest and fastest model, ada. You can visit OpenAI’s <a href="https://openai.com/api/pricing/#faq-fine-tuning-pricing-calculation">pricing page</a> to find the rates for each model. Here’s the exact command that we need to run to train our model:</p><pre>openai api fine_tunes.create -t &quot;reviews_prepared.jsonl&quot; -m &quot;ada&quot;</pre><p>Running the command will create a fine-tune job and starts an events stream till the job is finished. Your job may be added to a queue of other jobs on OpenAI’s system. After the job is finished, the unique model name will be displayed which can be used to access the model.</p><h4>Use the model</h4><p>Now we can move to the most interesting part, using our fine-tuned OpenAI GPT model. You can use the model using OpenAI CLI, cURL, or Python. We’ll be using Python in this tutorial. The following code tests out the model’s response to a prompt.</p><pre>import openai<br>import os<br><br>openai.api_key = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>MODEL = &lt;your_model_name&gt;<br><br>test_prompt = &quot;Summary: Good display but poor performance.\<br>    \nText: The phone has a beautiful, bright display that is great for streaming videos and browsing the internet.\<br>    However, the phone&#39;s performance leaves a lot to be desired. Apps frequently crash and the phone can be slow to respond.\<br>    Overall, I would not recommend this phone.\nRating:&quot;<br><br>response = openai.Completion.create(<br>    model=MODEL,<br>    prompt=test_prompt,<br>    temperature=0.2,<br>    max_tokens=1<br>)<br><br>print(f&quot;Prediction: {response[&#39;choices&#39;][0][&#39;text&#39;].strip()}&quot;)<br>print(f&quot;Full response: \n{response}&quot;)</pre><p>First, we set the OpenAIAPI key and the name of the fine-tuned model. Next, we set a test prompt. After that, we get the response from the model for the test prompt using OpenAI’s <a href="https://platform.openai.com/docs/api-reference/completions">Completions API</a>; temperature (randomness) is set to a low value and max_tokens is set to 1 since we only need the rating value which will fit in 1 token. Finally, we print out the model’s response.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*Q9GI4TCq7qy3y_HA1dEXsA.png" /></figure><p>The predicted rating, 2, seems sensible given the nature of the review.</p><p>Next let’s test the model on some random reviews from the original dataset:</p><pre>data = pd.read_csv(&quot;Reviews.csv&quot;)<br><br>sample = data.sample(5)  # sample 5 random rows<br><br># test model on sample<br>correct = 0  # to count correct results<br>for i, row in sample.iterrows():<br>    prompt = f&quot;Summary: {data[&#39;Summary&#39;][i]}\nText: {data[&#39;Text&#39;][i]}\nRating:&quot;<br>    completion = f&quot;{data[&#39;Score&#39;][i]}&quot;.strip()<br><br>    print(f&quot;prompt: {prompt.encode(&#39;unicode_escape&#39;)}&quot;)<br>    print(f&quot;completion: {completion}&quot;)<br>    response = openai.Completion.create(<br>        model=MODEL,<br>        prompt=prompt,<br>        temperature=0.2,<br>        max_tokens=1,<br>    )<br>    prediction = response[&quot;choices&quot;][0][&quot;text&quot;].strip()<br>    print(f&quot;prediction: {prediction}&quot;)<br><br>    if prediction == completion:<br>        correct += 1<br>        <br>    print()<br><br>print(f&quot;accuracy: {correct/len(sample)}&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_HfiNysYQnPjSwB7DdeTQ.png" /></figure><p>The model guessed correctly 4 out 5 times.</p><h3>Conclusion</h3><p>So this was an introduction to OpenAI fine-tuning with the help of a practical demonstration. While the overall fine-tuning process is relatively straightforward, the most difficult and time-consuming part is clearly the data preparation stage which requires a significant amount of effort, as the training data must be both extensive and formatted according to requirements. Potential applications for fine-tuning are plentiful and readers are encouraged to use the knowledge gained from this article to try out a fine-tuning project of their own. To learn more visit the official OpenAI documentation on fine-tuning at <a href="https://platform.openai.com/docs/guides/fine-tuning">https://platform.openai.com/docs/guides/fine-tuning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2095464084b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Copilot Labs — Get Explanations and Translate Code]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/github-copilot-labs-get-explanations-and-translate-code-720983e20a5f?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/720983e20a5f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 16:26:53 GMT</pubDate>
            <atom:updated>2022-10-20T16:26:53.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>GitHub Copilot Labs — Get Explanations and Translate Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*xqUjF1sijiXlmFK5GNsBzg.png" /></figure><p>If you’re a programmer, you most probably know about or have heard of GitHub Copilot, the incredibly powerful AI autocomplete tool. But there are a couple of experimental features of Copilot that come with the “Github Copilot Labs” extension that you may not know about that are very fascinating and useful. Let’s have a quick look at them.</p><h4>How To Get It?</h4><p>GitHub Copilot Labs is separate from but dependent on the GitHub Copilot extension and is currently available only for VS Code. You can download the Copilot Labs extension through the VS Code Marketplace, just like you would download Github Copilot.</p><h3>The “Explain” Feature</h3><p>Is there a block of code that you just can’t fully grasp? Or some code in a language you don’t know but need to understand? The Explain feature of Copilot is just what you need in such situations. Using this feature you can get natural language (English) explanations of any code snippet! To do so, highlight the block of code you want the explanation for, choose one of the options for the type of explanation from the dropdown menu, and then click “Ask Copilot” under the “explain” tab to get the explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EJj5YSJYflcTUl7r77NiFw.gif" /></figure><h3>The “Language Translation” Feature</h3><p>Ever needed to translate your code from one coding language into another? You can do that very easily with the Language Translation feature of GitHub Copilot Labs. Just highlight the block of code you want to translate, select your desired language, and then click “Ask Copilot” under the “language translation” tab to get the translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OYbkUnhf-pU9Fq0BF5TcDw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=720983e20a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using AI To Solve A Mathematics Assignment]]></title>
            <link>https://medium.com/@SohaibAhmedAbbasi/using-ai-to-solve-a-mathematics-assignment-c06f5bc2cbe3?source=rss-f3627a85be27------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06f5bc2cbe3</guid>
            <category><![CDATA[numerical-methods]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[applied-ai]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Sohaib Ahmed Abbasi]]></dc:creator>
            <pubDate>Mon, 05 Sep 2022 11:52:12 GMT</pubDate>
            <atom:updated>2022-09-11T10:01:15.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In the sixth semester of my computer engineering undergraduate degree, I had a course called ‘Numerical Methods’, the main assignment of which I solved using an artificial intelligence technique that I had learned some time back. In this article, I’ll briefly go over the assignment problem and how I used the AI technique to solve it. The purpose of this article isn’t to dive deep into the details of the assignment or the AI algorithm, rather it is to show that one can use pre-existing knowledge to solve new problems.</p><h3>The Assignment Problem</h3><p>The assignment revolved around the <strong>Four Stage Runge-Kutta (R.K-4) method</strong> which is a numerical method to find solutions to differential equations.</p><blockquote><strong>About numerical methods:</strong> A numerical method is a mathematical technique that is used to find approximate solution of a solution that is either not possible to solve or too computationally expensive to solve using analytical (normal, traditional) mathematical techniques. The solution of numerical methods usually aren’t completely accurate and thus have some error.</blockquote><blockquote><strong>The goal of the assignment was to find out the best coefficients for the general formulas of the R.K-4 method such that the error in the solution is minimized.</strong></blockquote><p>The general iterative formula for solving differential equations using R.K-4 method is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*6SITc8Vds9JyXdHyaWCvtQ.png" /></figure><p>where ki is obtained from the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*9rjPbSKyqgHsiVDNxUl8cQ.png" /></figure><p>So basically we had to find the best possible values for the coefficients ci, Θi (theta i), and wi, i.e. values that minimize error in the final solution. The assignment required some logical method of finding out optimal coefficients.</p><p>You can check out the assignment document <a href="https://pdfhost.io/v/9.BsAe0Zt_NM_Assignment_CIS">here</a> if you’re interested in knowing more about the assignment.</p><h3>Intuition behind using AI</h3><p>This problem is basically an ‘optimization’ problem. Optimization involves choosing the best option from a set of possible options, or in a more mathematical/technical way, finding out optimal inputs — inputs that maximize or minimize certain criteria. Here the values for coefficients can be thought of as inputs whereas the error of the solution can be considered as the value to be optimized (minimized). The error of solution by any coefficients can be found by comparing the solution of the differential equation found by using some analytical technique to the solution found by the R.K-4 method with the chosen coefficients. Optimization is a subfield of Artificial Intelligence and there are many algorithms and techniques in AI for optimization, hence I decided to go with AI to solve this assignment.</p><h3>Hill Climbing — The AI Algorithm Used</h3><p><strong>Hill climbing</strong> is an AI optimization algorithm from the family of <strong>local search algorithms</strong> which is a method for solving computationally hard optimization problems. Local search algorithms move from one possible solution of a problem to another in order to optimize a certain criterion. In local search algorithms we have the following terminologies:</p><ul><li>An<strong> objective or cost function:</strong> An objective function is a function used to maximize the value of the solution and a cost function is used to minimize the value of the solution.</li><li><strong>State:</strong> A certain configuration of the problem. Each state has a value equal to the value of the objective or cost function at that state.</li><li><strong>Current state:</strong> A state that’s being currently considered by the algorithm.</li><li><strong>Neighbor state: </strong>A state that can be reached by changing something in the current state.</li></ul><p>In Hill Climbing, we start at a random state. Then we consider neighbor states and move to the best neighbor. We keep doing this till we reach some state which has no better neighbors.</p><h4>Hill Climbing With Random Restart</h4><p>There is one issue with the hill climbing approach discussed above, which you may have noticed, that it may not necessarily find the optimal solution. This is because the algorithm stops when it is at a state which has no better neighbors. No better neighboring states does not necessarily mean that there will not be better states somewhere else. That is, the hill climbing algorithm may stop at a point that’s locally optimal but not globally optimal.</p><blockquote>A <strong><em>local</em> minimum </strong>is a state that has a lower value than its <em>neighboring states</em>. A <strong><em>global</em> minimum</strong> is a state that has the lowest value of <em>all states</em> in the state-space.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m49CDwpWpWcF-DUP1Sk7Xg.png" /><figcaption>Local VS Global Minimas</figcaption></figure><p>Whether the algorithm reaches and stops at a local or global minima depends on the starting state. There are many variations to the vanilla hill climbing algorithm to ensure that the algorithm reaches the globally optimal state. One such variation is <strong>random-restart</strong>, where the algorithm is run multiple times with different start states and the best result of all the algorithm runs is selected. Performing hill climbing with random-restart increases the probability of reaching a globally optimal state or at least getting a better result than running hill climbing once, hence the random-restart variant of hill climbing was chosen for this assignment.</p><h3>Applying Hill Climbing (With Random-Restart) To The Given Problem</h3><ul><li><strong>Cost function</strong>: The cost function to be minimized is the root mean squared error between actual answers of the differential equation in given domain compared to answers generated by rk4 using our modified coefficients.</li><li><strong>State</strong>: Set of inputs (coefficients) to the rk4 method.</li><li><strong>Neighbor state:</strong> Set of inputs created by changing input coefficients of a state (at least 1, maximum all) using some logic.</li></ul><p>Probably the most challenging part of framing the problem according to hill climbing’s requirement was how to find neighbor states, as the values of coefficients had to be varied using some logic; they couldn’t just be assigned any values. For example, the values of the coefficients c1, c2, c3, and c4 had to be such that their sum is equal to 1.</p><p>So to sum it up here’s what I did to modify the coefficients:</p><pre>&gt; Run hill climb a certain number of times (eg 20). For each attempt of hill climb:</pre><pre>    - Start with a random initial state (random coefficients).</pre><pre>    - Set current state = initial state.</pre><pre>    - Repeat the following:</pre><pre>    - Find all neighbors of current state</pre><pre>    - Select best neighbors(lowest value of cost function).</pre><pre>   - If the value of cost function of the best neighbor<br>     is better than value of current state: <br>         Set current state = best neighbor</pre><pre>   - Otherwise:<br>         Stop hill climbing and return current state</pre><pre>   - Store the result of current hill climb attempt.</pre><pre>&gt; Return the result of the hill climb attempt which gave lowest value of cost function. (i.e combination of best coefficients)</pre><h3>Acknowledgments</h3><p>Most of my knowledge of the AI algorithm and some of the inspiration for the content of this article came from CS50 AI, a free online introduction to Artificial intelligence course by Harvard. More specifically, lecture 3 of the course went over the topic of optimization in AI.</p><ul><li>Notes on CS50 AI lecture 3 Optimization — <a href="https://cs50.harvard.edu/ai/2020/notes/3/">https://cs50.harvard.edu/ai/2020/notes/3/</a></li><li>CS50 AI website: <a href="https://cs50.harvard.edu/ai/2020/">https://cs50.harvard.edu/ai/2020/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c06f5bc2cbe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>