<?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 Abhiram Varma on Medium]]></title>
        <description><![CDATA[Stories by Abhiram Varma on Medium]]></description>
        <link>https://medium.com/@isjustabhi?source=rss-ce921d679daf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XemkLJays0q2831BzoyHSg.jpeg</url>
            <title>Stories by Abhiram Varma on Medium</title>
            <link>https://medium.com/@isjustabhi?source=rss-ce921d679daf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:59:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isjustabhi/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[Associated Variable Analysis: Finding Meaningful Connections in Data]]></title>
            <link>https://medium.com/@isjustabhi/associated-variable-analysis-finding-meaningful-connections-in-data-5e2b4de4a4c7?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2b4de4a4c7</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 17:17:23 GMT</pubDate>
            <atom:updated>2026-09-01T17:50:06.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Every dataset contains variables, but the real value of data often appears when we begin examining how those variables relate to one another.</p><p>For example, does spending more time studying relate to better examination results? Does increasing the price of a product influence the number of customers willing to buy it? Is employee experience connected with salary?</p><p>Questions like these are explored through <strong>associated variable analysis</strong>.</p><h3>Understanding Associated Variable Analysis</h3><p>Associated variable analysis is the process of studying two or more variables to determine whether there is a relationship between them.</p><p>A variable is simply something that can take different values. Age, salary, temperature, examination score, customer satisfaction, and product price are all examples of variables.</p><p>Suppose a researcher collects information about the number of hours students study each week and the marks they receive on an examination. If students who spend more time studying usually receive higher marks, the two variables appear to be associated.</p><p>The purpose of the analysis is not only to identify a relationship but also to understand its <strong>direction, strength, and importance</strong>.</p><h3>Why Do We Study Relationships Between Variables?</h3><p>Looking at one variable by itself can provide useful information, but comparing variables often reveals much more.</p><p>Imagine that a company knows its monthly sales. That information is useful, but management may want to understand why sales change.</p><p>The company might compare sales with:</p><ul><li>Advertising expenditure</li><li>Product prices</li><li>Customer reviews</li><li>Seasonal changes</li><li>Website traffic</li></ul><p>Studying these relationships can help the organization identify patterns and make better decisions.</p><p>The same principle applies in education, healthcare, economics, marketing, social science, and many other areas.</p><h3>Positive Association</h3><p>A <strong>positive association</strong> occurs when two variables tend to move in the same direction.</p><p>When one variable increases, the other generally increases as well.</p><p>For example, consider study time and examination performance. Students who dedicate more hours to studying may generally achieve better marks.</p><p>Another example can be found in business. Increased advertising expenditure may sometimes be associated with increased product awareness or sales.</p><p>This does not mean that the relationship will be perfect. Individual observations may be different, but an overall pattern may still exist.</p><h3>Negative Association</h3><p>A <strong>negative association</strong> occurs when variables tend to move in opposite directions.</p><p>As one variable increases, the other tends to decrease.</p><p>A simple example is product price and demand. When the price of a product increases significantly, fewer customers may be willing to purchase it.</p><p>Another example could involve the speed of completing a fixed journey. As average travel speed increases, the amount of time required to reach the destination usually decreases.</p><p>Negative association does not mean the relationship is undesirable. The term simply describes the direction in which the variables move.</p><h3>When Variables Have Little or No Association</h3><p>Not every pair of variables has a meaningful relationship.</p><p>For instance, the number of books in someone’s home may have little relationship with their shoe size. Even if we collected information from thousands of people, we would probably not find a useful pattern between these variables.</p><p>Identifying the absence of a meaningful relationship is also valuable. It can prevent researchers or businesses from making decisions based on unrelated information.</p><h3>Choosing the Correct Method of Analysis</h3><p>The technique used to analyze association depends on the type of variables involved.</p><h3>Two Numerical Variables</h3><p>When both variables contain numerical values, <strong>correlation</strong> is commonly used.</p><p>Examples include:</p><ul><li>Height and weight</li><li>Study hours and examination marks</li><li>Advertising expenditure and sales</li><li>Temperature and electricity consumption</li></ul><p>A scatter plot can also help visualize the relationship. Each observation is represented as a point, allowing the analyst to see whether the data follows a recognizable pattern.</p><p>A correlation coefficient can then be used to describe the direction and strength of a linear relationship.</p><p>A value closer to <strong>+1</strong> represents a stronger positive linear relationship, while a value closer to <strong>−1</strong> represents a stronger negative linear relationship. A value close to zero indicates that there may be little linear association.</p><p>It is important to remember that a correlation close to zero does not always mean that absolutely no relationship exists. The variables could have a nonlinear relationship that correlation does not capture effectively.</p><h3>Two Categorical Variables</h3><p>Sometimes researchers want to examine variables that represent groups or categories rather than numerical measurements.</p><p>Examples might include:</p><ul><li>Gender and product preference</li><li>Employment status and education level</li><li>Payment method and age category</li><li>Customer type and subscription choice</li></ul><p>A <strong>cross-tabulation</strong>, also known as a contingency table, can be used to organize this information.</p><p>A statistical method such as the <strong>chi-square test of independence</strong> may then be used to investigate whether the categorical variables appear to be associated.</p><p>For example, an online retailer could investigate whether preferred payment method differs across customer age groups.</p><p>If meaningful differences appear, the company may use that information when designing its payment options or marketing strategy.</p><h3>One Numerical and One Categorical Variable</h3><p>In other situations, one variable represents categories while the other contains numerical values.</p><p>Imagine that a company wants to know whether employee salaries differ according to department.</p><p>Here:</p><p><strong>Department</strong> is a categorical variable, while <strong>salary</strong> is numerical.</p><p>The company could compare average salaries across departments.</p><p>Depending on the number of groups and the purpose of the analysis, statistical techniques such as a <strong>t-test</strong> or <strong>analysis of variance (ANOVA)</strong> may be appropriate.</p><h3>A Simple Example</h3><p>Consider a small study investigating whether the amount of time students spend studying is associated with their final examination scores.</p><p>Student. Study Hours. Exam Score</p><p>A. 1. 52</p><p>B. 2. 58</p><p>C. 3. 65</p><p>D. 5. 77</p><p>E. 7. 86</p><p>From this small dataset, we can notice a pattern.</p><p>Students who studied for more hours generally achieved higher examination scores.</p><p>This suggests a positive association between study hours and examination performance.</p><p>However, we should not immediately conclude that additional study time is the only reason for the higher marks.</p><p>Other factors might also matter, including:</p><ul><li>Previous academic ability</li><li>Quality of teaching</li><li>Study techniques</li><li>Motivation</li><li>Sleep</li><li>Attendance</li><li>Difficulty of the examination</li></ul><p>This brings us to one of the most important ideas in data analysis.</p><h3>Association Is Not the Same as Causation</h3><p>Finding that two variables are associated does not automatically prove that one variable causes changes in the other.</p><p>Consider a classic example involving ice-cream sales and sunburn cases.</p><p>During hotter months, ice-cream sales may rise. At the same time, more people may experience sunburn.</p><p>If we looked only at the numbers, we might observe a positive relationship between ice-cream sales and sunburn cases.</p><p>But buying ice cream does not cause someone to get sunburned.</p><p>Instead, another factor — hot and sunny weather — helps explain both observations.</p><p>Warm weather encourages people to buy ice cream, while also encouraging them to spend more time outdoors.</p><p>A third factor that influences the relationship between variables may be described as a <strong>confounding variable</strong>.</p><p>Therefore, researchers must be careful when interpreting statistical associations.</p><h3>Association in Business Decision-Making</h3><p>Associated variable analysis is especially useful in business because organizations continuously collect information about customers, products, operations, and financial performance.</p><p>A marketing department might investigate whether advertising expenditure is associated with sales revenue.</p><p>An e-commerce company could examine whether faster delivery is related to higher customer satisfaction.</p><p>A subscription business might study whether customers who use certain features are more likely to renew their subscriptions.</p><p>These relationships can generate useful insights.</p><p>However, decision-makers should consider the wider context before changing business strategy based on a single statistical relationship.</p><h3>Association in Education</h3><p>Educational institutions can also use variable analysis to better understand student outcomes.</p><p>Researchers could investigate relationships between:</p><ul><li>Attendance and examination results</li><li>Study time and academic performance</li><li>Class participation and grades</li><li>Access to learning resources and student achievement</li></ul><p>Such analysis may help schools identify factors connected with student success.</p><p>Again, these relationships should be interpreted carefully because student performance can be influenced by many different variables.</p><h3>Association in Healthcare and Research</h3><p>Researchers frequently examine associations when studying health-related questions.</p><p>They might explore whether exercise frequency is associated with certain health measurements or whether particular lifestyle behaviors are related to specific outcomes.</p><p>Association studies can provide valuable evidence and help researchers identify questions that deserve further investigation.</p><p>However, healthcare relationships can be complex. Factors such as age, lifestyle, genetics, environment, and socioeconomic conditions may influence the results.</p><p>For this reason, observing an association should usually be considered a starting point for deeper research rather than final proof.</p><h3>A Practical Process for Analyzing Associated Variables</h3><p>A useful analysis can follow a straightforward process.</p><p>First, clearly define the question you want to answer.</p><p>For example:</p><p><strong>Is delivery time associated with customer satisfaction?</strong></p><p>Next, identify the types of variables being analyzed. Are they numerical, categorical, or a combination of both?</p><p>After identifying the variable types, explore the data using tables, graphs, averages, percentages, and other descriptive methods.</p><p>The next step is choosing an appropriate statistical technique. Depending on the situation, this might involve correlation, regression, a chi-square test, a t-test, or ANOVA.</p><p>Finally, interpret the results in context.</p><p>A good analyst does more than report a number. They ask what the relationship means, whether it is strong enough to matter, what other variables could be involved, and whether the evidence supports the conclusion being made.</p><h3>Common Mistakes to Avoid</h3><p>One of the biggest mistakes is assuming that correlation proves causation.</p><p>Another mistake is relying entirely on a statistical result without examining the actual data.</p><p>Outliers, measurement errors, small sample sizes, and unusual observations can influence results considerably.</p><p>Researchers should also avoid ignoring variables that may influence both variables being studied.</p><p>Finally, statistical significance should not automatically be treated as practical importance. A relationship may be statistically detectable but too small to have meaningful real-world consequences.</p><h3>Final Thoughts</h3><p>Associated variable analysis helps us move beyond simply describing data.</p><p>Instead of asking only, <strong>“What happened?”</strong>, we can begin asking, <strong>“How are these factors connected?”</strong></p><p>Understanding these connections is important in research, business, education, healthcare, economics, and everyday decision-making.</p><p>The process can reveal positive relationships, negative relationships, or cases where no meaningful association exists.</p><p>Yet interpreting those relationships responsibly is just as important as discovering them.</p><p>A statistical association can point us toward an important pattern, but it does not automatically explain the reason behind that pattern.</p><p>Good data analysis therefore combines statistical techniques with logical reasoning, subject knowledge, and careful interpretation.</p><p>That is what turns numbers into meaningful insight.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2b4de4a4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Layers I Mistook for Me]]></title>
            <link>https://medium.com/@isjustabhi/the-layers-i-mistook-for-me-3e5b96c34d11?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5b96c34d11</guid>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 00:13:23 GMT</pubDate>
            <atom:updated>2026-06-13T00:13:23.875Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I spent years thinking I was my thoughts. Turns out that was only the third layer in.</blockquote><p>A while ago I wrote that for most of my life, I thought I was my thoughts.</p><p>I still believe that was an important thing to notice. But lately I’ve been sitting with an old idea that takes it further, and honestly, it humbled me a little. Because it turns out the mind isn’t even the first thing I confused for myself.</p><p>There’s a map for this, very old, from the Taittiriya Upanishad. It says a human being is made of layers. Sheaths, they call them. Koshas. Each one wrapped around the next, like a lamp sitting inside a series of lampshades. And the work of a lifetime, maybe of many lifetimes, is to slowly realize that you are the lamp, not any of the shades.</p><p>Let me walk you through the layers the way I’ve actually met them.</p><h3>The body</h3><p>The outermost layer is the <strong>Annamaya kosha.</strong> The sheath made of food.</p><p>That name is not poetry. It’s literal. This body is built from the food you eat, and before that, the food your mother ate while you were forming inside her. The rice becomes blood. The blood becomes flesh, bone, marrow. You are, quite plainly, walking, breathing food.</p><p>For a long stretch of my life, this was simply <em>me.</em> I am this face. This weight. This tiredness. When the body felt good, I felt like a good person. When it didn’t, I felt like a failure. I never once questioned it. It didn’t feel like a layer. It felt like the whole of me.</p><h3>The breath</h3><p>Just beneath it is the <strong>Pranamaya kosha.</strong> The energy that animates the body. The breath, the life-force, the thing that leaves when a person dies and turns the body back into ordinary matter.</p><p>You can feel this layer if you’ve ever sat still and just followed your breath. There’s a body, yes, but there’s also something moving through it, keeping it lit. And you start to sense, quietly, that you are not the lamp’s glass. You might be closer to the flame.</p><h3>The mind</h3><p>Then comes the <strong>Manomaya kosha.</strong> The mind. The thoughts, the moods, the endless commentary. The place where “I” and “mine” are manufactured, where fear and craving and the old stories live.</p><p>This is the layer I got stuck on for years, the one I finally started catching myself believing. And it’s a strange relief to learn it was never the deepest thing about me. It’s the third shade in, not the lamp.</p><h3>The one that understands</h3><p>Beneath the noisy mind is the <strong>Vijnanamaya kosha.</strong> The sheath of intellect and discernment. Not the chatter, but the quieter knowing underneath it. The part that can watch a thought arise and gently say, <em>that one isn’t true.</em></p><p>I think this is the layer that does the actual unlearning. It’s the witness the spiritual teachers kept pointing me toward, the one I said I wasn’t ready to meet yet. I’m still not sure I am. But I can feel it now, faintly, underneath the mind I used to drown in.</p><h3>The bliss</h3><p>And deeper still, the <strong>Anandamaya kosha.</strong> The sheath of bliss. The quiet, causeless joy you brush against in dreamless sleep, or in a moment of stillness so complete that for a second there’s nothing to fix and nowhere to run.</p><p>Not happiness <em>about</em> something. Just peace, with no reason attached. The kind of contentment that doesn’t depend on the day going well.</p><h3>Why this undid me a little</h3><p>Here is the part that stayed with me.</p><p>The whole point of the map is that you are <em>none</em> of these layers. Not the body, not the breath, not the mind, not even the intellect or the bliss. They are all coverings. What you are is the awareness they wrap around, the lamp inside the shades.</p><p>And most of us, the old text says gently, never get past the very first one. We spend a whole life, maybe many, convinced we are the outermost shell, the body made of food, chasing comfort and validation and the next thing, never once suspecting there are four more layers in, and then something quieter still beneath all of them.</p><p>That was me. That has been me.</p><p>So when people ask why I keep talking about the mind, this is part of the answer now. I’m not even trying to reach the deepest layer yet. I’m just slowly working inward, one sheath at a time, setting down each thing I mistook for myself.</p><p>I started by realizing I am not my body.</p><p>Then, that I am not my thoughts.</p><p>I don’t know how far in I’ll get in this life. But for the first time, I know which direction is in.</p><p>And that, for now, is enough.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5b96c34d11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG App Keeps Missing the Right Answer. Here’s Why.]]></title>
            <link>https://medium.com/@isjustabhi/your-rag-app-keeps-missing-the-right-answer-heres-why-c8ec691fcaec?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ec691fcaec</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 17:35:53 GMT</pubDate>
            <atom:updated>2026-06-06T17:35:53.373Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of 10, Becoming an AI Engineer</em></p><p>At the end of Part 2 I gave you homework: point your PDF app at a real document and find the question where it fails. If you did it, you found one. Maybe the answer was right there on page 12 and the app swore it didn’t exist.</p><p>That failure isn’t a bug in your code. It’s the limit of how vector search actually works, and understanding that limit is what turns a RAG demo into a RAG system you can trust. So let’s break search on purpose and see what’s really going on.</p><h3>What an embedding actually captures</h3><p>We said an embedding turns text into a vector, a list of numbers, and that similar meanings get similar vectors. True, but the word “similar” is doing a lot of quiet work.</p><p>Picture every chunk of text as an arrow in space. Not 2D or 3D space, but a space with hundreds or thousands of dimensions. The embedding model learned, from enormous amounts of text, to point arrows about related topics in roughly the same direction. “Refund,” “money back,” and “reimbursement” all aim the same way, even though they share no letters.</p><p>Cosine similarity, the thing we computed in Part 2, just measures the angle between two arrows. Small angle, similar meaning. That’s the whole engine. And here’s the catch that bites everyone: the model decides what “meaning” means. It’s optimized for general topical closeness, not for whatever your specific question cares about.</p><h3>Why naive search misses</h3><p>Two failure modes show up constantly. Both are worth feeling in your hands.</p><p>The first is paraphrase distance. If your question is worded very differently from the source text, the arrows can drift apart enough to fall out of the top results, even when they’re about the same thing. A short embedding model has a coarser sense of meaning, so this happens more often.</p><p>The second is the one that really stings: exact terms. Embeddings are built to blur surface details in favor of meaning, which is usually what you want. But it means a product code like “X-440,” an order number, a person’s name, or a specific clause reference gets smeared into “some identifier.” Ask “what does error code E-17 mean” and a pure vector search may happily hand you the chunk about error E-19, because to the embedding they look almost identical.</p><p>The fix for that second problem is hybrid search: run a keyword search alongside the vector search and blend the scores. Keyword search nails exact tokens, vector search nails meaning, and together they cover each other’s blind spots. Here’s the idea in miniature:</p><pre>def hybrid_score(query, chunk, vector_sim):<br>    query_words = set(query.lower().split())<br>    chunk_words = set(chunk.lower().split())<br>    keyword_overlap = len(query_words &amp; chunk_words) / max(len(query_words), 1)<br>    return 0.7 * vector_sim + 0.3 * keyword_overlap</pre><p>That’s a toy blend, not production weighting, but the principle holds: when meaning alone fails, exact tokens rescue you. Real systems use BM25 for the keyword half, which is smarter about rare words, but the intuition is exactly this.</p><h3>When numpy stops being enough</h3><p>In Part 2 we kept every vector in a numpy array and scanned all of them on each query. For a few hundred chunks that’s instant. Push it to a few hundred thousand and you’re comparing against every single vector on every query, which gets slow and memory-hungry fast.</p><p>That’s when you reach for a vector database. The short version of your options:</p><p>A library like FAISS lives inside your process and is brilliant for fast local search when you don’t need a server. Chroma is the easiest on-ramp for a small project and stores to disk so your index survives a restart. pgvector is a Postgres extension, which is the pragmatic pick if you already run Postgres and want your vectors next to your real data. Managed services like Pinecone hand you scaling and uptime so you don’t babysit infrastructure, at the cost of a monthly bill and less control.</p><p>There’s no universal best. For the PDF app, Chroma or pgvector covers you for a long time. Don’t reach for a managed cluster to search a hundred documents.</p><h3>The bake-off: do better embeddings actually matter?</h3><p>People argue about embedding models endlessly. Let’s stop arguing and measure. Here’s a tiny but honest evaluation. We take a small knowledge base, write questions where we know the correct answer, and check whether each model retrieves the right chunk first.</p><pre>from openai import OpenAI<br>import numpy as np<br>client = OpenAI()<br>docs = [<br>    &quot;Refunds are processed within 7 business days of approval.&quot;,<br>    &quot;The office is closed on all national holidays.&quot;,<br>    &quot;To reset your password, click &#39;Forgot password&#39; on the login screen.&quot;,<br>    &quot;Premium plans include 24/7 priority support from our team.&quot;,<br>    &quot;Shipping is free for any order above $50.&quot;,<br>]<br># Each query is paired with the index of the doc that should win.<br>eval_set = [<br>    (&quot;how long until I get my money back&quot;, 0),<br>    (&quot;I can&#39;t remember my login details&quot;, 2),<br>    (&quot;do you charge for delivery&quot;, 4),<br>    (&quot;can I get help in the middle of the night&quot;, 3),<br>]<br>def embed(texts, model):<br>    resp = client.embeddings.create(model=model, input=texts)<br>    return np.array([d.embedding for d in resp.data])<br>def normalize(m):<br>    return m / np.linalg.norm(m, axis=1, keepdims=True)<br>def recall_at_1(model):<br>    doc_vecs = normalize(embed(docs, model))<br>    hits = 0<br>    for query, correct in eval_set:<br>        q = normalize(embed([query], model))[0]<br>        ranking = np.argsort(doc_vecs @ q)[::-1]<br>        if ranking[0] == correct:<br>            hits += 1<br>    return hits / len(eval_set)<br>for model in [&quot;text-embedding-3-small&quot;, &quot;text-embedding-3-large&quot;]:<br>    print(f&quot;{model}: recall@1 = {recall_at_1(model):.2f}&quot;)</pre><p>The point isn’t the exact numbers you’ll get back. It’s the habit. The moment you have a labeled set of questions, picking a model stops being a vibe and becomes a measurement. On a hard set, the larger model usually edges out the smaller one on the questions phrased least like the source text, which are exactly the ones that were failing in your PDF app.</p><p>This little eval is also a tool you keep. Change your chunk size and re-run it. Add hybrid search and re-run it. Now every tweak has a number attached instead of a feeling.</p><h3>The honest trade-offs</h3><p>Bigger embedding models retrieve better and cost more, both in money per call and in latency. They also produce longer vectors, which take more storage and more time to compare. For a chatty support bot, the small model is often plenty. For dense legal or medical text where a single misread term matters, the large model earns its cost.</p><p>And no embedding model fixes bad chunks. If your chunker split the answer in half back in Part 2, no amount of search quality recovers it. Retrieval quality is a chain, and the weakest link decides the result.</p><h3>What’s next</h3><p>You now know why search misses, how to blend keyword and vector to fix it, when to graduate from numpy to a real database, and how to measure a model instead of guessing. That’s the retrieval half of RAG handled with eyes open.</p><p>Here’s the thing though: everything we’ve built still lives in a script you run from your terminal. Nobody else can use it. In <strong>Part 4</strong> we change that. We’ll wrap the whole PDF app in a FastAPI backend with a real /chat endpoint that streams answers token by token, the way a proper product feels. That&#39;s the jump from notebook to something you can actually ship.</p><blockquote>Before then, build the eval set for your own documents. Even five labeled questions will tell you more about your system than a week of guessing.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ec691fcaec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Pasted an 80-Page PDF Into ChatGPT. There’s a Much Better Way.]]></title>
            <link>https://medium.com/@isjustabhi/i-pasted-an-80-page-pdf-into-chatgpt-theres-a-much-better-way-e476fe50fc1c?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e476fe50fc1c</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 12:57:19 GMT</pubDate>
            <atom:updated>2026-06-05T12:57:19.625Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of 10, Becoming an AI Engineer</em></p><p>In Part 1 we got the model to return clean, structured data. But it had one painful limit: it only knows what it learned during training. Ask it about your company handbook, your meeting notes, last quarter’s report, and it will either shrug or, worse, invent a confident answer that sounds exactly right and is completely wrong.</p><p>My first instinct was the obvious one. I copied an 80-page policy PDF straight into the prompt and asked my question. The model choked on the length, the call cost more than I’d like to admit, and the answer still missed a detail buried on page 60.</p><p>There’s a cleaner way, and it has a name you’ve probably heard thrown around: RAG. Retrieval-Augmented Generation. By the end of this article you’ll have built a working version yourself, no framework required, so you actually understand what’s happening under the hood.</p><h3>The idea, in one sentence</h3><p>Don’t make the model memorize your documents. Hand it the right page at the moment you ask the question.</p><p>Think of it as the difference between a closed-book and an open-book exam. A closed-book exam tests what you crammed. An open-book exam lets you look things up. RAG turns every question into an open-book exam: before the model answers, we find the few chunks of your document most relevant to the question and paste only those into the prompt.</p><p>That solves all three of my problems at once. We never send the whole PDF, so cost and length stay sane. We send the most relevant part, so accuracy goes up. And because the model is answering from text we provided, we can tell it to admit when the answer isn’t there instead of making one up.</p><h3>The four moving parts</h3><p>Every RAG system, no matter how fancy, is these four steps:</p><ol><li><strong>Load</strong> the raw text out of your document.</li><li><strong>Chunk</strong> it into bite-sized pieces.</li><li><strong>Embed and store</strong> those chunks so we can search them by meaning.</li><li><strong>Retrieve and answer</strong>: find the best chunks for a question, then generate a reply from them.</li></ol><p>We’ll build each one. Here’s everything you need installed:</p><pre>pip install openai pypdf numpy</pre><pre>from openai import OpenAI<br>from pypdf import PdfReader<br>import numpy as np<br><br>client = OpenAI()</pre><h3>Step 1: Get the text out</h3><p>PDFs are a mess to parse, so we lean on pypdf to pull plain text from every page.</p><pre>def load_pdf(path):<br>    reader = PdfReader(path)<br>    return &quot;\n&quot;.join(page.extract_text() or &quot;&quot; for page in reader.pages)</pre><p>The or &quot;&quot; matters more than it looks. Scanned or image-heavy pages return None, and one None in the middle will crash the join. Small defensive habits like this are the difference between code that demos and code that survives a weird input.</p><h3>Step 2: Chunk it</h3><p>You can’t search a wall of text, and you can’t paste a whole book into a prompt. So we slice the document into overlapping windows.</p><pre>def chunk_text(text, size=800, overlap=150):<br>    chunks = []<br>    start = 0<br>    while start &lt; len(text):<br>        chunks.append(text[start:start + size])<br>        start += size - overlap<br>    return chunks</pre><p>Two decisions worth understanding. <strong>Size</strong> controls how much context each chunk carries: too small and a chunk loses its meaning, too big and retrieval gets vague. <strong>Overlap</strong> stops you from slicing a sentence clean in half and losing the answer at the seam. 800 characters with 150 of overlap is a fine starting point, not a law.</p><p>I’ll be honest with you: this is the crudest possible chunker. It cuts by character count with zero respect for sentences or paragraphs. It works surprisingly well for a first build, and it’s also the first thing you’ll improve later. We’ll come back to that.</p><h3>Step 3: Turn text into searchable meaning</h3><p>Here’s the part that feels like magic the first time. An embedding model takes a piece of text and returns a long list of numbers, a vector, that captures its meaning. Texts about similar things end up with similar vectors, even if they share no words. “How do I reset my password” and “I forgot my login” land close together.</p><pre>def embed(texts):<br>    resp = client.embeddings.create(<br>        model=&quot;text-embedding-3-small&quot;,<br>        input=texts,<br>    )<br>    return np.array([d.embedding for d in resp.data])</pre><p>We embed every chunk once, up front, and keep the vectors in memory:</p><pre>text = load_pdf(&quot;handbook.pdf&quot;)<br>chunks = chunk_text(text)<br>chunk_vectors = embed(chunks)</pre><p>That chunk_vectors array is our entire search index. Real systems push this into a dedicated vector database, but for a few hundred chunks a numpy array in memory is genuinely fine, and it lets you see exactly what&#39;s going on.</p><h3>Step 4: Search by meaning, then answer</h3><p>To find the right chunks for a question, we embed the question the same way, then measure which chunk vectors point in the most similar direction. That measurement is cosine similarity, and it’s just a dot product of normalized vectors.</p><pre>def search(question, k=4):<br>    q_vec = embed([question])[0]<br>    sims = (chunk_vectors @ q_vec) / (<br>        np.linalg.norm(chunk_vectors, axis=1) * np.linalg.norm(q_vec)<br>    )<br>    top = np.argsort(sims)[-k:][::-1]<br>    return [chunks[i] for i in top]</pre><p>We grab the top k most similar chunks. Now the final step: hand those chunks to the model and ask it to answer using only them.</p><pre>def ask(question):<br>    context = &quot;\n\n&quot;.join(search(question))<br>    prompt = f&quot;&quot;&quot;Answer the question using only the context below.<br>If the answer is not in the context, say you don&#39;t know.<br><br>Context:<br>{context}<br><br>Question: {question}&quot;&quot;&quot;<br><br>    resp = client.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        temperature=0,<br>    )<br>    return resp.choices[0].message.content</pre><p>That’s the whole app:</p><pre>print(ask(&quot;How many vacation days do new employees get?&quot;))</pre><p>Notice the prompt instruction borrowed straight from Part 1: “say you don’t know.” That single line is what turns a confident liar into a tool you can trust. Without it, the model fills gaps with fiction. With it, you get a clean “I don’t know” when the retrieval missed, which is exactly the signal you want.</p><h3>Where this honestly falls short</h3><p>It would be dishonest to pretend this is production-grade, so let me name the cracks before you find them the hard way.</p><p>The chunker is blunt and will sometimes split a key sentence across two chunks. The retrieval is only as good as the embedding, so a question phrased very differently from the source text can miss. There’s no handling for “the answer needs three scattered chunks but we only fetched the top four.” And the whole index lives in memory, so it vanishes when the script stops and won’t scale past a few thousand chunks.</p><p>None of that makes this useless. It makes it a foundation. Every one of those cracks has a known fix, and the fixes are what separate a weekend demo from something a team relies on.</p><h3>What’s next</h3><p>You now have a working RAG pipeline you understand line by line, which is worth ten you copied from a framework and can’t debug.</p><p>The weakest link in what we built is Step 3 and 4: how we turn text into vectors and how we search them. That’s where retrieval quality is won or lost. In <strong>Part 3</strong> we go deep on exactly that. We’ll look at what embeddings really capture, why naive cosine search fails on certain questions, how to pick a real vector database, and we’ll run two embedding models head to head on the same documents so you can see the quality gap for yourself.</p><blockquote>Before then, point this script at one of your own PDFs and ask it ten questions. Find the one where it fails. That failure is your Part 3 homework.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e476fe50fc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Asking ChatGPT Nicely. Start Engineering Your Prompts.]]></title>
            <link>https://medium.com/@isjustabhi/stop-asking-chatgpt-nicely-start-engineering-your-prompts-2ba1d18d30e9?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ba1d18d30e9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 12:48:33 GMT</pubDate>
            <atom:updated>2026-06-05T12:48:33.821Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of 10, Becoming an AI Engineer</em></p><p>The first time I shipped a feature powered by an LLM, it worked beautifully in the demo. Then it hit real users and started returning answers wrapped in friendly little sentences like “Sure! Here’s the JSON you asked for:” which promptly crashed my parser at 2 a.m.</p><p>That night taught me something the tutorials skip. Prompting isn’t about being polite to a chatbot. It’s the first real engineering skill in the stack, and most people never get past treating it like a search box.</p><p>Let me show you what actually changes when you stop asking and start engineering.</p><h3>What’s really happening when you type a prompt</h3><p>Here’s the mental model that fixed my thinking. A language model doesn’t “understand” your request and then decide how to reply. It predicts the next most likely chunk of text, one piece at a time, based on everything before it.</p><p>That’s the whole trick. Your prompt isn’t a command. It’s a set of conditions that nudge the model toward some continuations and away from others. When you write “Sure! Here’s the JSON,” guess what the model decided was a likely next thing to say? Exactly what it copied from a million blog posts that opened the same way.</p><p>So the job isn’t to ask harder. It’s to set conditions so tightly that the answer you want becomes the most probable thing the model can say. Once that clicked, my prompts stopped being requests and started being specs.</p><h3>The example we’ll build: turning messy text into clean data</h3><p>Forget toy examples. Here’s a job you’ll do constantly as an AI engineer: take unstructured human text and pull structured data out of it.</p><p>Say you run a support inbox and you want to auto-route tickets. A real message looks like this:</p><pre>hey so my order #44812 still hasnt shipped and its been like 9 days,<br>this is the second time this happened tbh getting pretty annoyed.<br>need this before friday for a gift</pre><p>You want this back, every single time, with no surprises:</p><pre>{<br>  &quot;order_id&quot;: &quot;44812&quot;,<br>  &quot;sentiment&quot;: &quot;frustrated&quot;,<br>  &quot;priority&quot;: &quot;high&quot;,<br>  &quot;deadline&quot;: &quot;Friday&quot;<br>}</pre><p>Sounds easy. The naive version will betray you anyway. Watch.</p><h3>Attempt one: the way everyone starts</h3><pre>from openai import OpenAI<br><br>client = OpenAI()<br><br>email = &quot;&quot;&quot;hey so my order #44812 still hasnt shipped and its been like 9 days,<br>this is the second time this happened tbh getting pretty annoyed.<br>need this before friday for a gift&quot;&quot;&quot;<br>response = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;,<br>         &quot;content&quot;: f&quot;Extract the order id, sentiment, priority and deadline from this email:\n\n{email}&quot;}<br>    ],<br>)<br>print(response.choices[0].message.content)</pre><p>This runs. It even looks like it works. But you’ll get prose, a paragraph that <em>describes</em> the fields instead of giving you data you can use. Sometimes you’ll get a bulleted list. Sometimes a polite intro. Three runs, three shapes. You can’t build on that.</p><p>The problem isn’t the model. It’s that I never told it what “done” looks like.</p><h3>Attempt two: describe the output, not just the task</h3><p>Two changes make a huge difference. First, give the model a role so it stops defaulting to chatty-assistant mode. Second, show the exact shape you want.</p><pre>SYSTEM = &quot;&quot;&quot;You are a data extraction service. You receive a support email<br>and return only a JSON object. No prose, no greetings, no markdown.<br><br>Schema:<br>{<br>  &quot;order_id&quot;: string or null,<br>  &quot;sentiment&quot;: one of [&quot;happy&quot;, &quot;neutral&quot;, &quot;frustrated&quot;, &quot;angry&quot;],<br>  &quot;priority&quot;: one of [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;],<br>  &quot;deadline&quot;: string or null<br>}&quot;&quot;&quot;<br><br>response = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: email},<br>    ],<br>)</pre><p>Now you’ll get JSON most of the time. Notice the constraints doing the heavy lifting: I didn’t say “be accurate,” I gave the model a fixed menu for sentiment and priority. A free-text field invites creativity. An enum kills it. That&#39;s the difference between hoping and specifying.</p><p>But “most of the time” is the phrase that ruins production. You’ll still hit the occasional ```json fence wrapped around the output, or a stray “Here you go.” So we go one level deeper.</p><h3>Attempt three: stop trusting, start enforcing</h3><p>This is the part the beginner tutorials almost never reach, and it’s the actual skill. You don’t <em>ask</em> for valid JSON. You make valid JSON the only possible output.</p><p>Most modern APIs support a structured-output mode that constrains generation to a schema you define. Here’s the same job using a Pydantic model as the contract:</p><pre>from pydantic import BaseModel<br>from typing import Optional, Literal<br><br>class Ticket(BaseModel):<br>    order_id: Optional[str]<br>    sentiment: Literal[&quot;happy&quot;, &quot;neutral&quot;, &quot;frustrated&quot;, &quot;angry&quot;]<br>    priority: Literal[&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;]<br>    deadline: Optional[str]<br>response = client.beta.chat.completions.parse(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Extract ticket data from the support email.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: email},<br>    ],<br>    response_format=Ticket,<br>)<br>ticket = response.choices[0].message.parsed<br>print(ticket.priority)   # &quot;high&quot;, a real Python object, guaranteed to fit</pre><p>Now the model physically can’t hand you a stray apology or a broken brace. The schema is enforced during generation, and you get back a typed object instead of a string you have to pray over. My 2 a.m. parser crash is now impossible by construction.</p><p>Here’s the honest part though: this isn’t free. Constrained output can occasionally make the model less fluent on genuinely ambiguous inputs, because you’ve taken away its room to say “I’m not sure.” So you still design the schema to absorb uncertainty. That’s why order_id and deadline are nullable, and why sentiment has a neutral escape hatch. The model needs a legal way to say &quot;I don&#39;t know&quot; or it&#39;ll guess.</p><h3>When to reach for few-shot examples</h3><p>Sometimes the schema isn’t the hard part. The <em>judgment</em> is. If “high priority” means something specific to your business, the model can’t read your mind. So show it.</p><pre>EXAMPLES = &quot;&quot;&quot;<br>Email: &quot;love the product, just checking when v2 drops&quot;<br>-&gt; {&quot;sentiment&quot;: &quot;happy&quot;, &quot;priority&quot;: &quot;low&quot;}<br><br>Email: &quot;this is the third broken unit, I want a refund today&quot;<br>-&gt; {&quot;sentiment&quot;: &quot;angry&quot;, &quot;priority&quot;: &quot;high&quot;}<br>&quot;&quot;&quot;</pre><p>Two or three sharp examples will teach a rule faster than a paragraph of instructions ever could. But don’t overdo it. Every example you paste in costs tokens on every single call, and ten examples rarely beat three well-chosen ones. I usually start with zero examples, find the cases where the model gets it wrong, and add an example for exactly that failure. Targeted, not exhaustive.</p><h3>The one setting nobody mentions</h3><p>For extraction work like this, turn the temperature down. Temperature controls how much randomness the model allows when picking each next token. High temperature is great for brainstorming and terrible for data you need to be identical across runs.</p><pre>response = client.beta.chat.completions.parse(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[...],<br>    response_format=Ticket,<br>    temperature=0,<br>)</pre><p>At temperature=0 you get near-deterministic output, the same email maps to the same JSON. For creative writing you&#39;d crank it up. Knowing which knob to turn for which job is half of what prompting actually is.</p><h3>What you should take from this</h3><p>Prompting badly looks like typing a question and hoping. Prompting like an engineer looks like defining the output, constraining the choices, enforcing the contract in code, and tuning for the job. Same model, completely different reliability.</p><p>That’s the foundation. But a model can only work with what it already knows, and right now ours knows nothing about <em>your</em> data, your docs, your last week of support tickets. Ask it about your internal pricing and it’ll confidently make something up.</p><p>In <strong>Part 2</strong>, we fix that. We’ll build a RAG pipeline that lets the model answer from your own documents. The project will be a working “chat with your PDFs” app, and it’s where this series starts getting genuinely fun.</p><blockquote>Try the ticket extractor on your own messy text before then. Break it on purpose. The failures are where you’ll learn the most.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ba1d18d30e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Keep Talking About the Mind]]></title>
            <link>https://medium.com/@isjustabhi/why-i-keep-talking-about-the-mind-0f4d28a17815?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f4d28a17815</guid>
            <category><![CDATA[emotions]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[stories]]></category>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[fear]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Sun, 31 May 2026 20:17:09 GMT</pubDate>
            <atom:updated>2026-05-31T20:17:09.930Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Someone asked me why I don’t talk about the deeper things. This is my honest answer.</strong></blockquote><p>Today someone asked me,</p><p>“Why do you keep talking about the mind?</p><p>Why not talk about deeper things?</p><p>Meditation. The witness. Who you really are?”</p><p>And honestly, maybe the reason I keep talking about the mind is simple.</p><p>For most of my life, I thought I was it.</p><p>I thought I was my thoughts.</p><p>My fears.</p><p>My emotions.</p><p>My reactions.</p><p>My stories.</p><p>It never felt like a costume I was wearing. It felt like skin.</p><p>So right now, I’m not in a hurry to understand who the witness is. I’m still learning something far more basic than that. I’m still learning that I am not everything my mind tells me.</p><p>And for me, that is deep enough.</p><p>Maybe one day I’ll understand more. Maybe one day the bigger questions will matter. But right now, I’m not interested in collecting answers.</p><p>I’m interested in unlearning.</p><p>Unlearning the patterns.</p><p>The fears.</p><p>The beliefs.</p><p>And the identities I spent years calling “me.”</p><p>Because for most of my life, I was running.</p><p>Running after people.</p><p>Running after validation.</p><p>Running after love.</p><p>Running after the next thing.</p><p>And then the next. And then the next. Certain that the one after that would finally be enough.</p><p>It never was.</p><p>And for the first time, I don’t want to run.</p><p>I just want to sit. Observe. And slowly understand what I’ve been living through all these years, instead of rushing past it to get somewhere better.</p><p>People assume that talking about the mind means you’re stuck in it. As if the goal is to climb past it as fast as you can and arrive somewhere more enlightened.</p><p>But maybe it’s the opposite.</p><p>Maybe I’m not talking about the mind because I’m stuck there.</p><p>Maybe I’m talking about it because I’m finally seeing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f4d28a17815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RAG End to End: From Zero to a Production Pipeline (With Code)]]></title>
            <link>https://medium.com/@isjustabhi/building-rag-end-to-end-from-zero-to-a-production-pipeline-with-code-8d710b40447b?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d710b40447b</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Fri, 29 May 2026 10:40:57 GMT</pubDate>
            <atom:updated>2026-05-29T10:40:57.953Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I’ve shipped retrieval systems that answer questions over millions of documents. Here is everything that actually matters, built up one honest layer at a time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MuZeSlzFTW0qNRXNNhLxQ.png" /></figure><p>Most RAG tutorials hand you a LangChain one-liner, the demo works on three PDFs, and then it falls apart the moment you point it at real data. The problem is that the one-liner hides the four or five decisions that decide whether your system is good or garbage.</p><p>So we are going to do the opposite. We will build RAG from scratch with nothing but NumPy and an embedding model, so you understand every moving part. Then we will swap each hand-rolled piece for the production-grade version and talk about why. By the end you will have a pipeline you actually understand, plus the judgment to debug it when retrieval quietly starts returning nonsense.</p><p>Let’s go.</p><h3>What RAG actually is (in one paragraph)</h3><p>A language model only knows what was in its training data. RAG, Retrieval-Augmented Generation, fixes that by doing a search over <em>your</em> documents at question time, pasting the most relevant snippets into the prompt, and asking the model to answer using them. That’s it. The “intelligence” of a RAG system lives almost entirely in the retrieval step, not the model. Get retrieval right and a cheap model looks brilliant. Get it wrong and the best model on earth will confidently make things up.</p><p>Here is the whole architecture on one screen:</p><pre>INDEXING (done once, offline)<br>  ┌──────────┐   ┌─────────┐   ┌────────────┐   ┌──────────────┐<br>  │ Raw docs │ → │  Chunk  │ → │   Embed    │ → │ Vector store │<br>  └──────────┘   └─────────┘   └────────────┘   └──────────────┘</pre><pre>                    QUERYING (done per question, online)<br>  ┌──────────┐   ┌────────────┐   ┌────────────┐   ┌─────────────┐   ┌────────┐<br>  │ Question │ → │   Embed    │ → │  Retrieve  │ → │ Build prompt│ → │  LLM   │<br>  └──────────┘   └────────────┘   │  top-k     │   │ (ctx + Q)   │   │ answer │<br>                                   └────────────┘   └─────────────┘   └────────┘</pre><p>Five components. We’ll build each one.</p><h3>Setup</h3><pre>pip install sentence-transformers numpy anthropic</pre><p>I’m deliberately using sentence-transformers for embeddings so you can run this with zero API keys and watch it work on your laptop. We&#39;ll talk about hosted embedding providers later, because that&#39;s the right call in production. For generation I&#39;ll use Claude, but the prompt-building logic is identical for any model.</p><pre>export ANTHROPIC_API_KEY=&quot;your-key-here&quot;</pre><h3>Part 1: Loading and chunking (where most systems are won or lost)</h3><p>You cannot feed a 40-page document to an embedding model and expect good retrieval. Embeddings compress meaning into a single vector, and a single vector cannot represent forty pages of distinct ideas. So you split documents into <strong>chunks</strong>, embed each chunk, and retrieve at the chunk level.</p><p>The naive approach is to split every N characters. The problem is it slices sentences in half and destroys meaning at the boundaries. A better baseline is to split on natural boundaries (paragraphs, then sentences) and add <strong>overlap</strong> so an idea that straddles a boundary still survives intact in at least one chunk.</p><pre>import re<br><br>def chunk_text(text, chunk_size=500, overlap=50):<br>    &quot;&quot;&quot;Split text into overlapping chunks on sentence boundaries.<br>    chunk_size and overlap are measured in characters here for clarity.<br>    In production, measure in tokens (see notes at the end).<br>    &quot;&quot;&quot;<br>    # Split into sentences without breaking on abbreviations too aggressively.<br>    sentences = re.split(r&#39;(?&lt;=[.!?])\s+&#39;, text.strip())<br>    chunks = []<br>    current = &quot;&quot;<br>    for sentence in sentences:<br>        # If adding this sentence would overflow, close the current chunk.<br>        if len(current) + len(sentence) &gt; chunk_size and current:<br>            chunks.append(current.strip())<br>            # Start the next chunk with the tail of the previous one (overlap).<br>            current = current[-overlap:] + &quot; &quot; + sentence<br>        else:<br>            current += &quot; &quot; + sentence<br>    if current.strip():<br>        chunks.append(current.strip())<br>    return chunks</pre><p>Why overlap matters in one sentence: if the answer to a question is split across a chunk boundary, overlap is the difference between retrieving it and missing it entirely.</p><p>A small but real refinement: keep metadata with every chunk. You will want it later for citations and filtering.</p><pre>def load_and_chunk(documents):<br>    &quot;&quot;&quot;documents: list of dicts like {&quot;id&quot;: &quot;doc1&quot;, &quot;text&quot;: &quot;...&quot;}&quot;&quot;&quot;<br>    corpus = []<br>    for doc in documents:<br>        for i, chunk in enumerate(chunk_text(doc[&quot;text&quot;])):<br>            corpus.append({<br>                &quot;text&quot;: chunk,<br>                &quot;source&quot;: doc[&quot;id&quot;],<br>                &quot;chunk_index&quot;: i,<br>            })<br>    return corpus</pre><h3>Part 2: Embeddings (turning text into searchable geometry)</h3><p>An embedding model maps text to a fixed-length vector such that texts with similar meaning land close together in space. “How do I reset my password?” and “I forgot my login credentials” will sit near each other even though they share no words. That semantic matching is the entire reason RAG beats keyword search for natural-language questions.</p><pre>from sentence_transformers import SentenceTransformer<br>import numpy as np<br># A small, fast, genuinely good model. 384-dimensional vectors.<br>embedder = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>def embed(texts):<br>    &quot;&quot;&quot;Return an (n, dim) array of L2-normalized embeddings.&quot;&quot;&quot;<br>    vectors = embedder.encode(texts, convert_to_numpy=True)<br>    # Normalize so that dot product == cosine similarity. This matters.<br>    norms = np.linalg.norm(vectors, axis=1, keepdims=True)<br>    return vectors / np.clip(norms, 1e-12, None)</pre><p>The normalization trick is worth internalizing: once vectors are unit-length, cosine similarity is just a dot product, which lets us score the entire corpus with a single fast matrix multiply.</p><h3>Part 3: The vector store, built from scratch</h3><p>A vector store does one job: given a query vector, find the most similar stored vectors fast. The real ones (FAISS, Chroma, pgvector, Pinecone) use clever indexes to do this at billion-scale. But the core idea is fifteen lines of NumPy, and you should see it once with your own eyes.</p><pre>class TinyVectorStore:<br>    def __init__(self):<br>        self.vectors = None   # (n, dim) matrix<br>        self.payloads = []    # parallel list of chunk dicts<br><br>    def add(self, vectors, payloads):<br>        self.vectors = vectors if self.vectors is None \<br>            else np.vstack([self.vectors, vectors])<br>        self.payloads.extend(payloads)<br><br>    def search(self, query_vector, k=4):<br>        # Cosine similarity == dot product, because everything is normalized.<br>        scores = self.vectors @ query_vector<br>        # argpartition is O(n); we only need the top-k, not a full sort.<br>        top_idx = np.argpartition(-scores, range(k))[:k]<br>        top_idx = top_idx[np.argsort(-scores[top_idx])]<br>        return [(self.payloads[i], float(scores[i])) for i in top_idx]</pre><p>That @ is the whole search engine. Every nearest-neighbor library on the planet is an optimization of this one matrix multiply.</p><h3>Part 4: Retrieval, wired together</h3><p>Now indexing and querying become almost trivial.</p><pre>store = TinyVectorStore()<br><br>def index(documents):<br>    corpus = load_and_chunk(documents)<br>    vectors = embed([c[&quot;text&quot;] for c in corpus])<br>    store.add(vectors, corpus)<br>    print(f&quot;Indexed {len(corpus)} chunks.&quot;)<br><br>def retrieve(question, k=4):<br>    q_vec = embed([question])[0]<br>    return store.search(q_vec, k=k)</pre><h3>Part 5: Generation (the easy part everyone overcomplicates)</h3><p>Here is the secret about the LLM step: it is a glorified string template. You retrieve context, paste it into a prompt with strict instructions, and the model writes the answer. The two things that matter are (1) telling the model to answer <em>only</em> from the context, and (2) telling it to admit when the context doesn’t contain the answer. That second instruction is your single best defense against hallucination.</p><pre>from anthropic import Anthropic<br><br>client = Anthropic()<br><br>SYSTEM_PROMPT = (<br>    &quot;You answer questions strictly using the provided context. &quot;<br>    &quot;If the context does not contain the answer, say so plainly. &quot;<br>    &quot;Cite the source id in brackets after each claim, like [doc1].&quot;<br>)<br><br>def generate(question, retrieved):<br>    context = &quot;\n\n&quot;.join(<br>        f&quot;[{p[&#39;source&#39;]}] {p[&#39;text&#39;]}&quot; for p, _ in retrieved<br>    )<br>    user_message = f&quot;Context:\n{context}\n\nQuestion: {question}&quot;<br><br>    response = client.messages.create(<br>        model=&quot;claude-sonnet-4-6&quot;,<br>        max_tokens=1024,<br>        system=SYSTEM_PROMPT,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_message}],<br>    )<br>    return response.content[0].text</pre><h3>Part 6: The complete pipeline</h3><p>Wrap it in one object and you have a working RAG system in well under a hundred lines.</p><pre>class RAG:<br>    def __init__(self):<br>        self.store = TinyVectorStore()<br><br>    def index(self, documents):<br>        corpus = load_and_chunk(documents)<br>        vectors = embed([c[&quot;text&quot;] for c in corpus])<br>        self.store.add(vectors, corpus)<br><br>    def ask(self, question, k=4):<br>        q_vec = embed([question])[0]<br>        retrieved = self.store.search(q_vec, k=k)<br>        answer = generate(question, retrieved)<br>        sources = [p[&quot;source&quot;] for p, _ in retrieved]<br>        return {&quot;answer&quot;: answer, &quot;sources&quot;: sources}<br><br><br># Run it<br>docs = [<br>    {&quot;id&quot;: &quot;handbook&quot;, &quot;text&quot;: open(&quot;employee_handbook.txt&quot;).read()},<br>    {&quot;id&quot;: &quot;policy&quot;,   &quot;text&quot;: open(&quot;security_policy.txt&quot;).read()},<br>]<br><br>rag = RAG()<br>rag.index(docs)<br><br>result = rag.ask(&quot;How many vacation days do new employees get?&quot;)<br>print(result[&quot;answer&quot;])<br>print(&quot;Sources:&quot;, result[&quot;sources&quot;])</pre><p>That is a real, functioning RAG system. Run it, confirm it works, and now let’s make it good enough to put in front of users.</p><h3>Going to production: the upgrades that actually move the needle</h3><p>The toy above will embarrass you on real data. Here is what to fix, in priority order, because not all improvements are equal.</p><h3>1. Swap the embedding model and store</h3><p>For anything beyond a prototype, move embeddings to a hosted, higher-quality model and your vectors into a real database. Anthropic does not ship its own embedding model and points users to Voyage AI as its preferred provider, though OpenAI, Google, and Cohere all produce strong embeddings too. Pick based on quality on <em>your</em> data, latency, and cost.</p><pre>import voyageai<br><br>vo = voyageai.Client()<br><br>def embed_voyage(texts, input_type=&quot;document&quot;):<br>    # input_type=&quot;query&quot; for questions, &quot;document&quot; for stored chunks.<br>    # Asymmetric embedding meaningfully improves retrieval quality.<br>    result = vo.embed(texts, model=&quot;voyage-3&quot;, input_type=input_type)<br>    return np.array(result.embeddings)</pre><p>That input_type distinction is a free quality win most people miss: embedding questions and documents with different modes lets the model optimize each side of the match.</p><p>For storage, Chroma is the gentlest on-ramp and runs locally or as a server:</p><pre>import chromadb<br><br>client = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br>collection = client.get_or_create_collection(&quot;docs&quot;)<br><br># Indexing<br>collection.add(<br>    ids=[f&quot;{c[&#39;source&#39;]}-{c[&#39;chunk_index&#39;]}&quot; for c in corpus],<br>    documents=[c[&quot;text&quot;] for c in corpus],<br>    metadatas=[{&quot;source&quot;: c[&quot;source&quot;]} for c in corpus],<br>    embeddings=embed_voyage([c[&quot;text&quot;] for c in corpus]).tolist(),<br>)<br><br># Querying<br>hits = collection.query(<br>    query_embeddings=embed_voyage([question], input_type=&quot;query&quot;).tolist(),<br>    n_results=4,<br>)</pre><p>When you outgrow Chroma, pgvector (if you already run Postgres) and a managed service like Pinecone are the usual next steps. Don’t reach for them before you need them.</p><h3>2. Add a reranker (the highest ROI change in RAG)</h3><p>Embedding search is fast but coarse. It compresses a chunk into one vector, so it sometimes ranks a vaguely-related chunk above the truly relevant one. The fix is a two-stage retrieve: pull a generous candidate set with the vector store, then re-score those candidates with a <strong>cross-encoder</strong>, which reads the query and each chunk <em>together</em> and is far more accurate (and far slower, which is why we only run it on the shortlist).</p><pre>from sentence_transformers import CrossEncoder<br><br>reranker = CrossEncoder(&quot;cross-encoder/ms-marco-MiniLM-L-6-v2&quot;)<br><br>def retrieve_rerank(question, fetch_k=25, final_k=4):<br>    candidates = store.search(embed([question])[0], k=fetch_k)<br>    pairs = [(question, p[&quot;text&quot;]) for p, _ in candidates]<br>    scores = reranker.predict(pairs)<br>    ranked = sorted(zip(candidates, scores), key=lambda x: -x[1])<br>    return [c for c, _ in ranked[:final_k]]</pre><p>In my experience this single change does more for answer quality than any prompt tweak. If you only adopt one upgrade from this article, adopt this one.</p><h3>3. Hybrid search (rescue the exact-match cases)</h3><p>Semantic search is great at meaning but can whiff on exact tokens: product SKUs, error codes, surnames, acronyms. Combine it with classic keyword search (BM25) so you get the best of both.</p><pre>from rank_bm25 import BM25Okapi<br><br>texts = [c[&quot;text&quot;] for c in corpus]<br>bm25 = BM25Okapi([t.split() for t in texts])<br><br>def hybrid_search(question, k=4, alpha=0.5):<br>    # Dense scores<br>    dense = store.vectors @ embed([question])[0]<br>    # Sparse (keyword) scores, normalized to [0, 1]<br>    sparse = np.array(bm25.get_scores(question.split()))<br>    sparse = sparse / (sparse.max() + 1e-12)<br>    dense = (dense - dense.min()) / (dense.max() - dense.min() + 1e-12)<br>    # Weighted blend<br>    combined = alpha * dense + (1 - alpha) * sparse<br>    top = np.argsort(-combined)[:k]<br>    return [(corpus[i], float(combined[i])) for i in top]</pre><h3>4. Smarter chunking</h3><p>Character counts are a stand-in for the real unit, which is <strong>tokens</strong>, because that’s what both the embedding model and the LLM actually consume. Use the model’s tokenizer to size chunks, respect document structure (don’t split a table or a code block down the middle), and for structured docs consider attaching the section heading to each chunk so an orphaned paragraph still carries its context. There is no universally best chunk size; 200 to 500 tokens with 10 to 20 percent overlap is a sane starting range to tune from.</p><h3>5. Make answers trustworthy</h3><p>Two cheap habits separate a demo from something people rely on. First, always return the source chunks alongside the answer so users can verify, which my prompt above already enforces with bracketed citations. Second, handle the empty case explicitly: if your top reranked score is below a threshold, short-circuit and return “I don’t have enough information to answer that” rather than feeding weak context to the model and inviting a hallucination.</p><pre>def ask_safe(question, threshold=0.2):<br>    hits = retrieve_rerank(question)<br>    if not hits:<br>        return {&quot;answer&quot;: &quot;No relevant documents found.&quot;, &quot;sources&quot;: []}<br>    return {&quot;answer&quot;: generate(question, [(h, 1.0) for h in hits]),<br>            &quot;sources&quot;: [h[&quot;source&quot;] for h in hits]}</pre><h3>How to actually know if it’s working</h3><p>You cannot improve what you don’t measure, and “it looked fine on a few questions” is not measurement. Build a small evaluation set of real questions paired with the chunk(s) that contain the answer, then track two things separately:</p><ul><li><strong>Retrieval quality.</strong> Did the right chunk appear in the top-k? Recall@k and Mean Reciprocal Rank are the standard metrics, and they isolate the part of the system you can most easily fix.</li><li><strong>Answer quality.</strong> Given correct context, is the final answer faithful (no claims beyond the context) and complete? An LLM-as-judge with a strict rubric works well here and scales.</li></ul><p>The reason to measure these separately is diagnostic: if retrieval recall is high but answers are bad, fix your prompt; if recall is low, no prompt on earth will save you, and you should be tuning chunking, embeddings, and reranking instead.</p><h3>The pitfalls I see most often</h3><p>Chunks too large dilute the embedding and bury the answer in noise. Chunks too small lose the surrounding context the model needs to interpret them. No overlap silently drops answers that fall on boundaries. Skipping the reranker leaves a large, easy quality gain on the table. Embedding queries and documents the same way when your model supports asymmetric modes. And the quiet killer: treating retrieval failures as model failures, then burning weeks tuning prompts when the right chunk was never retrieved in the first place. When an answer is wrong, <em>always</em> print the retrieved context first. Nine times out of ten the bug is upstream of the model.</p><h3>Where to go from here</h3><p>What you’ve built scales surprisingly far. The next frontiers, when you need them, are query rewriting (have an LLM rephrase or decompose the question before retrieval), multi-hop retrieval for questions that require chaining facts across documents, and agentic RAG where the model decides <em>when</em> and <em>what</em> to search rather than retrieving blindly on every turn.</p><p>But resist the urge to add those before you’ve nailed the fundamentals. A clean pipeline with good chunking, a strong embedding model, a reranker, and an honest evaluation harness will beat a baroque agentic system built on shaky retrieval every single time.</p><p>Build the simple thing. Measure it. Then, and only then, make it clever.</p><p><em>If this was useful, the best favor you can do me is run the code, break it on your own data, and tell me where it fell over. That’s where the real learning is.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d710b40447b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Eye That Cannot Find You]]></title>
            <link>https://medium.com/@isjustabhi/the-eye-that-cannot-find-you-a6129f9a401a?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6129f9a401a</guid>
            <category><![CDATA[nazar]]></category>
            <category><![CDATA[manifestation]]></category>
            <category><![CDATA[evil-eye]]></category>
            <category><![CDATA[judaism]]></category>
            <category><![CDATA[hinduism]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Fri, 29 May 2026 10:22:31 GMT</pubDate>
            <atom:updated>2026-05-29T10:22:31.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everyone around you is quietly manifesting your downfall. That’s the promise of the evil eye. Here’s why it works, and the one shift that makes it stop. (Nazar)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tFPoo98zWVkwMrQN.jpg" /><figcaption>Image source cited from-Evil Eye in Judaism</figcaption></figure><p>Someone is jealous of you right now.</p><p>Maybe it’s the colleague who congratulated you a half-second too late. Maybe it’s the relative who asks about your salary and then goes quiet. Maybe it’s a stranger who watched you laugh on the train and felt the cold weight of not having what you have. You can feel it sometimes, can’t you? That sideways glance. The compliment with an edge.</p><p>My grandmother had a whole defense system for it. Dried red chilies and a withered lemon by the front door. A fistful of salt circled over my head and thrown into the fire. If the salt crackled too loudly, she’d press her lips together and say someone had looked at me with a heavy heart. <em>Nazar.</em> The evil eye. The oldest superstition we have, found from the Mediterranean to the Subcontinent, older than most of our gods.</p><p>The logic is simple and cruel. You hold something good, a harvest, a beautiful child, an easy life, and someone who lacks it looks at you. Not always with hatred. Sometimes just with the ache of wanting. And then, the belief goes, the thing you held begins to slip away. The crop fails. The child falls ill. The laugh goes quiet. As if envy were a current that could cross a room and rot whatever it touched.</p><p>I spent years rolling my eyes at all of it. The chilies, the salt, the whole anxious theater of it. I think now I was being lazy. Because the belief is wrong about almost everything except the one thing that actually matters. And to see what that is, you have to ask a question the lemon by the door never answers.</p><p><em>Why would another person’s feeling have any power over your life at all?</em></p><h3>The wall that isn’t there</h3><p>Look at the assumption hiding inside the whole idea, the one everybody makes and nobody examines.</p><p>Nazar assumes there are two of you. There’s <em>you</em>, holding your good fortune, and there’s <em>them</em>, out there, separate, wanting it. The envy travels across the gap in between.</p><p>But look hard at that gap.</p><p>The deepest claim of the non-dual traditions, Advaita Vedanta most precisely but you find the same shape in Zen and Sufism and Taoism, is that the gap is the illusion. Not the people. The <em>separateness.</em> There is, on this view, only one awareness in all of existence, and it is wearing every single face at once. “The total number of minds in the universe is one,” Schrödinger wrote, after years spent reading the Upanishads. “Consciousness is a singular of which the plural is unknown.”</p><p>I used to read lines like that as pretty poetry. Lately I read them as a description.</p><p>Try the experiment the old teachers loved. Lift your hand and look at it. The moment you do, your whole attention shrinks down onto five fingers, and the rest of your body drops out of awareness. Your spine, your feet, the breath moving in your chest. They don’t stop existing. You just stop noticing them. You made yourself small so you could <em>experience</em> one small thing.</p><p>That, the tradition says, is exactly what’s happening to you right now. The one awareness has narrowed itself to a single point, focused through one nervous system, and forgotten the rest of itself just to taste what it’s like to be <em>this.</em> To be you, reading this, on this ordinary afternoon. You are not separate from the whole. You are the whole, staring at its own hand.</p><p>And everyone you’re <em>not</em> attending to right now, the city outside, the strangers on the train, the relative with the heavy heart, is simply the part of that one awareness you’ve set down for the moment. Your own subconscious, in a sense. The rest of your own forgotten body, wearing a thousand different masks.</p><h3>Why the curse works anyway</h3><p>Here’s where the superstition turns out to be half right, in a way that should make you uncomfortable.</p><p>Think about a dream. In the dream, a stranger appears and curses you, and you feel real fear, and sometimes you wake with your heart pounding. So ask yourself. Whose mind made that stranger? Whose mind wrote the curse, supplied the face, manufactured the fear? One mind. One dreamer, playing every part.</p><p>If the non-dualist is right, your waking life has the exact same structure. The envy aimed at you is not arriving from outside the system, because there is no outside. It’s rising up <em>within</em> the single field of awareness that you also happen to be. Which means the only reason it can touch you at all is that you have agreed, completely and without noticing, to the premise that it’s foreign. That there’s a <em>them</em>, over there, with the power to reach <em>you</em>, over here.</p><p>So the curse isn’t powered by their wanting. It’s powered by your belief in the wall.</p><p>Drop the conviction that you’re a separate, defendable object surrounded by rivals, and the envy has nothing left to grab. You cannot be cursed by your own reflection. You cannot lose a coin to your own left hand.</p><p>The chilies were treating the symptom. The disease was always duality.</p><h3>The four words that break the spell</h3><p>So what do you actually do, the next time you feel the eye on you?</p><p>The teachers offer something almost embarrassingly simple, and I’ve come to think the simplicity is the whole point. You remember four words. <em>I am not. God is.</em></p><p>If the word God is too loud for you, say it however you can stand to. <em>The doing is not mine.</em></p><p>This wealth I’m gripping so anxiously? The awareness is holding it, not me. This life I keep calling mine? It’s being lived through me, not by me. Even this fear I’m feeling right now? It’s the whole, tasting what fear is like, through the small window it briefly became. I gained nothing. I’m protecting nothing. I’m just the reed, and the music is only passing through.</p><p>There’s an old Sanskrit phrase for exactly this. <em>Nimitta matra.</em> Merely an instrument. You are not the owner. You are the opening. And no envy, however sharp, can curse an opening. It can only curse someone who insists he’s solid enough, and separate enough, to be robbed.</p><p>I’m not asking you to believe any of this is metaphysically proven. It isn’t, and I have very little patience for people who sell certainty about the structure of consciousness at a premium. This is a <em>lens</em>, not a theorem. A way of standing in your own life that happens to dissolve a fear that has haunted people for four thousand years.</p><p>But notice what it asks of you, and what it gives back.</p><p>It doesn’t ask you to hang lemons or throw salt or guard your fortune against a hostile world. It asks something quieter and much harder. That you stop believing, just for a moment, in the wall between you and everyone you were taught to fear. And in exchange it hands you a strange relief. The people you imagined were manifesting your downfall were never strangers at all. They were you, forgetting yourself. There’s no one out there to defend against.</p><p>The eye is still searching the room. It just can’t find a separate self to land on.</p><p>That self was the only thing it could ever curse. And it was never really there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6129f9a401a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT Doesn’t Read Your Words. Here’s What It Actually Does.]]></title>
            <link>https://medium.com/@isjustabhi/chatgpt-doesnt-read-your-words-here-s-what-it-actually-does-5b67d1b11b1d?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b67d1b11b1d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Mon, 25 May 2026 01:49:56 GMT</pubDate>
            <atom:updated>2026-05-25T01:49:56.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P22Igs0zm7IlMvdvc8KH6g.png" /></figure><p>A friend once asked me, “How does ChatGPT know what I mean?”</p><p>I started to answer, then stopped. Because the honest reply is: it doesn’t. Not the way you and I know things. What happens between your question and its answer is closer to a magic trick performed by a calculator the size of a small country.</p><p>Let me show you the trick.</p><h3>Your sentence gets chopped up</h3><p>The first thing the model does is take your beautiful, thoughtful prompt and rip it apart.</p><p>Type “I love pizza” and the machine doesn’t see those three words. It sees fragments. Maybe “I”, “ love”, “ piz”, “za”. These fragments are called tokens, and every model has its own way of slicing.</p><p>Why bother? Because a vocabulary of word pieces is more flexible than a dictionary of full words. The model can handle “unbelievableness” or “tacocat” without ever having seen them before.</p><p>It’s like learning to read by recognizing syllables instead of memorizing every word in existence.</p><h3>Words become coordinates on a secret map</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VbjO0Yvz25w1Wmd4g6AAA.png" /></figure><p>Here’s where it gets strange.</p><p>Each token gets turned into a long list of numbers. Picture a string of a few thousand decimals. That list places the token somewhere on an invisible map with thousands of dimensions.</p><p>On this map, “puppy” sits near “dog.” “Tokyo” sits near “Japan.” “Furious” sits near “angry” but a few blocks over.</p><p><em>The model never sees language. It sees geography.</em></p><p>When you ask about heartbreak, the machine isn’t feeling anything. It’s just noticing that your prompt landed in a neighborhood close to “loss,” “missing,” and “rain on a Sunday.”</p><h3>The attention layer decides what matters</h3><p>Now comes the part that changed AI forever: attention.</p><p>Imagine reading the sentence “The trophy didn’t fit in the suitcase because it was too big.” What does “it” refer to? You barely think about it. The trophy, obviously. But for a computer, that’s a puzzle.</p><p>Attention is how the model solves these puzzles. For every token, it asks: which other tokens should I be looking at right now? It weighs the connections, learns which words pull on which, and builds a sense of context that wasn’t there before.</p><p>This is the layer that makes the difference between a chatbot and something that feels eerily fluent.</p><h3>It guesses the next word. Then guesses again.</h3><p>Here’s the punchline that disappointed me when I first learned it.</p><p>The model doesn’t plan its answer. It just predicts <strong>the single most likely next token</strong>, adds it to the sentence, and predicts the next one. And the next. And the next.</p><p>That’s it. A long chain of educated guesses.</p><p>When ChatGPT writes a poem or explains quantum physics, it’s not thinking ahead. It’s playing a very, very good game of autocomplete, one piece at a time, until it decides the answer is done.</p><h3>Then it pretends to be human again</h3><p>Finally, all those predicted tokens get stitched back together and converted into readable text. The numbers vanish. The map disappears. What lands on your screen looks like a person typed it.</p><p>But behind the curtain, no one did. A pile of math turned your question into coordinates, walked a landscape of meaning, and guessed its way to a reply that somehow makes sense.</p><h3>The takeaway</h3><p>The next time an AI answers you, remember: it didn’t understand your question. It transformed it, mapped it, weighed it, and gambled its way to a response.</p><p>And maybe that’s the most interesting part. Something with no thoughts, no feelings, and no real grasp of language can still help you write a wedding speech or debug your code.</p><p>The miracle isn’t that machines think like us.</p><p>It’s that they don’t, and we can still talk to them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b67d1b11b1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression in 3 Minutes]]></title>
            <link>https://medium.com/@isjustabhi/logistic-regression-in-3-minutes-1033e0dfbb90?source=rss-ce921d679daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1033e0dfbb90</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Abhiram Varma]]></dc:creator>
            <pubDate>Fri, 22 May 2026 03:14:49 GMT</pubDate>
            <atom:updated>2026-05-22T03:14:49.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>The algorithm behind every “yes or no” decision online</h3><p>Every time your email app flags a message as spam, a bank decides whether your card swipe looks fraudulent, or Netflix decides whether you’re about to cancel — there’s a good chance the same algorithm is making the call.</p><p>It’s not a neural network. It’s not GPT.</p><p>It’s a 70-year-old workhorse called <strong>logistic regression</strong>, and once you understand it, you’ll start seeing it everywhere.</p><h3>The Question It’s Built to Answer</h3><p>Linear regression predicts <em>how much</em> — how much an apartment will rent for, how many ice creams you’ll sell, how many minutes your commute will take.</p><p>Logistic regression predicts something different. It predicts <strong>probability</strong> — specifically, the probability that something is <em>one thing or another</em>.</p><ul><li>Is this email spam, or not? <em>(yes/no)</em></li><li>Will this customer churn, or stay? <em>(yes/no)</em></li><li>Is this transaction fraud, or legit? <em>(yes/no)</em></li><li>Will this lead convert, or ghost us? <em>(yes/no)</em></li></ul><p>That’s it. That’s the entire job.</p><h3>Why Not Just Use Linear Regression?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vCEPDV3eAUeJT8moDfYPQ.png" /></figure><p>You might think: “Why not just predict a number between 0 and 1, where 0 means ‘definitely no’ and 1 means ‘definitely yes’?”</p><p>Great instinct. The problem is that linear regression draws a <em>straight line</em> — and a straight line can shoot up to 1.7 or down to -0.3. What does it mean for the probability of spam to be 170%? Nothing. It’s nonsense.</p><p>We need a function that <strong>squashes any input — no matter how big or small — into a number between 0 and 1.</strong></p><p>Enter the sigmoid.</p><h3>The Sigmoid: A Beautiful Little Curve</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkJEz3kAuqV3657N4DH-mQ.png" /></figure><p>The sigmoid (or “S-curve”) is the heart of logistic regression. It takes any number from negative infinity to positive infinity and squashes it neatly between 0 and 1.</p><p>Big positive input? Output approaches 1. Big negative input? Output approaches 0. Right in the middle? Output is 0.5 — pure uncertainty.</p><p>That’s logistic regression’s superpower: it always speaks the language of probability.</p><p>Once you’ve got that probability, you draw a threshold — usually 0.5 — and you have a decision:</p><ul><li>Probability &gt; 0.5 → predict <strong>“yes”</strong></li><li>Probability &lt; 0.5 → predict <strong>“no”</strong></li></ul><p>That’s the whole algorithm. Take features, run them through a linear combination, squash through a sigmoid, get a probability, threshold it, done.</p><h3>A Concrete Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1V1_gqkcLDaEzq6l4Lq1Q.png" /></figure><p>Imagine you’re building a spam filter. You look at every incoming email and extract a few features:</p><ul><li>Number of suspicious links</li><li>Contains the word “winner,” “free,” or “urgent”</li><li>Sender is in your contacts (yes/no)</li><li>Time of day it was sent</li></ul><p>Logistic regression learns a weight for each feature. Maybe it learns that “contains ‘urgent’” gets a +1.2 weight (pushes toward spam), and “sender is in contacts” gets a -2.5 weight (pulls strongly away from spam).</p><p>Add them all up, push through the sigmoid, and you get something like <strong>“this email is 87% likely to be spam.”</strong></p><p>Above the threshold? Junk folder.</p><h3>Where It Actually Gets Used</h3><p>Logistic regression is the unsexy, undefeated champion of the business world:</p><ul><li><strong>Spam detection</strong> — Gmail’s classic baseline model</li><li><strong>Churn prediction</strong> — telecoms and SaaS companies use it constantly</li><li><strong>Credit scoring</strong> — your loan application almost certainly runs through one</li><li><strong>Medical diagnosis</strong> — predicting whether a tumor is benign or malignant</li><li><strong>Marketing</strong> — will this lead convert? Should we send this ad?</li><li><strong>Fraud detection</strong> — flagging suspicious credit card transactions</li></ul><p>It’s preferred over fancier models in regulated industries (finance, healthcare) because every coefficient is <strong>interpretable</strong>. You can literally tell the auditor, “If the applicant’s debt-to-income ratio goes up by 1, their probability of default goes up by X%.”</p><p>Try doing that with a deep neural network.</p><h3>When to Use It (and When to Run)</h3><p><strong>Use logistic regression when:</strong></p><ul><li>Your outcome is binary (yes/no, will/won’t, spam/not spam)</li><li>You need to explain <em>why</em> the model decided what it did</li><li>You want a fast, low-overhead baseline before trying anything fancier</li><li>Your data isn’t insanely high-dimensional or non-linear</li></ul><p><strong>Skip it when:</strong></p><ul><li>The relationship between features and outcome is deeply non-linear (try random forests or boosting)</li><li>You have many overlapping classes (try multinomial models or neural nets)</li><li>Features interact in complex ways that a linear combination can’t capture</li></ul><h3>The 3-Minute Takeaway</h3><p>Logistic regression is the algorithm you reach for when the question isn’t <em>“how much?”</em> — it’s <em>“will it, or won’t it?”</em></p><p>It takes any combination of features, mixes them with learned weights, squashes the result through a sigmoid to produce a probability, and gives you a clean yes-or-no decision.</p><p>It’s fast. It’s interpretable. It’s been around since the 1950s. And right now, somewhere in the world, it’s making millions of decisions a second — about your emails, your purchases, your loan applications, and probably your last login.</p><p>Master this one, and a huge chunk of applied machine learning suddenly makes sense.</p><p><em>If this helped, give it a clap and follow for more 3-minute deep-dives into the algorithms you’ll actually use.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1033e0dfbb90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>