<?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 Abhijith S Babu on Medium]]></title>
        <description><![CDATA[Stories by Abhijith S Babu on Medium]]></description>
        <link>https://medium.com/@abhijithsbabu183?source=rss-7ff9f333ad49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W5-Y0xKC-YxNciTh4qlbGQ.png</url>
            <title>Stories by Abhijith S Babu on Medium</title>
            <link>https://medium.com/@abhijithsbabu183?source=rss-7ff9f333ad49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:06:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhijithsbabu183/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[AI Seems to do Everything Impossible. So Where Are We in Time Travel?]]></title>
            <link>https://pub.towardsai.net/ai-seems-to-do-everything-impossible-so-where-are-we-in-time-travel-fa740bdb8349?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa740bdb8349</guid>
            <category><![CDATA[einstein]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[general-relativity]]></category>
            <category><![CDATA[time-travel]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 23:59:00 GMT</pubDate>
            <atom:updated>2026-09-23T07:23:39.259Z</atom:updated>
            <content:encoded><![CDATA[<p>Every few days, we hear about an AI system discovering a new material, solving a mathematical problem, or finding a scientific pattern humans had missed. At the same time, physics has never completely killed the idea of time travel. Einstein’s equations contain strange solutions involving wormholes and closed timelike curves, while quantum mechanics keeps challenging our everyday intuition about cause and effect. So it is tempting to combine the two trends and ask a very 2026 question:</p><blockquote><strong>Could AI help us build a time machine?</strong></blockquote><p>The short answer is that AI may become extremely useful in the search for new physics involving time, gravity and causality. But we are nowhere close to engineering the kind of time travel shown in movies. The biggest obstacle is not simply that the equations are too difficult for humans. We do not yet know whether nature permits the required physical conditions at all.</p><p>Still, the state of the art is much more interesting than a simple “no.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAH-BBUcwx55DwyWegeUTQ.png" /></figure><h4>Time travel already exists… in one direction</h4><p>Before discussing wormholes, there is one misconception worth clearing up. Traveling into the future faster than somebody else is already allowed by established physics.</p><p>Special relativity tells us that a clock moving very quickly relative to another clock accumulates less elapsed time. General relativity adds another effect: clocks in stronger gravitational fields run more slowly. (Who hasn’t seen interstellar movie, right?)</p><p>These are measurable engineering effects, not philosophical ideas. Modern atomic clocks have measured gravitational time dilation across millimeter-scale height differences, and GPS requires relativistic corrections to remain accurate. If I could travel sufficiently close to the speed of light and later return to Earth, less time would have passed for me than for the people who stayed behind. In that limited sense, I would have traveled into their future.</p><p>The problem is scale. Accelerating a human-scale spacecraft to relativistic speed requires extraordinary energy. AI might optimize propulsion, trajectories and materials, but it cannot negotiate with the speed of light.</p><h4>Going backward is where physics gets strange</h4><p>Travel into the past is a completely different problem. General relativity describes gravity as the geometry of spacetime. Surprisingly, some mathematically valid spacetime geometries contain what physicists call <strong>closed timelike curves</strong>, or CTCs.</p><p>Roughly speaking, a CTC is a path that always moves locally forward through time but eventually returns to an earlier event. These are not just science-fiction inventions. CTCs arise in serious solutions of Einstein’s equations, including Gödel-type universes, idealized rotating spacetimes, wormhole constructions and some warp-drive geometries.</p><p>And research on them is still active.</p><p>In 2025, Achintya Sajeendran and Timothy Ralph published a <em>Physical Review D</em> paper constructing a controlled warp-drive spacetime in which a freely falling particle could follow a closed timelike curve and return to flat spacetime. Importantly, the authors explicitly noted the questionable physical realizability of the metric. In other words, the mathematics provides a time-machine-like geometry. It does not tell us how to build one.</p><p>Another 2025 <em>Physical Review D</em> study showed how a nonsingular wormhole spacetime containing CTCs could be constructed through a form of topological surgery. But the resulting spacetime violated the standard energy conditions.</p><p>That somewhat innocent-sounding statement hides one of the biggest problems in the entire subject. Many wormhole or time-machine proposals depend on exotic distributions of energy that we do not know how to create or sustain on useful scales.</p><p>There is also Stephen Hawking’s famous <strong>chronology protection conjecture</strong>: perhaps quantum effects prevent time machines from forming in the first place. The question remains unsettled. Work published in 2026 is still examining whether instabilities around chronology horizons could provide such a protection mechanism.</p><p>Then came a particularly interesting result in June 2026. Kaiyuan Ji, Seth Lloyd and Mark Wilde published a <em>Physical Review Letters</em> paper studying how much information could theoretically be sent backward through a noisy, postselected closed-timelike-curve channel. They derived information-theoretic limits for these hypothetical retrocausal channels.</p><p>That sounds spectacular, but the distinction is crucial. They did <strong>not</strong> send information into the past.</p><p>They studied what communication theory would look like <em>if such a channel existed</em>. That gap between <strong>“mathematically describable”</strong> and <strong>“physically constructible”</strong> is basically the entire time-travel problem.</p><h4>So where does AI enter?</h4><p>This is where the question becomes genuinely interesting to me as someone coming from computer science and AI. AI does not need to magically invent a time machine to change this field. Its immediate value is as a <strong>search and modeling engine</strong>.</p><p>Einstein’s field equations are nonlinear tensor differential equations, and interesting spacetime geometries occupy an enormous mathematical search space. Traditionally, physicists make simplifying assumptions, choose a form for the spacetime metric, solve the equations and then test whether the solution has sensible physical properties. AI gives us another possibility: searching and representing much larger spaces computationally.</p><p>We are already seeing early versions of this.</p><p>A 2025 project called <strong>Einstein Fields</strong> used neural representations to encode four-dimensional numerical-relativity simulations as implicit neural networks representing the spacetime metric. The researchers reported up to roughly a 4,000-fold reduction in storage on their test cases while preserving high numerical accuracy.</p><p>Another 2025 project, appropriately named <strong>AInstein</strong>, used machine learning to numerically solve Euclidean vacuum Einstein equations with a cosmological constant without making the usual symmetry assumptions.</p><p>Neither project is trying to construct a time machine. That is not really the important part. What matters is the direction of progress: neural methods are beginning to represent and solve complicated geometries that are expensive to explore using conventional numerical techniques.</p><p>AI is also getting better at discovering equations themselves.</p><p>Symbolic-regression systems search huge spaces of mathematical expressions and try to recover compact physical laws from data. A recent <em>Nature Computational Science</em> study on parallel symbolic enumeration demonstrated substantial improvements in equation-recovery accuracy and computational efficiency across more than 200 synthetic and experimental problem sets. Now imagine extending this idea to spacetime.</p><p>Instead of manually proposing one strange metric at a time, researchers could give an AI system a collection of constraints: Find a geometry that satisfies Einstein’s equations, avoids singularities, minimizes violations of energy conditions, remains stable under perturbations and exhibits a desired causal structure.</p><p>The AI could search candidate geometries, eliminate inconsistent solutions, run numerical simulations and perhaps even derive symbolic descriptions of promising candidates.</p><p>That would not prove that time travel is possible. But it could search the theoretical design space far faster than humans can today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hH1M2J9IfgHaXTtL" /><figcaption>Photo by <a href="https://unsplash.com/@hubblespacetelescope?utm_source=medium&amp;utm_medium=referral">NASA Hubble Space Telescope</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Didn’t a quantum computer already create a wormhole?</h4><p>This is one place where headlines have gotten somewhat ahead of the physics. In 2022, researchers used Google’s Sycamore quantum processor to study a quantum system whose behavior has a dual description resembling a traversable wormhole. The result, published in <em>Nature</em>, was important because it provided an experimental way to study ideas connecting quantum information and gravity.</p><p>But nobody created a physical tunnel through spacetime. Caltech explicitly clarified that the experiment did not produce a rupture in physical spacetime. Instead, the processor implemented a quantum system whose dynamics could be interpreted through the mathematics of a theoretical wormhole.</p><p>That distinction is important when discussing AI too.</p><p><em>Simulating a wormhole, finding an equation describing one and physically constructing one are three very different achievements.</em></p><p>The experiment is nevertheless fascinating because the deepest questions surrounding wormholes and time may require something we still do not possess: a complete, experimentally verified theory combining quantum mechanics with gravity. That is another area where AI might matter enormously.</p><h4>Could a superintelligent AI discover the missing trick?</h4><p>Possibly — <strong>if there is a trick to discover.</strong></p><p>I think discussions about AI and time travel often frame it as an engineering problem. Give a sufficiently intelligent model enough scientific literature, compute and laboratory access, and eventually it will design the machine.</p><p>But there are two very different possibilities.</p><p>In one universe, backward time travel is physically possible but hidden behind mathematics or engineering far beyond our current abilities.</p><p>In that case, advanced AI could be transformative. It might discover completely new spacetime geometries, quantum states, materials or control strategies that humans would never think to test.</p><p>But consider the other possibility.</p><p>Perhaps backward time travel is prohibited by a deeper law of nature. Maybe quantum gravity enforces chronology protection. Maybe physically realizable matter can never generate the required geometry. Perhaps causality itself emerges as an unavoidable consistency condition of the universe.</p><p>If that is true, no amount of intelligence changes the answer. An AI can find a solution that we overlooked, it cannot make an inconsistent universe consistent.</p><p>This reminds me somewhat of computation itself. Better algorithms can turn previously impractical problems into tractable ones, sometimes spectacularly so. But intelligence does not automatically erase fundamental limits. It helps us explore the space permitted by the rules.</p><p>So, are we close?</p><p>As of September 2026, <strong>no — not in an engineering sense</strong>.</p><p>We can measure relativistic time dilation with extraordinary precision.</p><p>We can write mathematically consistent models containing closed timelike curves.</p><p>We can simulate quantum systems related to wormhole physics.</p><p>We can calculate how information would behave inside hypothetical retrocausal channels.</p><p>And AI is rapidly becoming better at representing complicated physical systems, solving equations and discovering new mathematical relationships. What we cannot do is send matter, information or a person into their own past.</p><p>Still, I would not dismiss the question. Black holes were once strange mathematical consequences of general relativity. Today, we observe their environments and measure gravitational waves produced when black holes collide. That history should make us careful about declaring every exotic mathematical solution physically irrelevant.</p><p>But there is another lesson hidden in that history. Black holes did not become real because our computers became smarter. <em>They became real because nature contained them.</em><strong> </strong>That is probably the most important distinction when thinking about AI and time travel.</p><p>AI may eventually become the most powerful scientific search engine we have ever built. It could explore solutions to Einstein’s equations that humans would never think to try, uncover unexpected connections between quantum information and spacetime, and perhaps contribute to the theory that finally joins gravity with quantum mechanics.</p><p>If a route to time travel exists somewhere inside the laws of physics, AI may dramatically improve our chances of finding it.</p><p>But first, the universe has to have left the door open.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa740bdb8349" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/ai-seems-to-do-everything-impossible-so-where-are-we-in-time-travel-fa740bdb8349">AI Seems to do Everything Impossible. So Where Are We in Time Travel?</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>
        <item>
            <title><![CDATA[If Computation Theory Says Some Proofs Are Impossible, Why Can AI Prove Theorems?]]></title>
            <link>https://medium.com/@abhijithsbabu183/if-computation-theory-says-some-proofs-are-impossible-why-can-ai-prove-theorems-9e7097b41bd9?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7097b41bd9</guid>
            <category><![CDATA[navier-stoke]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 11:04:46 GMT</pubDate>
            <atom:updated>2026-09-14T11:04:46.325Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most fascinating things happening in AI right now is its growing ability to do mathematics. Not just arithmetic or solving textbook equations, but actually producing mathematical proofs.</p><p>In 2024, Google DeepMind’s AlphaProof and AlphaGeometry 2 solved four of the six problems from the International Mathematical Olympiad, reaching the level of a silver medalist. A year later, an advanced version of Gemini reached gold-medal-level performance and produced proofs directly from natural-language IMO problems within the competition time limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zDw6OXmZT9klnG_T" /></figure><p>Then, in September 2026, something even more striking happened. OpenAI announced that an experimental AI system had produced a proposed solution to the <strong>Navier–Stokes existence</strong> and smoothness problem, one of the seven<strong> Millennium Prize Problems. </strong>The system generated a long analytical proof arguing that a smooth three-dimensional fluid can develop a singularity in finite time, and the result was also formalized and checked in Lean. The claim is still being scrutinized by the mathematical community, so it is worth being careful about calling the problem completely settled. But even the possibility that an AI system contributed substantially to a solution of a problem that had resisted mathematicians for decades changes the scale of the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G__dR5NXx2hw-a_y_nUQfA.png" /></figure><p>At first, all of this seems to create a strange contradiction.</p><p>If you have read a Theory of Computation book, you probably remember about undecidability, Gödel’s incompleteness theorems, the Halting Problem, and all the things computers fundamentally cannot solve. Mathematics itself appears somewhere in this discussion: there is no general algorithm that can determine the truth of every mathematical statement.</p><p>So how are AI models suddenly writing proofs? And potentially contributing to the solution of problems that humans have struggled with for decades?</p><p>Did computers somehow become powerful enough to escape the limits established by theoretical computer science?</p><p>Not really.</p><p>The more interesting answer is that <strong>nothing went wrong with the theory. What went wrong was our interpretation of what the theory actually says.</strong></p><p>Consider a hypothetical program:</p><pre>PROVE(statement)</pre><p>Give it any mathematical statement imaginable, and the program always eventually returns either:</p><pre>TRUE — here is a proof</pre><p>or</p><pre>FALSE — here is a proof that it is false</pre><p>For sufficiently expressive mathematical systems, such a universal program cannot exist.</p><p>Results from Gödel, Church, Turing and others established fundamental limits around this idea. There are mathematical statements whose truth cannot be established within a given formal system, and there is no algorithm that can universally decide arbitrary mathematical questions of sufficient expressive power.</p><p>But notice what this does <strong>not</strong> say.</p><p>It does not say that computers cannot prove mathematical theorems.</p><p>That would be a much stronger claim.</p><p>Suppose I give a computer a theorem that actually has a finite proof in some formal system. In principle, the computer could simply start generating every possible sequence of symbols:</p><p><em>P1, P2, P3, …</em></p><p>For every candidate, it checks:</p><blockquote><em>Is this a valid proof of my theorem?</em></blockquote><p>Proof verification is mechanical. A formal system specifies exactly which logical steps are allowed.</p><p>Eventually, if a finite proof exists, our ridiculously inefficient search will encounter it.</p><p>The problem arises when no proof exists. The computer may continue searching forever. It has no universal way of knowing when to give up.</p><p>That distinction — between <strong>finding some proofs</strong> and <strong>having an algorithm that decides everything</strong> — is where much of the apparent paradox disappears.</p><h3>AI changes the search, not computability</h3><p>There is still an obvious problem with our brute-force proof generator.</p><p>It would be hopelessly slow.</p><p>Imagine proving a theorem by randomly pressing keys until a valid proof appears. Theoretically possible is very different from practically useful.</p><p>And this is where modern AI becomes interesting.</p><p>A language model has seen enormous amounts of mathematical structure. It learns statistical patterns about what mathematical reasoning tends to look like. If the current goal contains an inequality, certain transformations may be more promising than others. If we are dealing with divisibility, induction or modular arithmetic may be useful. If a proof reaches a particular intermediate expression, previous mathematical knowledge provides clues about what might come next.</p><p>Instead of exploring the entire proof space uniformly, AI can ask:</p><blockquote><em>Which proof step looks promising from here?</em></blockquote><p>That is a completely different problem from magically deciding mathematics.</p><p>In some ways, the AI is providing a <strong>learned heuristic for navigating an enormous search tree</strong>.</p><p>This idea becomes especially clear in systems such as AlphaProof. AlphaProof combined a language model with reinforcement learning and proof search. It generated possible proof steps in the formal language Lean, explored promising directions, and learned from proofs it successfully discovered.</p><p>And the recent Navier–Stokes work pushes this idea much further. OpenAI describes coordinating many AI agents that explored different mathematical approaches, shared promising intermediate results, used computational tools, and eventually converged on a candidate construction. The important part is that the system did not somehow ask an oracle for the answer. It searched, but searched in a vastly more informed way than brute force.</p><p>The theoretical limits have not moved at all.</p><p>We have simply become much better at searching inside them.</p><h3>There is another important ingredient: verification</h3><p>Large language models have an uncomfortable property when doing mathematics: they can sound extremely convincing while being completely wrong.</p><p>Formal theorem provers solve a large part of this problem.</p><p>Systems such as Lean represent mathematical statements and proofs in a precise formal language. Rather than trusting the language model because its reasoning <em>sounds</em> correct, the proof can be translated into a form where every logical step is mechanically checked.</p><p>This creates a powerful division of labor.</p><p>AI can be creative and unreliable:</p><blockquote><em>Maybe this lemma works.<br>Try induction here.<br>Rewrite this expression.<br>Perhaps construct this object.</em></blockquote><p>The theorem prover can be extremely conservative:</p><blockquote><em>Valid.<br>Invalid.<br>Invalid.<br>Valid.</em></blockquote><p>That combination is surprisingly powerful.</p><p>You do not necessarily need the AI generating proofs to be perfectly trustworthy if another system can mechanically verify its output.</p><p>The Navier–Stokes announcement is particularly interesting for this reason. OpenAI did not only release natural-language mathematical reasoning; it also reported a Lean formalization of the result. That distinction matters enormously. An LLM producing 160 pages of convincing mathematics is interesting. A machine-checkable formal proof is a different level of evidence altogether — even though mathematicians still need to examine whether the formalized theorem corresponds exactly to the claimed mathematical result and assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sup8nkCK0Wqjrd7OnLxwLg.png" /></figure><h3>So what about Gödel?</h3><p>Gödel’s incompleteness theorem is sometimes summarized far too dramatically as “mathematics cannot be solved by computers.”</p><p>That is not what it says.</p><p>Very roughly, any sufficiently expressive and consistent formal system will contain statements that cannot be proved or disproved <em>within that system</em>.</p><p>AI does not make those statements disappear.</p><p>If tomorrow we built a model one thousand times more capable than today’s best models, the fundamental result would remain. Making the searcher more intelligent does not change the mathematical properties of the search space.</p><p>An AI might discover extraordinary proofs that humans missed. It might invent useful lemmas, combine distant mathematical ideas, coordinate thousands of parallel attempts, or explore millions of candidate arguments.</p><p>It might even help resolve problems that mathematicians have stared at for a century.</p><p>But there will still be limits to what can be established inside any fixed sufficiently powerful formal framework.</p><p>That is a mathematical limitation, not a lack-of-compute limitation.</p><h3>And I think that is the more interesting story</h3><p>When I first encountered undecidability in Theory of Computation, it was tempting to interpret these results as a map marking areas computers could never enter.</p><p>But that is not quite the right picture.</p><p>They are closer to boundaries on what any <strong>universal procedure can guarantee</strong>.</p><p>Inside those boundaries lies an enormous space of problems that may still be solvable — and we may have underestimated how effectively machines could navigate it.</p><p>The Navier–Stokes development makes that distinction particularly vivid. A Millennium Prize Problem is exactly the kind of problem one might casually point to when talking about the limits of automated mathematics. Yet computability theory never said a machine could not find such a proof. It said there cannot be one algorithm that is guaranteed to correctly settle every possible mathematical question.</p><p>Those are very different statements.</p><p>Generative AI did not defeat Gödel or Turing. It did something less dramatic theoretically, but perhaps much more important practically: it became much better at guessing where to look.</p><p>For decades, we knew that a computer could mechanically verify a formal proof. What was difficult was finding the proof in the first place without searching an astronomical number of possibilities.</p><p>Now we are building systems that combine learned mathematical intuition, massive parallel search, reinforcement learning, computational tools and rigorous verification.</p><p>And perhaps that is the part worth paying attention to.</p><p>The great results of Theory of Computation tell us where the absolute limits are. They do <strong>not</strong> tell us how close ordinary mathematical problems are to those limits.</p><p>AI is beginning to explore the enormous territory in between.</p><p>So perhaps the surprising lesson from AI theorem proving is not that the old theory was wrong.</p><p>It is that <strong>“impossible in general” and “astonishingly capable in practice” can both be true at exactly the same time.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7097b41bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should programmers know what happens inside a computer?]]></title>
            <link>https://medium.com/@abhijithsbabu183/should-programmers-know-what-happens-inside-a-computer-ab1dc09bba1f?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1dc09bba1f</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 16:55:33 GMT</pubDate>
            <atom:updated>2025-04-13T16:55:33.353Z</atom:updated>
            <content:encoded><![CDATA[<p>Coding is a headache for many people until they get a hang of the art. (Obviously I am talking about the pre-chatGPT era). There comes a phase when coders learn the syntax and basic logic and gets confident only to get stumbled by time/space complexities. A good programmer masters these concepts and finally sets off to build fast running codes. But is that enough??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qdnOym-Ke-VIc4dl" /></figure><p>We were talking aboutr fast running code. But what does it mean? A programmer should know that your codes will be translated in multiple steps into machine instructions. A piece of code is considered fast if at the end the number of machine instructions to be executed is minimized.</p><p>A programmer is now working on a very time sensitive code that wants him to first initialize a 2D array (50*50) that has the value 0 at all positions.</p><p>This is how most people write the code</p><pre>// create an array A here<br><br>for (int i=0; i&lt;50; i++)<br>{<br>  for (int j=0; j&lt;50; j++)<br>  {<br>    A[i][j] = 0<br>  }<br>}</pre><p>Well, a smart programmer thought — “Why can’t I make it interesting?” (Whether this is interesting or not is debated until eternity). She made a small tweak in the above code.</p><pre>// create an array A here<br><br>for (int i=0; i&lt;50; i++)<br>{<br>  for (int j=0; j&lt;50; j++)<br>  {<br>    A[j][i] = 0<br>  }<br>}</pre><p>She just swapped i and j. What changed? There were 2500 values to initialize. All of them are initialized with the same value. The only thing that changed was the order in which they were initialized. And just as she expected, both the codes would run the same number of machine instructions and should obviously take the same time to execute.</p><p>The programmer had a tool that precisely calculates the time taken to run their codes. And She ran both the codes through the tool just for fun. (The legend says that some people agree its still interesting). But to her utter surprise, one of the code ran orders of magnitude faster than the other. (At this point, many people agreed that it is interesting)</p><p>But how did that happen? Was that a glitch in the tool?</p><p>Well this could actually happen because of something that happens inside our computers. Which of these codes work faster depends on how the arrays are stored inside the computer, which in turn depends upon many factors like compiler, OS etc. Anyways, story time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UUcHEtzidsRG-PXJ" /></figure><p>For a CPU to run something, all related data has to be stored in memory (In common words, the famous guy called RAM). Considering 2 bytes for one integer value, 2500 integers could take 5KB space in the RAM. That is nothing when you have a computer with 4–32 GB RAM (Spoiler alert — It takes 0.00001% of the RAM approximately).</p><p>Let us assume the array is stored row by row. Then the first code is likely to run faster. Now you might think the time differnence is because the time taken to reach different parts of the RAM is different. (Spoiler alert — Its wrong)</p><p>First of all. That time difference is negligible. And second of all, you cannot know where in the RAM each row is stored. (Ever heard of paging?)</p><p>So what is the actual reason??? Without further ado (the joke intended, comment it if you get it) lets look at the reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zDuPzVa9j2hA7ptH" /></figure><p>Your computer with 8 GB RAM is expected to run a lot of softwares at a time, which in total takes way more than 8 GB. So they don’t store the whole thing in the RAM. A big part of the data is stored in the storage (hard disk or SSD) and they are retrieved and bought to the memory when the CPU wants it. As mentioned before, the data are stored in pages. Now let us look at one (obviously scripted) case where our programmer’s code took much more amount of time than expected.</p><p>Seeing her very small code, the operating system allots one page of memory in the RAM. One page in this fancy system is 100 Bytes. So the moment she started initializing the array, the page contaning the first row (which takes exactly 100 bytes) is bought to the RAM. If she was initializing it row by row (like in the first code), the initialization of the first row could be done after which we send the page back to our storage and bring back the second page. In this way, we need to swap the pages only 50 times. But when she initialized it column by column, for each value the page had to be swapped which means a total of 2500 swaps. And a swap takes much more time than fetching data from the RAM, hence creating a huge time difference.</p><p>Too long didnt read? Well I dont have a shorter way of explaining :(</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*O0sqE7-O_TR-IFtw1Ft6IA.png" /></figure><p><em>The programmer from the future was utterly confused until she came across my article. Now she knows what is happening and can sleep in peace :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1dc09bba1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unblocking the blackbox: A quick peek into explainable AI]]></title>
            <link>https://medium.com/@abhijithsbabu183/unblocking-the-blackbox-a-quick-peek-into-explainable-ai-4979e9b04a65?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/4979e9b04a65</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[interpretation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 05:55:20 GMT</pubDate>
            <atom:updated>2024-08-23T05:55:20.010Z</atom:updated>
            <content:encoded><![CDATA[<p>AI is not new, it is already everywhere. From the deeply personal notifications in Zomato (A food delivery app in India) to the music playlist that connects with us accurately, many things around us are run by AI. In the ever-growing world, AI has taken over many more of our responsibilities, including self-driving cars, automated security systems, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pO_XiF_7ijG6YzbG" /><figcaption>Photo by <a href="https://unsplash.com/@leiadakrozjhen?utm_source=medium&amp;utm_medium=referral">Leiada Krozjhen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>All these are magic to the common man who is not much into computers or technology. They cannot understand how these systems work and might think only the tech people will know it. But coming to the tech people, the situation is different. Even an expert machine learning developer, capable of building such products might not understand them completely. That is right. Most of the complex AI products around us are black boxes. They give fascinating outputs and solve complex problems but no one knows how exactly they work.<br> <br>Let’s imagine a future where AI has achieved good results and is trusted by society in all areas. That could be the case in the near future. From administering the right medication according to a patient’s health conditions to limiting criminal activities, AI can do any job with close to 100% accuracy. That accuracy can be better than how well humans do these jobs. If such a capability is proven, society and the government will be willing to adopt AI in all its applications. Our friends Jansen and Lacey are living in such a society.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*j4jGiZ-DvM8E0Of6Qri2-A.png" /></figure><p>Jansen is a supervisor at the city hospital. A patient who had been in a coma after an injury just passed away due to an overuse of coagulant. The medication was administered by a machine-learning-based system that has successfully saved thousands of patients in the past. It is the first time such a mistake has happened. Jansen wasn’t too worried. Such a failure occurs very rarely in the system, so he thought it is still safe and such a mistake may not happen again. However, the technical lead of the hospital wanted to disagree.<br>“These machine learning systems are not actually random systems. Even though it is a black-box, there are predefined patterns and algorithms in the underlying model. In a similar environment and same set of inputs, the system will make the same mistake.”<br>“So what exactly caused the issue?”<br>“I don’t know. It was the decision of the model…”<br> <br>On the other side of the city, Lacey was rushing across the city to attend the ceremony where her sister would receive an award for developing a social metrics AI. This AI analyzes people’s daily activities and predicts their ethical and trustworthiness levels. Based on these predictions, individuals are either granted or denied access to various services in society. The government has adopted this technology due to its proven accuracy, which has significantly improved social life. Lacey’s sister is being honored for her groundbreaking invention.<br> <br>Lacey tried to book a taxi using her online taxi application, but the app unexpectedly closed. After multiple attempts, she decided to head to the subway station. However, she was denied entry after scanning her access card. Upon checking her social metrics app, she discovered that her score was very low, leading to her ban from various services. Lacey believed this was a bug, as it had never happened to anyone else before. Unfortunately, she was unable to prove it, as the output was from a black-box model. Disheartened, she returned home, feeling as though her life had been ruined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*C5hZDEjro17WmKfx5kNr1w.png" /></figure><p>The stories mentioned earlier might seem like they belong to a far-off future, but that future could be closer than we think. To tackle the issues these stories highlight, the best solution is to improve how well we can explain the decisions made by AI models. By making AI more understandable, we can better trust and use these technologies in our everyday lives.<br> <br><strong>When do we need explainability?</strong><br> <br>The need for explainability depends on the problem that is solved by the AI models. In some cases, explainability might be critical, while in others, explainability does not have an impact. There are cases where explainability can cause adverse effects too. We will come to that later.<br> <br>We can say that explainability is essential when the model affects important aspects of our lives, for example, medical AIs, AIs in finance, etc. Those that won’t have a serious impact might not care about explainability. A movie recommendation software that you made for your own use will not need explainability, but a product recommendation or advertising AI has an impact on the business and hence benefits from explainability.<br> <br>When a model can explain how it arrived at a decision, it becomes easier to identify and fix errors, ultimately improving its accuracy. Take, for example, a self-driving car that’s designed to recognize and maintain a safe distance from bicycles to prevent accidents. However, the car occasionally misses some bicycles, which could lead to dangerous situations. By applying explainability, it was discovered that the model recognizes bicycles by detecting two wheels, handlebars, and other typical features. But in some cases, bicycles with a rear carry-basket were missed because the basket obscured one of the wheels. With this insight, the model can be adjusted, enhancing its ability to detect all bicycles and ensuring greater safety.<br> <br>Explainability also plays a role in detecting and removing bias in AI models. If the data sent to the model is biased, it can give biased outputs. This can have serious impacts including discrimination towards certain classes of people. While training a model for predicting the trustability of people, the data was such that almost all of the untrustable people had blue eyes. The model learned it as a rule and every person with a blue eye was considered untrustable. If the model can explain that the eye color was the reason for the model’s prediction, then we can adjust the training such that it is not given importance. Because when did having blue eyes become a crime?<br> <br>Explainability is crucial in identifying and eliminating bias in AI models. When biased data is fed into a model, it can produce biased outcomes, leading to serious consequences like discrimination against certain groups. For example, imagine training a model to predict whether someone is trustworthy. If the data used for training showed that almost all untrustworthy people had blue eyes, the model might mistakenly learn that blue eyes are a sign of untrustworthiness. As a result, it could unfairly label every person with blue eyes as untrustworthy. However, if the model can explain that eye color influenced its prediction, we can correct the training process to ensure that eye color is not given undue importance. After all, when did having blue eyes ever become a reason for mistrust?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMaFLsyxg78zOfP_UJrGCQ.png" /></figure><p>If an AI model is highly explainable, why might that be a problem in some situations? The reason is that people could use this transparency to manipulate the model. This often occurs when the person using the model is not genuinely following its intended purpose. For example, imagine a company that implements an AI system to monitor whether remote workers are actually doing their jobs. If the model is explainable, an employee could figure out how the system detects inactivity. Suppose one of the key indicators is the frequency of pressing the enter key. With this knowledge, the employee could watch a movie during work hours and simply press the enter key every five minutes to avoid being flagged by the system. This is a clear case where too much explainability could be exploited.<br> <br>Explainability is key to building trust between users and AI systems. When a model can clearly explain how it makes decisions, users are more likely to trust its results because the process is transparent and easy to understand. It also helps developers find and fix mistakes or biases in the model. In short, explainable AI makes sure that these systems are both reliable and trustworthy, helping them work in a way that aligns with our values and ethics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4979e9b04a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolutionary Testing]]></title>
            <link>https://medium.com/@abhijithsbabu183/evolutionary-testing-75fa99c1fd74?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/75fa99c1fd74</guid>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[qa-testing]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Tue, 28 May 2024 11:13:51 GMT</pubDate>
            <atom:updated>2024-05-28T11:13:51.951Z</atom:updated>
            <content:encoded><![CDATA[<p>The expansive domain of search-based software engineering (SBSE) has given light to evolutionary algorithms, an advanced software testing technique that employs evolutionary algorithms to generate test cases. This approach utilizes sophisticated optimization techniques to address and resolve complex problems in software testing.</p><p>Unlike manual test case generation, which is prone to human error, the use of evolutionary algorithms introduces a level of intelligence that can explore a diverse range of inputs. This exploration helps uncover edge cases that may be overlooked by human testers. The adaptability and scalability of evolutionary testing have made it a valuable tool for various testing objectives, including unit testing, integration testing, and performance evaluations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtXuNY9FwI3OECZ3b4ATaA.png" /></figure><h4><strong>Evolutionary Algorithms</strong></h4><p>Evolutionary algorithms are the special classes of algorithms in computer science that are inspired by the concept of biological evolution. The living organisms evolved and became more capable and complex era after era. This was an inspiration for the evolutionary algorithms that can evolve a solution to make it better.</p><p>They operate by starting with a set of potential solutions, referred to as a population. This population undergoes a series of genetic operations such as crossover (recombination of solutions) and mutation (random alterations). After each iteration, the population is refined, allowing the better-performing individuals to advance to the next generation. The quality of each solution is evaluated using a fitness function. Through numerous iterations, this process produces a population of solutions that are optimal or near-optimal.</p><h4>What evolutionary algorithms have to do with testing?</h4><p>Evolutionary testing is a technique that employs metaheuristic search methods to generate test cases for software. When testing software, it’s important to consider that the code often contains if-statements, loops, recursion, and other structures that introduce non-linearity. This non-linearity increases the complexity of optimizing test case generation.</p><p>In such scenarios, traditional neighborhood search methods such as hill-climbing may not yield the expected output. This is because these methods are not well-suited to deal with the non-linear nature of the software code. As a result, evolutionary testing, which utilizes metaheuristic approaches, becomes a more effective method for generating test cases in such complex environments.</p><h3>Components of Evolutionary Algorithm</h3><h4>Population and generations</h4><p>To apply evolutionary algorithms in the generation of test cases, one begins by initializing a large and diverse set of potential test cases. This means creating a wide range of different test cases that cover various scenarios and conditions that the software might encounter during its operation.</p><p>Subsequently, a subset of these test cases is randomly selected to constitute an individual within the population. This process involves randomly choosing a group of test cases from the initial set to form an individual within the population of test cases. This helps ensure that a diverse range of characteristics and conditions are represented within the population.</p><p>This process creates a rich initial population, where each individual is essentially a composite of several test cases, embodying a unique combination of characteristics. By combining different test cases into individuals within the population, the initial population becomes diverse and representative of various scenarios and conditions that the software might face. This diversity is essential for the evolutionary algorithm to effectively explore and identify effective test cases for the software.</p><h4>Fitness function</h4><p>The selection of a fitness function plays a crucial role in determining how effectively the final output meets the specified problem requirements. In the context of software testing, different fitness functions are applied based on the specific objectives of the testing process. These objectives can vary widely, ranging from ensuring functional correctness to optimizing performance or enhancing security.<br> <br>One of the primary factors that influence the effectiveness, or “fitness,” of test cases is their code coverage. Code coverage refers to the extent to which the source code of a program is executed when a particular set of test cases is run. High code coverage implies that a significant portion of the codebase is tested, which in turn increases the likelihood of detecting defects and ensuring that the software behaves as expected under various conditions.<br> <br>In addition to this, mutation testing is another approach used to determine the fitness of the function.</p><blockquote>Mutation testing is an approach in which small intentional changes are made to the source code. It can be as small as altering an operator to change the flow of a block. Once the changes are made, the code is tested on the set of test cases. More failed test cases indicate that the test cases are effective. Hence, the fitness of the test cases can be the number of tests failed on the mutant source code.</blockquote><h4>Search space</h4><p>When we talk about the search space in the context of using software, we are referring to all the potential scenarios that can be encountered while using the software. This includes the various inputs and outputs that the software can handle.</p><p>Inputs to the software can come in different forms.<br><strong>-</strong> Gestures such as clicking, touching, or pressing keys. Additionally, <br><strong>-</strong> files or data<br><strong>-</strong> environment settings and configurations.</p><p>On the other hand, the outputs of the software encompass any action that the software can perform. This can range from displaying a message on the screen to sending a message over the internet, and everything in between.</p><p>When it comes to testing the software, an exhaustive test set should take into account all the possible combinations of inputs and outputs. This means that the search space should contain all the inputs and outputs that the system can encounter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2HX5x69mds6eebNPr0Dxg.png" /></figure><h3>How to execute evolutionary testing?</h3><h4>Initiation</h4><p>In evolutionary testing, the initial population of test cases is generated using a combination of random and heuristic approaches to ensure diversity. Test cases are structured based on defined input parameters and evaluated using a fitness function targeting specific objectives such as code coverage. This diverse initial population is essential for the evolutionary process, where test cases are progressively refined through selection, crossover, and mutation to optimize testing outcomes.</p><h4>Selection</h4><p>The test suite size can be predetermined, and a random set of test cases of this size can be designated as an individual. Multiple such individuals are generated to form the initial population for the first generation. <br>This approach provides a structured and diverse starting point for the evolutionary testing process, allowing for the exploration of various combinations of test cases within the initial population. Through subsequent generations, the evolutionary process aims to optimize the test suite by selectively breeding and evolving individuals based on their fitness in achieving testing objectives.</p><h4>Crossovers and Mutations</h4><p>From the current generation, we select individuals and do crossovers and mutations on them. The choice of individuals for crossovers and mutations depends on the fitness of those individuals. The higher the fitness of the individual, the more likely is the individual to be selected for crossover or mutation. This can improve the fitness of the upcoming generation. We still give a small probability for the individuals with less fitness to be selected, so as to avoid the possibility of being stuck at a local maxima.<br> <br>After selecting the individuals, crossover, and mutation are applied to them. Crossover involves combining parts of two or more individuals to create a new test suite, enhancing the diversity of the next generation. Mutation introduces small random changes to some individuals in the test suite, thus exploring new cases. These processes iteratively refine the population, optimizing test cases to achieve better coverage and defect detection.</p><h4>Evaluations and iterations</h4><p>The new generation formed through evolutionary algorithms is likely to have a higher average fitness compared to the previous generation due to the selection and reproduction processes that favor more fit individuals. By repeatedly applying the steps of selection, crossover, and mutation over multiple iterations, the algorithm progressively refines the population. This iterative process results in a population that better adheres to the defined fitness function, improving the overall quality of solutions.</p><p>If mutation testing is used as a measure of fitness, incorporating changes to the mutant code after each iteration can introduce greater diversity. Mutation testing involves creating small, random changes in the code (mutants) to see if the test cases can detect them. By changing the mutant code in each iteration, the algorithm exposes the population to a wider variety of scenarios, which can help avoid local optima and ensure a more comprehensive search of the solution space.</p><p>This diversity is crucial as it prevents premature convergence to suboptimal solutions and encourages exploration of new areas in the solution space. Consequently, the population evolves to have not only higher fitness but also greater robustness and adaptability to various potential situations, ultimately leading to more effective and resilient solutions.</p><h3>Benefits of Evolutionary testing</h3><h4>Automation</h4><p>Evolutionary testing uses evolutionary algorithms to automate the generation and optimization of test cases. This approach reduces the manual effort needed to create and maintain test cases. By leveraging evolutionary algorithms, the testing process becomes more efficient and effective. These algorithms mimic the process of natural selection to evolve and improve the test cases over time. As a result, evolutionary testing can help identify and address software defects while reducing the burden on manual testers.</p><h4>Effectiveness</h4><p>Evolutionary testing enhances code coverage by generating test cases that explore previously untested paths, thereby improving verification across a broader spectrum of the software’s functionality. Additionally, it optimizes resource allocation, directing efforts toward defect-prone areas which increases testing efficiency.</p><h4>Adaptability</h4><p>Evolutionary testing demonstrates high adaptability, adjusting test cases dynamically as software requirements or the underlying codebase evolve. This capacity makes it particularly effective for projects characterized by continuous development and frequent updates, ensuring that testing processes remain relevant and comprehensive despite changes.</p><h4>Reproduction of failures</h4><p>Understanding the potential causes of software failure is essential as it can result from various factors, some of which may not be immediately apparent to the user. Users may encounter failures without a clear understanding of the actions or events that led to the issue. Reproducing the failure is crucial for thorough system testing and diagnosis.<br> <br>A variant of evolutionary testing can help in reproducing failures by systematically exploring a wide range of input combinations and environmental conditions. Through the processes of selection, crossover, and mutation, it generates diverse and optimized test cases that can uncover hidden defects. When a failure is detected, the specific test case causing the failure is identified, making it easier to reproduce and analyze the issue, leading to more robust software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_2kHX72R53PCkntBZQkPQ.png" /></figure><h3>Challenges</h3><p>The following are some of the challenges in implementing evolutionary algorithms in testing.</p><h4>Defining Fitness Function</h4><p>Defining a fitness function for various kinds of testing in evolutionary algorithms presents distinct challenges. For instance, there are challenges in defining the fitness for performance testing primarily due to the multifaceted nature of performance metrics and the diverse conditions under which systems operate. Given these complexities, defining an effective fitness function for performance testing in evolutionary testing frameworks requires a deep understanding of both the software/hardware being tested and the specific performance metrics that are most relevant to the system’s operational success.</p><h4>Computational Resources</h4><p>Evolutionary testing can overutilize computational resources due to the need for managing large populations of test cases, conducting multiple generations of evolution, and performing intensive fitness evaluations. The processes of crossover and mutation further consume resources, and redundant operations can lead to inefficiencies. These factors collectively result in significant computational load during evolutionary testing.</p><h4>Scalability</h4><p>Scalability is a significant issue in evolutionary testing due to the intensive computational requirements for handling large populations of test cases. As the software system grows, the number of potential input combinations increases exponentially, demanding more memory and processing power. Multiple generations of evolution, combined with resource-intensive fitness evaluations, further exacerbate the computational load. Additionally, the processes of crossover and mutation require extensive calculations, which can become impractical for larger systems. Redundant evaluations of similar test cases can also lead to inefficiencies, making it challenging to scale evolutionary testing for complex and extensive software applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0u8u8Qwo8nkKYnuo1SooGg.png" /></figure><p>In short, we can say that leveraging evolutionary algorithms is a powerful approach to generating test cases. The efficiency of the output in terms of code coverage and defect detection makes it a valuable tool in software development. The algorithm takes care of the thorough exploration of the search space which not only improves robustness of the software, but also optimizes the resource utilization. As software systems grow in size and complexity, evolutionary testing will continue to be a handy tool in the developer’s armory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75fa99c1fd74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Symbolic regression: When regression took it seriously]]></title>
            <link>https://pub.towardsai.net/symbolic-regression-when-regression-took-it-seriously-a5f47ada8ad8?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f47ada8ad8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Mon, 20 May 2024 16:44:22 GMT</pubDate>
            <atom:updated>2024-05-21T13:24:58.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Symbolic Regression: When Regression Took it Seriously!!</h3><p>In a great mission to unravel the mysteries of the universe, humans always sought the patterns in the vast abundance of data. Going to the previous century, John Kepler, the brilliant mind behind Kepler’s laws of planetary motion, was not armed with a computer that could run a genetic algorithm to find the patterns in his data. Kepler made use of his sheer mathematical brilliance and fixed his eyes and mind on a huge dataset and unveiled the relationship between a planet’s time period and radius. His method was simple, immerse himself in the data, trust his intuitions, and let the patterns emerge. This method was used by various scientists throughout the history of science. But do not mistake simplicity for ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqxKNjaLV1v8jz3GenLaJg.jpeg" /></figure><p>Scientists who used the above method in the past had to put a lot of effort and dedication into their discoveries. In the modern world, where data grows in size and dimensions, the task of uncovering complex patterns becomes more daunting. In the agony, symbolic regression emerges, a modern computational marvel that kills pain in the pursuit of patterns.</p><p>Symbolic regression stands apart from classic regression by offering greater flexibility in identifying patterns within data. A traditional regression model looks for a specific pattern in data, i.e. a model designed for finding linear relationships cannot work accurately on data that has an exponential relationship between variables. Symbolic regression thrives on this diversity. It is closely related to the <a href="https://medium.com/towards-artificial-intelligence/genetic-algorithm-a-quick-glance-ae36b9f1317d">genetic algorithm</a>, in fact, it is a modification of the evolutionary algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBjRwpSrthAj6pzo5Fq56w.jpeg" /></figure><p>A normal evolutionary algorithm goes as follows:</p><ul><li>We have a population of individuals (mathematical functions), and a fitness function (accuracy of the function on our data)</li><li>We randomly select an n-sized subset of the population</li><li>We calculate the fitness function of all the individuals in the subset</li><li>We select one individual from the subset. Selection is made in such a way that the fittest individual is the most likely to be selected, but still, there is a chance that another individual is selected. (The more the fitness, the more the probability of being selected)</li><li>We create a copy of this selected individual and do a random mutation on it (randomly change an operation in the mathematical function)</li><li>We replace the weakest member of the subset with this mutated copy.</li></ul><p>These steps are repeated to get a subset of high-average fitness</p><blockquote>Crossover between individuals is not done in the above algorithm. You can introduce crossover by selecting more than one individual from the subset and doing a crossover among them before mutation.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gPTPEzKA34SflUen" /></figure><p>Symbolic regression makes modifications to this evolutionary algorithm to improve its output. One important modification is the introduction of age-regularization. Instead of replacing the weakest member of the subset, the earliest created individual in the subset is replaced. This could prevent the early convergence of the population and avoid getting stuck at a local maximum fitness function.</p><p>When it comes to symbolic regression, a fascinating twist is introduced to improve the algorithm — age-regularization. Age-regularization ushers a chronological method of regeneration, i.e. instead of adding the newly formed individual by replacing the weakest individual, we replace the oldest element in the subset, thus making way for a new generation. This change can have a profound effect on the evolutionary journey of the population. Age-regularization ensures that genetic diversity is maintained within the population. It prevents the population from stagnating at a local maximum, thus encouraging a robust search in the solution landscape.</p><p>Symbolic regression also uses a new variable called temperature, which controls the mutations in the algorithm. Based on the value of temperature, the algorithm can reject the mutations when the fitness of the mutated individual is lesser than the original chosen individual. This process is called simulated annealing. This temperature value can also be coupled with the probability of choosing an individual from the population. Using this variable we can have good control of converging or diverging our expression. Simulated annealing has been experimentally proven to speed up the search process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hxqPzQbsAg3uJq0DN5iyA.jpeg" /></figure><p>In symbolic regression, the genetic algorithm goes through an evolve-simplify-optimize loop, i.e., after every evolution, the mathematical expressions are simplified and optimized. The simplification and optimization can reduce the complexity of the algorithm, but they are introduced only after some iterations of evolution alone. This is done to avoid losing some important individuals.</p><p>Suppose the equation we are searching for is (x*y) — (x/y). In one step, we reach (x*y) — (x*y). We know that we are one correct mutation away from finding our solution. But, if we simplify the equation, it will go to 0 and we won’t be able to achieve the output. So, simplifying only occasionally can keep the redundant but useful expressions while reducing the complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7r3qUYrMb7Fvxxj0EL_3gg.jpeg" /></figure><p>Symbolic regression is like the maverick scientist of the regression world, shaking things up with its cool genetic algorithm vibes. It’s the rebel that doesn’t settle for a “close enough” mathematical model, but instead crafts an actual, tangible model that scientific researchers can hold onto.</p><p>While traditional regression models might come close to fitting the data, they can sometimes play havoc with related theories and derivations. Symbolic regression, on the other hand, is the renegade that refuses to compromise, delivering precise and impactful results for the scientific community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f47ada8ad8" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/symbolic-regression-when-regression-took-it-seriously-a5f47ada8ad8">Symbolic regression: When regression took it seriously</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>
        <item>
            <title><![CDATA[Genetic Algorithm: A Quick Glance]]></title>
            <link>https://pub.towardsai.net/genetic-algorithm-a-quick-glance-ae36b9f1317d?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae36b9f1317d</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[genetics]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 13:50:36 GMT</pubDate>
            <atom:updated>2024-03-20T14:03:21.758Z</atom:updated>
            <content:encoded><![CDATA[<p>Science and technology have made rapid progress in the recent past. Humans are always in pursuit of answers to everything, and this led to a lot of innovative breakthroughs, ranging from remedies for deadly diseases to extra-terrestrial travel. The world of computer science has made great achievements in the recent past, with artificial intelligence being the buzzword of the modern world. Even though it is relatively new to the common man, the term AI is as old as the term computer. Ever since computers were invented, scientists have been thinking about inducing intelligence in them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OeKgW0JKNXpTDMVe" /><figcaption>Photo by <a href="https://unsplash.com/@siderius_creativ?utm_source=medium&amp;utm_medium=referral">Gerard Siderius</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Gradually, the focus of the study shifted to the world of biology, where intelligence actually existed. In this regard, they studied three main concepts — the model of the brain, the learning mechanism of humans, and evolution. The first one led to the development of artificial neural networks, and the second one led to the concept of machine learning. The third one gave birth to a very interesting concept called <strong>genetic algorithm</strong>!</p><p>Before going to what the genetic algorithm is, let’s have a quick peek at why genetic algorithm. The pre-historic studies say that the world started with a big bang 14 billion years ago. 10 billion years later, the first life was formed on earth in the form of some microorganisms. 2 billion years later humans comparable to the species we see around us were formed. Assuming the theories are correct, evolution is what makes this transition possible. Through a series of evolutionary steps that occurred naturally without the interference of any intelligent force, a microbe evolved into humans. Magical isn’t it???</p><p>No. Not to someone with a mathematical background. Did you miss that I said, “2 billion years later”? The microbes take a day or less to reproduce. Even the small animals take months or maybe a few years. Humans reproduce on average every 25 years. So in the worst case, if I consider 4 generations per 100 years, it took “80 million” generations at the least for such a transformation. That is a lot more generations than you can imagine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fwy_9ehc1JjLWSdw" /><figcaption>Photo by <a href="https://unsplash.com/@jplenio?utm_source=medium&amp;utm_medium=referral">Johannes Plenio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Being a natural process, genetic evolution was slow. If it was simulated artificially, it could have been much faster and better. That is where the computer scientists found the opportunity to mock the same process and solve problems.</p><p>The genetic algorithm comes from genetics, a basic concept in biology that explains evolution. In simple terms, every organism has some characteristics and abilities, that are defined by their genes. An organism has multiple genes, each of which can take multiple states. The set of genes contained in a structure called chromosomes can undergo various operations such as crossover, mutation, inversion, etc. After these operations, the resulting chromosomes can be stronger or weaker than the original. According to the survival of the fittest theory, the organisms that have the stronger chromosomes survive, while the one that has weaker chromosomes phases out, maybe without contributing to future generations.</p><p>So when we take the population as a whole, the average fitness of a generation is much likely to be higher than the past generations.</p><p>Now coming to computer science, this theory can be used to find good solutions to problems that are theoretically harder to solve. Let us take an example.</p><p>We aim to find a medicine that can cure a certain disease. To make that, we need a protein of a particular shape. Proteins are chains of amino acids. There are 20 possible amino acids, so a protein of length 10 can have 20¹⁰ possible combinations. All of these combinations will not align to the required shape. Every protein offers resistance when we try to bend it into the required shape, which can be measured using available equipment.</p><p>At first glance, we might think that the resistance offered depends on each of the amino acids. In that case, we could have found the 10 amino acids that offer the least resistance and built a protein with them. But that is not the case here. The contribution of an acid to its resistance depends on the other acids in the protein as well as its sequence. In this case, a genetic algorithm is the best possible solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*3gDhI223xbrA8InoiZEIlg.jpeg" /></figure><p>Consider that a protein is a chromosome and each of its amino acids is a gene. We can define a fitness function such that the resistance offered by the protein decreases the fitness of the protein. By starting with a random set of proteins and evolving them with genetic operations, we can reach a good protein in less number of tests.</p><p>Step 1</p><p>Take a set of randomly selected proteins. We can fix a population size, say 50, and choose 50 random proteins. Now calculate the fitness of all these proteins.</p><p>Step 2</p><p>Choose two random proteins from the population and do a crossover. A crossover is an operation in which a certain area of both chromosomes is selected and exchanged. Suppose our proteins are AVGFTGATGH and NJGTHSRTFV. We take a part, say the first 4 acids, and exchange them between the chromosomes. So the resultant proteins will be NJGTTGATGH and AVGFHSRTFV. The resultant proteins will be added to a new population.</p><p>The choice of proteins to crossover is not completely random. The proteins with more fitness are more likely to be chosen (because in evolution, the fittest organisms survived and reproduced).</p><p>The step is repeated until the new population has the same number of elements as the original population.</p><p>Step 3</p><p>The elements in the new population may undergo mutation or rearrangement. Mutation is a process in which a random acid in a protein changes to some other acid. For example, a protein ABCDEF can be mutated at second position to form ATCDEF.</p><p>Steps 2 and 3 produced a new population which can be considered as a new generation. These steps can be repeated to form more generations, and each generation will be fitter on average compared to the previous generations.</p><p>The process of crossover helps here as one of the resultant proteins is very likely fitter than its parent proteins. Mutation is required to stop the process from converging to a subpopulation. For instance, if the initial population does not contain the amino acid B, then the only way to bring it into the algorithm is through mutation.</p><p>After several generations, we will get a much fitter population, which contains a protein that is good for our situation. Thus, we can solve the problem using a genetic algorithm quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-p7Gqm1UhgZ5COUf4KposA.jpeg" /></figure><p>Though the protein we got might not be the best possible option, we got a good option in much less time. This is just one such example. There are many situations where a quick good answer is better than the slow best answer. For instance, a fast-moving driverless car has to make an action. While the car can compute the best possible action, there won’t be enough time to do it, instead, a nearly good action with quick response time will be ideal.</p><p>Genetic algorithm is a vast topic. It cannot be contained in a single article. More articles on the proofs and interesting applications will be discussed in future articles. Make good use of the commenting section😅. Have a happy reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae36b9f1317d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/genetic-algorithm-a-quick-glance-ae36b9f1317d">Genetic Algorithm: A Quick Glance</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>
        <item>
            <title><![CDATA[Chain of Thought Prompting: That’s how we make the models think.]]></title>
            <link>https://pub.towardsai.net/chain-of-thought-prompting-thats-how-the-models-think-6e31a5844a32?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e31a5844a32</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 14:41:06 GMT</pubDate>
            <atom:updated>2024-01-31T13:40:42.270Z</atom:updated>
            <content:encoded><![CDATA[<p>I was just playing around with the chatGPT when I tried the following prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*cJXpuHb-rr-l7_EgCeTeaQ.png" /></figure><p>The model gave a wrong output to a basic arithmetic problem. This wasn’t a surprise (at least for me), as large language models are not designed for arithmetic problem-solving. They can’t be relied on for any situation where we need accurate or factual answers. They are designed to talk to us like a human being.<br> <br>Then, I tried a technique called few-shot prompting. Here we give examples to teach the model how to respond. I added a new similar math problem along with the correct answer before asking my actual question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*dZHVopXG_72p8fO39Y6krw.png" /></figure><p>Still a wrong answer!! Well, I am not planning to give up that easily. I am going to teach the model a lesson (on arithmetic).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moHMogAqigB_ZkgRst0Ygw.png" /></figure><p>Tadaa!!!! Now the model knows what has to be done. All I did was give the model enough examples to unlock its full reasoning ability. This few-shot prompting technique, in which we show examples of certain prompts and outputs along with the intermediate thought process, is called the chain of thought prompting.</p><p>The main concept behind the chain of thought prompting is to endow a thought process on large language models, similar to how humans think. When humans encounter a problem, we will break it down into a sequence of small problems and solve each of the problems until we reach the final output. The large language models can do the same if they provide examples using the few-shot prompting technique.</p><p>Chain of thought prompting has the following advantages:</p><ul><li>When problems are broken down into multiple steps, each step can be given enough computation based on the complexity of that step. Thus, more focus will be given to the important steps.</li><li>When models output the thought process (like in the previous example), the users can get an idea of the black box model’s way of thinking. This is beneficial in debugging the large language models.</li></ul><p>Thus, this method can be applied to any large language model and can be used to solve any task that a human can solve using language.</p><p>The above experiment shows how showing an example solves a new problem. But did the chain of thought help the model, or did the given example just activate a problem-solving skill of the model? To test this, I conducted a different experiment where I explained the steps after answering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4pNegC16G7cMJlXFueqqg.png" /></figure><p>Here, it gives a wrong output of 23, where the correct answer should have been 80.</p><p>Now I ask for the steps after the answer, and this time, it solved the problem without mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7yKcOJWtB9OSS4OnyRsww.png" /></figure><p>So, when we make the model explain the steps, it goes through the correct steps and gives the correct answer.</p><p>Chain of thought prompting can also be used for commonsense reasoning and logical operations. See the below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*ecbyAzH3OFUp8b6j4R2S_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*EBIHETnEFVlbutgPD9J5Nw.png" /></figure><p>When we ask the model for a reason, it goes through a chain of thought processes. Even without an example, the model gives good reasoning and a good answer. This happened even though it initially failed to provide the right answer.<br> <br>Now, we can see the example of symbolic reasoning. Symbolic reasoning means identifying patterns which is easy for a human but can be quite challenging for a large language model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9SA7dWYg7M-aWLx-Ez6CA.png" /></figure><p>Here, the reason I gave two kinds of examples is to make the model think more. The model can look for any pattern, but a single pattern might curb the model from thinking outside the given pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQu_OsyE6hX7bYa--AYyzA.png" /></figure><p><strong>Importance of prompt engineering.</strong></p><p>Prompt engineering plays a very important role in language models. For an LLM user, understanding how to get the necessary output is very important. While the large language models possess the capability to perform a diverse range of complex tasks, the responsibility lies in the user to guide the model in achieving the task. AI, especially generative AI, is not meant to replace humans. It is meant to assist humans. In a world where LLMs will be common like crows, it is your job to learn how to prompt them so that your life is made easier.<br> <br> In the examples I used, I made use of few shot prompting to initiate the chain of thought. The prompting technique used to initiate the chain of thought depends on the user. One can initiate the chain of thought in the following way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63mZAfCguZDmUJ_SlCRMAA.png" /></figure><p>Here the user was able to initiate the chain of thought without using few-shot prompting. The LLM gives the correct output of 38 in the end.<br> <br><strong>Behind the stage</strong><br> <br>In this article, I talked about initiating the chain of thought in large language models by efficient prompting. Let’s have a peek at what is happening behind the stage. The size of the model plays an important role in the chain of thought prompting. By size of the model, I mean the number of parameters. A model with less number of parameters is likely to make a mistake in the chain of thought process. There is no denying the fact that smaller models are weaker in arithmetic operations. Their inability to understand the semantics in the prompt and initiate a correct chain of thought is evident. Common mistakes made by the small models include misinterpretation of the semantics and missing a step or arithmetic calculation. Thus, it is important to have human observation when the large language models are doing these kinds of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*GczZgyxKtz5gUUr3VGjRaA.png" /></figure><p>Chain of thought prompting is very efficient, but better methods like ReAct also exist. Tot Ziens until I delve deep into those concepts. If you had a good read, follow me for more exciting stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e31a5844a32" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/chain-of-thought-prompting-thats-how-the-models-think-6e31a5844a32">Chain of Thought Prompting: That’s how we make the models think.</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>
        <item>
            <title><![CDATA[ReDoS : Mind your regex to save your software]]></title>
            <link>https://medium.com/@abhijithsbabu183/redos-mind-your-regex-to-save-your-software-c0caf0dbcb5e?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0caf0dbcb5e</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[denial-of-service-attack]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 10:37:24 GMT</pubDate>
            <atom:updated>2024-01-24T10:37:24.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>ReDoS : Mind your regex to save your software</h3><p>Most of us have probably tried doing some computer experiments to access things we’re not supposed to. Every computer program, no matter how strong it seems, has weak points that attackers try to find. These attackers are like digital detectives searching for ways to harm the program and the people using it. In this back-and-forth between keeping things safe and trying to break in, there are various dangers. These include invading someone’s privacy, sneaking into parts of the program that are off-limits, and even completely stopping the program from working. The risks are many. Today I am going to talk about Regular Expression Denial of Service (ReDoS), a threat that can potentially bring a software down to dust, due to the inefficiencies in a simple regular expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ODxfamik2cMsQdo" /><figcaption>Photo by <a href="https://unsplash.com/@blunkorama?utm_source=medium&amp;utm_medium=referral">Daniel Lloyd Blunk-Fernández</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Think of a door, guarded by several guards. You are allowed to get past only if you pass a set of written criteria. A regular expression is quite similar to those criteria. It is a set of rules that checks whether a string is eligible for further processing. For example, there is a door that only allows email IDs to pass through them. So the set of rules says</p><ol><li>Start with one letter.</li><li>followed by zero or more letters or numbers.</li><li>optionally followed by a dot(.) followed by one or more letters or numbers.</li><li>followed by a ‘@’.</li><li>followed by two or more letters.</li><li>followed by any number of a dot (.) followed by two or more letters.</li></ol><p>These rules can be written in a condensed form:</p><pre>^[a-zA-Z0–9._%+-]+@[a-zA-Z0–9.-]+\.[a-zA-Z]{2,}$</pre><p>which is understood by programming languages. But how can such a simple thing bring down a whole software? To understand that, you have to know how a regex works.</p><p>The regular expression engines usually follow a method called backtracking. Imagine we have a regular expression that looks for a specific pattern, ‘<strong>ABABC</strong>’, in a bunch of text. Now, we have a particular text: ‘<strong>CCABABABCCD</strong>’. The code starts by searching for an ‘A’ in the text. It finds one in the third position. Then, it checks if there’s a ‘B’ after the ‘A’, and indeed there is. The code continues by looking for another ‘A’ and then a ‘B’, and it finds both. Now, it’s on the lookout for a ‘C’, but instead, it finds another ‘A’ in the next position. The current attempt to match the pattern ‘ABABC’ fails because it expected a ‘C’ but got an ‘A’ instead. In the current attempt, we started at the third position, so now we go to the 4th position and start searching for an A again. This time we find an ‘A’ in the 5th position, which is followed by a ‘B’, ‘A’, ‘B’, and ‘C’. The pattern matches finally.</p><p>In the above example, we see the number of steps taken to complete the validation can be very high. To search a substring of size <em>k </em>in a string of size <em>n</em>, the complexity could be <strong><em>O</em></strong><em>(k*n)</em>. That means, in the worst case, we might need almost <em>k*n</em> steps to validate it. The complexity depends upon the regular expression we are using, i.e. the way we define the rules affects the time taken to process it.</p><p>For instance, if we want to check whether a given string is binary, we can define the rule in 2 ways</p><ol><li>Check whether each character in the string is 0 or 1 : <strong>^[0|1]+$</strong></li><li>Check whether all the substrings of the strings contain only zero or one : <strong>^[[0|1]+]+$</strong></li></ol><p>Technically both the regular expressions do the same thing, but the first one is much more efficient than the second one. For a string of length n, the first regular expression takes <strong><em>n</em></strong> steps to complete validation in the worst case. But the second expression takes <strong><em>n²</em></strong> steps to even find all the substrings, then much more effort to verify each substring. Thus there is a significant increase in complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b0kBAgA_-PtT8kSH" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the vulnerability that makes a software susceptible to regular expression denial of service attacks. All the attacker has do is to find a string that takes a lot of time for CPU to process. With the CPU completely wasted on that process, the whole system slows down or crashes.<br> <br>In the above case, the flaw was obvious. Every programmer who implements this will use the first regular expression itself, as the absurdity in the second regular expression is clear. But there are cases where we might implement an inefficient regular expression because it looks efficient.</p><p>Here is an example. You have a regular expression that validates dates in <em>yyyy-mm-dd</em> format. (For the sake of this example I am checking whether the string contains digits and hyphens and is in yyyy-mm-dd format. Other factors like checking if the month is between 1 and 12, which adds more complexity, are not considered here). The regular expression for the same will be</p><pre>^\d{4}-\d{2}-\d{2}$</pre><ul><li>^ denotes the start of the string</li><li>\d{4} checks for 4 digits</li><li><strong>-</strong> checks for a hyphen</li><li><strong>\d{2}</strong> checks for 2 digits</li><li><strong>-</strong> checks for a hyphen</li><li><strong>\d{2} </strong>checks for 2 digits</li><li><strong>$</strong> denotes the end of the string</li></ul><p>The regular expression starts from the beginning of the string and checks each of the patterns until it reaches the dollar sign, where the string should end. Now the programmer might spot the repetition of hyphen(-) and \d{2} in the regular expression. “Why should I repeat that instead of clubbing them together?”. The programmer changes it to</p><pre>^\d{4}(-\d{2}){2}$</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*CQoI4zgvZv6gIgGMVxCZCw.jpeg" /></figure><p>The new regular expression does the same thing, checks for 4 digits followed by 2 occurrences of a hyphen followed by 2 digits. This regular expression is smaller than the other and hence looks efficient (a common notion in the programming world😅). Unfortunately, a hacker notices this and gives the input 2024–01–24–22–23. The original regular expression checks if it has four digits for the year, a hyphen, two digits for the month, another hyphen, and finally, two digits for the day. If it encounters more characters, it quickly identifies the issue and stops processing.</p><p>The modified regular expression is more complex. It checks for a specific pattern: four digits for the year, followed by two instances of a hyphen and two digits each. However, it examines all possible pairs of a hyphen and two digits and checks if they occur immediately after the year, before the end of the string, and are consecutive. This introduces a potential problem with time complexity, especially for long inputs.</p><p>For example, with an input like “2023–11–30–01–02–03–04–05–06…”, the regex engine may need to explore a large number of possibilities, resulting in a time complexity of approximately n², for n occurrences of “-\d{2}”. This can be inefficient and potentially crash the system when dealing with extremely long inputs.</p><blockquote>A regular expression denial of service attack (ReDoS) can happen if,</blockquote><blockquote>1. the number of attempts required increases exponentially with respect to the length of input,</blockquote><blockquote>2. the input fails to match regular expression, and</blockquote><blockquote>3. the input is too long for the CPU to handle.</blockquote><p>Avoiding ReDoS issues is crucial, and a simple way to tackle this is by using efficient regular expressions. Keep your regular expression straightforward. Write the regular expression keeping an eye on how the engine backtracks them. Try to avoid nested structures in your regular expressions. Even the most perfect regular expression can have an exponential complexity. In those cases, sanitizing the input strings before applying the regular expression helps. Next time you write a regular expression, you will think about it. Hope you had a happy reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0caf0dbcb5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Code of Context: Word Vectorization Techniques in NLP]]></title>
            <link>https://pub.towardsai.net/cracking-the-code-of-context-word-vectorization-techniques-in-nlp-9fa3a90a3368?source=rss-7ff9f333ad49------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa3a90a3368</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Abhijith S Babu]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 15:56:06 GMT</pubDate>
            <atom:updated>2023-08-21T13:46:24.791Z</atom:updated>
            <content:encoded><![CDATA[<p>You moved to a new town far from your country, where you happened to bump into someone in a coffee shop. A young woman around your age and instantly, you both were engaged in a conversation. It happened because both of you knew English. Just when you were thrilled to have met someone who spoke your language, the waiter came speaking in the native tongue, to take your order. Well, your new friend is ready to be a translator. As soon as you were back in your apartment, you rummaged through the internet, looking for courses to learn the native language. So it’s vivid that a common language is essential for proper communication between two entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHqmf31Yhhhkyxjw" /><figcaption>Photo by <a href="https://unsplash.com/@daanelise?utm_source=medium&amp;utm_medium=referral">daan evers</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the buzzing domain of artificial intelligence, natural language processing is an exciting technology. It’s fascinating that a machine is able to understand what you are speaking in your native language. This facilitates a smooth mutual interaction between humans and computers. But shouldn’t there be a common language of communication for it to happen? As we know, humans speak a wide variety of languages, such as English, Spanish, French, Hindi, Mandarin, and so on. But the only language computers know is binary. Their entire world is built up of 0s and 1s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ftEAqIRnGtVJtf5h" /></figure><p>If computers understand numbers and we understand languages such as English, there should be something that converts natural language to numbers. Word2vec comes to our rescue.</p><p>Word2vec represents the words in a sentence as a vector in a continuous space. The vectors capture the semantic relationship between the words in various contexts. Similar words have a similar vector. The figure below shows a 2D representation of such a vector space (the dimension of a vector space in actual <strong>NLP</strong> problems is way more than 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*W7deKMP7nf6FQRKDgoytgQ.png" /></figure><p>We can see similar words like walk and run close to each other. While smile and Radiology are unrelated words and are far apart. The words close to each other are called replaceable words, i.e., if you interchange those words in a sentence, the sentence will still make sense. The replaceability of two words can be calculated based on the cosine of the angle between the vectors of two words. This can take a value between -1 and 1, 1 meaning the words are strongly related. Some operations on the vectors can be used to perform tasks such as finding analogous words.</p><p>Word2vec is mainly used in word predictions. We might have seen features like autocomplete and autocorrect in our daily used apps like email. Word2vec is mainly used to predict the next word/words in an incomplete document or to fill in the missing words in a document. To perform these tasks, a machine learning model will be trained.</p><p>We can now see some ways in which natural languages are vectorized for real-life applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W-00HUVO8HcwG7bp" /><figcaption>Photo by <a href="https://unsplash.com/@jefflssantos?utm_source=medium&amp;utm_medium=referral">Jefferson Santos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here we are gonna train a spam filtering model using a relatively small dataset. For a proper model, we have to use a larger dataset. That will take a lot of time to run.</p><p>The data consists of several text messages which are either spam messages or not. It can be downloaded from <a href="https://archive.ics.uci.edu/dataset/228/sms+spam+collection">here</a>.</p><p>It is a text file in which each line has two fields, a label, and a sentence separated by a comma. The label is given spam for spam messages and ham for genuine messages.</p><p>I am going to implement this in Python. The program requires various libraries such as <em>numpy, pandas, nltk, regex, gensim</em>, and so on. If you don’t have them installed, you can install them using pip. I will show you all the packages imported for the program.</p><pre>from gensim.models import Word2Vec<br>import numpy as np<br>from nltk.corpus import stopwords<br>import nltk<br>from nltk.corpus import stopwords<br>import pandas as pd<br>import string<br>import regex as re<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import precision_score,recall_score<br>from sklearn.model_selection import train_test_split<br>import gensim</pre><p>Now that we have all the packages imported, we can start the implementation.</p><p>The first step is to clean and prepare the dataset.</p><pre>messages = pd.read_csv(&quot;output.csv&quot;, delimiter=&quot;\t&quot;)<br>messages.columns = [&quot;label&quot;, &quot;text&quot;]<br> <br> <br>def text_cleaner(text):<br>    nxt = &quot;&quot;.join([char for char in text if char not in string.punctuation])<br>    nxt = re.split(&quot;\W+&quot;,nxt.lower())<br>    nxt = [k for k in nxt if k not in stopwords.words(&#39;english&#39;)]<br>    return nxt<br> <br>messages[&quot;clean_text&quot;] = messages[&#39;text&#39;].apply(lambda x:text_cleaner(x))<br>print(messages.head())</pre><p>I saved the dataset in a file called output.csv. I used <strong><em>pandas.read_csv()</em></strong> to read the file. The delimiter is set to “<em>\t </em>”as the fields are separated in the dataset using tabs.</p><p>We gave titles to the two columns in the data as <strong>label</strong> and <strong>text</strong>.</p><p>Now we have to convert the text into tokens. Before that, we can clean the texts. First, we removed all the punctuation in the sentence. In Python, all the common punctuation&#39;s can be found in <strong><em>string.punctuation</em></strong>.</p><p><strong><em>nxt = re.split(“\W+”,nxt.lower())</em></strong><em> </em>is used to split the sentence into a set of words using regex. I have also converted the words into lower-case since we don’t want our model to be case-sensitive.</p><p>Stopwords are those words which doesn’t contribute much to the gist of the sentence. There are around 170+ stopwords in English. They can be accessed from the <strong><em>nltk</em></strong> library using <strong><em>stopwords.words(‘english’)</em></strong>. We can remove those words from our data to make our model light and efficient.</p><p>The data is now cleaned and tokenized and is stored in a new column called clean_text. The first 5 entries in the data can be printed using head() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*UEUtFE7qw6JdQo13f5SmgA.png" /></figure><p>Now we have a set of tokens, which we have to convert into vectors before training. For that, let us use a property called TF-IDF (Term Frequency Inverse Document Frequency). The TF-IDF of a word in a document shows how important that word is to the document. It is directly related to the frequency of the word in the document and inversely related to the number of documents in the sample space. It can be calculated using</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*CeMX5QNbk386DhDea2UQTQ.png" /></figure><p>In Python, we can use a <strong>TfidfVectorizer</strong> class to create the vectors. To make the code simple, we are not creating a new column for cleaning and tokenizing. The text_cleaner function can be called in the <strong><em>TfidVectorizer()</em></strong>.</p><pre>new_vector = TfidfVectorizer(analyzer=text_cleaner)<br>x = new_vector.fit_transform(messages[&#39;text&#39;])<br>x_features = pd.DataFrame(x.toarray())</pre><p>x is now a 2D array in which each row represents a vector that contains the TF-IDF value of all the tokens in the sample space. If the word is not present in the sentence, the TF-IDF value of that token will be zero. Since this is the case for most of the words, we got a sparse matrix. The matrix is now converted to a pandas data-frame for training.</p><p>Here we are using the <strong><em>RandomForestClassifier</em></strong> provided by <strong>sklearn</strong> to train the model.</p><pre>x_train, x_test, y_train, y_test = train_test_split(x_features,messages[&#39;label&#39;],test_size=0.2)<br>rf = RandomForestClassifier()<br>rf_model = rf.fit(x_train,y_train)<br>y_pred = rf_model.predict(x_test)<br>precision = precision_score(y_test,y_pred,pos_label=&#39;spam&#39;)<br>recall = recall_score(y_test,y_pred,pos_label=&#39;spam&#39;)<br>print(&quot;precision = {} and recall = {}&quot;.format(round(precision,4),round(recall,4)))</pre><p>The data is split into training and testing sets and the training set is passed to <strong><em>RandomForestClassifier</em></strong> to create a model. This model is tested with the test data and we got a precision of <strong>1.0</strong> and a recall of <strong>0.8378</strong>. (you might get a slightly different value as I made some tweaks in the data I had).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GWdddisGbePbxHlf" /><figcaption>Photo by <a href="https://unsplash.com/@nateggrant?utm_source=medium&amp;utm_medium=referral">Nate Grant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Word2vec, on the other hand, works on a slightly different approach. It studies the word based on its position. This is done by analyzing the nearby words of a word. A window of a certain size is created around each occurrence of a word. In this way, the context of the usage of the word is learned. Let us see how it is done on the same dataset we used in the previous example.</p><p>The data is cleaned and tokenized and is stored in a new column as we did earlier. We can split that data into training and testing data and pass them into the word2vec model. Vectorization of the tokens is taken care of by the Word2Vec class found in the <em>gensim</em> package.</p><pre>x_train, x_test, y_train, y_test = train_test_split(messages[&quot;clean_text&quot;],messages[&quot;label&quot;],test_size=0.2)<br>w2v_model = gensim.models.Word2Vec(x_train,vector_size=100,window=5,min_count=2)<br>w2v_model.save(&quot;mymodel.model&quot;)</pre><p>The trained model can be saved to the local system so that we don’t have to train every time we run it.</p><p>Here we passed a minimum count of 2, which means that a vector is created only if there are at least 2 occurrences of the word in the whole data. Thus we can eliminate some words which don’t have any impact on the problem.</p><p>A word2vec model has a lot of in-built functionalities. For instance, if you want to find the words most similar to run in the model, you can use the <em>most_similar</em>() function.</p><pre>mymodel = Word2Vec.load(&quot;mymodel.model&quot;)<br>similar_words = mymodel.wv.most_similar(&quot;run&quot;)<br>print(similar_words)</pre><pre>[(&#39;pls&#39;, 0.9978137612342834),<br> (&#39;yes&#39;, 0.9977635145187378),<br> (&#39;r&#39;, 0.9977442026138306),<br> (&#39;win&#39;, 0.9977269768714905),<br> (&#39;today&#39;, 0.9976850152015686),<br> (&#39;im&#39;, 0.9976809024810791),<br> (&#39;get&#39;, 0.9976732134819031),<br> (&#39;reply&#39;, 0.9976603984832764),<br> (&#39;new&#39;, 0.9976487159729004),<br> (&#39;one&#39;, 0.9976474046707153)]</pre><p>The output we got is very crazy. That is because we used a small dataset for this training. Similar models trained on a large number of Wikipedia documents are available in <em>gensim,</em> which gives more accurate outputs.</p><p>Vectorizing natural language has a very large scope in machine learning. This technique can be applied in other domains as well. Sentimental analysis, text generation, and machine DNA classification are just a few of those applications. The success of word2vec played a key role in the development of these fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa3a90a3368" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/cracking-the-code-of-context-word-vectorization-techniques-in-nlp-9fa3a90a3368">Cracking the Code of Context: Word Vectorization Techniques in NLP</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>