<?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 Nikita Averitchev on Medium]]></title>
        <description><![CDATA[Stories by Nikita Averitchev on Medium]]></description>
        <link>https://medium.com/@naveritchev?source=rss-6398ab22002c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mYYDfUYAQh4msPwM1nBsyw.jpeg</url>
            <title>Stories by Nikita Averitchev on Medium</title>
            <link>https://medium.com/@naveritchev?source=rss-6398ab22002c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:55:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naveritchev/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[Beyond RAG: How CLaRa Makes Retrieval and Generation Think in the Same Space]]></title>
            <link>https://medium.com/@naveritchev/beyond-rag-how-clara-makes-retrieval-and-generation-think-in-the-same-space-84303d8e147e?source=rss-6398ab22002c------2</link>
            <guid isPermaLink="false">https://medium.com/p/84303d8e147e</guid>
            <category><![CDATA[representation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Nikita Averitchev]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 14:40:11 GMT</pubDate>
            <atom:updated>2025-12-23T14:45:57.293Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR</strong></p><ul><li><strong>Problem.</strong> Most RAG systems glue a dense retriever to a text‑only generator. Retrieval is optimized for embedding similarity, generation for next‑token prediction, with a hard Top‑k step in between that kills gradients and wastes context on redundant text.</li><li><strong>Idea.</strong> CLaRa compresses documents into dense <em>memory tokens</em> and runs both retrieval <em>and</em> generation in that same continuous space. A differentiable Top‑k layer lets the answer loss update the retriever directly.</li><li><strong>What’s new.</strong> (1) A salience‑aware compressor (SCP) trained on synthetic QA + paraphrases, so compressed vectors keep what actually matters for answering questions; (2) end‑to‑end training of a “query reasoner” and generator using only language modeling loss, no relevance labels.</li><li><strong>Why it matters.</strong> You get up to 16× shorter contexts while matching or beating strong text‑based RAG baselines. In some QA benchmarks, compressed representations outperform full text with BGE retrieval, and a weakly supervised retriever beats fully supervised rerankers.</li></ul><p>This section summarizes findings from CLaRa, a paper by He et al. (Apple &amp; University of Edinburgh), not my own work. See the <a href="https://arxiv.org/abs/2511.18659">arXiv page</a> for details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_RIv-J44bx3uOEo931yYQ.png" /><figcaption>generated figure</figcaption></figure><h3>Why Classic RAG Hits a Wall</h3><p>Standard RAG looks simple: embed the query, retrieve the Top‑k documents by cosine similarity, stuff their raw text into the prompt, let the LLM answer. At its core, that design introduces two structural problems:</p><ol><li><strong>Optimization mismatch.</strong> The retriever is trained (if at all) to maximize some notion of relevance in embedding space; the generator is trained on next‑token prediction over text. The discrete Top‑k selection in between is non‑differentiable, so gradients from the answer cannot flow back into the retriever. You end up with two partially aligned systems rather than one reasoning model.</li><li><strong>Representation mismatch.</strong> Retrieval works over dense vectors; generation over raw tokens. It leads to double encoding and bloated prompts, triggering classic long‑context failures: overflow, irrelevant filler, and higher compute per query.</li></ol><p>CLaRa’s core move is: stop treating retrieval and generation as two models with incompatible representations; put them in <em>one</em> continuous latent space and train them together.</p><h3>Step 1: Salient Compression Instead of Token Reconstruction</h3><p>CLaRa starts with <strong>SCP (Salient Compressor Pretraining)</strong>: a way to turn long documents into a handful of <em>memory tokens</em> without throwing away the information that matters for QA.</p><p>Rather than asking the model to reconstruct every token, SCP builds a synthetic pretraining set from ~2M Wikipedia documents:</p><ul><li><strong>Simple QA:</strong> atomic question–answer pairs that each target a single fact, forcing the compressor to retain fine‑grained factual details.</li><li><strong>Complex QA:</strong> multi‑hop questions that connect several facts inside the same document, encouraging relational and compositional semantics rather than surface co‑occurrence.</li><li><strong>Paraphrases:</strong> document‑level rewrites that preserve meaning but change structure and wording, pushing the representation to capture semantics instead of memorizing form.</li></ul><p>Architecturally, SCP appends learnable memory tokens to each document and uses their last‑layer hidden states as the compressed representation.</p><p>A generator adapter is trained to produce answers or paraphrases from those memory tokens, with a loss that combines:</p><ul><li>Cross‑entropy for the generated text; and</li><li>An MSE alignment term that pulls the average memory‑token embedding towards the average document‑token embedding, so the compressed vectors stay anchored in the original semantic space.</li></ul><p>Empirically, this compressor consistently beats strong baselines like LLMLingua‑2, PISCO, XRAG and others, both in realistic retrieval settings and when the relevant document is guaranteed in the candidate set.</p><p>On average it improves over the best soft compressor (PISCO) by +1.13 points in normal QA and +5.35 points in oracle QA, and over LLMLingua‑2 by +5.37 and +17.31 points, respectively.</p><p>Crucially, SCP’s compressed representations sometimes even outperform uncompressed full‑text pipelines with BGE retrieval, which suggests that well‑trained semantic compression can <em>improve</em> reasoning by filtering out noise rather than merely saving tokens.</p><h3>Step 2: CLaRa’s Unified Retriever–Generator</h3><p>On top of the frozen compressor, CLaRa trains a unified retriever–generator stack:</p><ul><li>Every document is encoded once, offline, into a fixed set of memory tokens M_i using the SCP compressor, which remains frozen during end‑to‑end training.</li><li>A <strong>Query Reasoner</strong>, implemented as a LoRA adapter initialized from the compressor, maps the query into the same memory‑token format as the documents.</li><li>Relevance scores are cosine similarities between the query representation and each compressed document; the Top‑k memory‑token embeddings are concatenated with the query representation and fed to the generator adapter, which produces the answer.</li></ul><p>The entire system (Query Reasoner and generator) is trained with a <strong>single next‑token prediction loss</strong> over the target answer, no explicit ranking labels required.</p><p>Intuitively, the retriever is rewarded whenever the documents it promotes help the generator increase answer likelihood, and penalized otherwise.</p><p>The remaining technical part is differentiability: Top‑k selection is discrete. CLaRa uses a <strong>Straight‑Through (ST) Top‑k estimator</strong>: in the forward pass it picks a hard Top‑k set exactly as a normal retriever would, but in the backward pass it routes gradients through a softmax‑based relaxation over all candidate documents.</p><p>That gives you a clean gradient path from the answer loss back to the Query Reasoner.</p><p>A gradient analysis in the paper shows that this yields two coupled learning signals for the retriever: one that aligns its ranking with answer usefulness, and one that shapes document embeddings themselves to better support the generator’s reasoning in the shared latent space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*685GS8qMozhkvY21QuCekQ.png" /><figcaption>Figure by He et.al.</figcaption></figure><h3>Latent Reasoning in the Query Embedding</h3><p>Because the Query Reasoner is trained through answer prediction, not just similarity, its embeddings start to encode pieces of the reasoning chain themselves.</p><p>The authors probe this using a logit‑lens analysis: they decode the top tokens implied by the query’s memory tokens. For a question about “the nephew of Ivory Lee Brown” and his freshman rushing yards, the decoded query representation includes tokens like “NFL” and “Oklahoma” even though these words never occur in the question text.</p><p>Those tokens <em>do</em> appear in the relevant documents about Adrian Peterson, who set the NCAA freshman rushing record at Oklahoma and is Brown’s nephew.</p><p>That’s a concrete sign that the Query Reasoner is not just matching on lexical overlap. It is implicitly filling in latent bridge concepts that connect the question to the right evidence — reasoning in the embedding space <em>before</em> any text is generated.</p><h3>Does It Actually Help?</h3><p>On four QA benchmarks (Natural Questions, HotpotQA, MuSiQue, and 2WikiMultihopQA) CLaRa is evaluated both as a compressor and as a full end‑to‑end system with Mistral‑7B and Phi‑4B backbones.</p><p>For compression alone, SCP’s memory‑token representations outperform all compared baselines across a range of compression rates. In the normal setting (Top‑5 retrieval from Wikipedia), SCP’s average QA performance exceeds PISCO’s by +1.13 points and LLMLingua‑2’s by +5.37 points; in the oracle setting (positive document guaranteed in Top‑5), the gains grow to +5.35 and +17.31 points.</p><p>Notably, SCP is on average +2.36 points (Mistral‑7B) and +6.36 points (Phi‑4‑mini) better than a non‑compressed text baseline using BGE retrieval over full documents.</p><p>For the full CLaRa pipeline, joint retriever–generator training on compressed representations achieves performance comparable to or better than strong text‑based joint models like DRO. With 16× compression, CLaRa‑Mistral‑7B surpasses text‑based DRO‑Mistral‑7B on NQ (F1 51.01 → 51.41) and especially on 2Wiki (43.65 → 47.18).</p><p>Under oracle retrieval, F1 exceeds 75 % on both NQ and HotpotQA, indicating that the model can fully leverage high‑quality retrieval when it’s available.</p><p>On the retrieval side, a CLaRa retriever trained <em>only</em> via answer‑level NTP loss reaches Recall@5 of 96.21 % on HotpotQA at 4× compression — beating a fully supervised BGE‑Reranker baseline at 85.93 % and even surpassing a retriever trained explicitly with contrastive relevance labels.</p><h3>What This Changes If You’re Building RAG</h3><p>If you’re designing RAG systems, CLaRa points to a different design target than “more context”:</p><ul><li><strong>Compress first, then reason.</strong> With a good semantic compressor, you can treat documents as dense memory objects, not walls of text. This reduces cost and, in these experiments, can <em>improve</em> QA quality by cutting noise.</li><li><strong>Train the retriever on answers, not just relevance labels.</strong> Let the answer loss backprop into your retriever via a differentiable selection mechanism. That marries retrieval to your real objective (answer quality), and it works even when you don’t have labeled positive/negative document pairs.</li><li><strong>Use a query reasoner, not a plain encoder.</strong> The query encoder should be trained to anticipate the latent evidence the generator will need, not just to sit close to similar documents in embedding space.</li></ul><p>This doesn’t make classic text‑only RAG obsolete — you can still start there. But CLaRa is a concrete demonstration that treating retrieval and generation as one continuous system, with compression built in, is both feasible and competitive at scale.</p><h3>Limitations and Open Questions</h3><p>There are some clear caveats:</p><ul><li>The compressor is pretrained on Wikipedia; its out‑of‑domain behavior (enterprise knowledge bases, code, multimodal content) is still an open question.</li><li>Experiments run on medium‑sized models (7B, 4B). It is plausible that larger base models will make compressed representations even more competitive with raw text, but we don’t yet know where that curve bends.</li><li>The work focuses on QA. Using compressed latent memories as the backbone for richer agentic workflows (planning, tool use, multi‑step search) is suggested but not explored experimentally.</li></ul><p>Even with those limitations, CLaRa is a useful proof of concept: <strong>reasoning in RAG is not just about longer contexts; it’s about better, shared representations.</strong> If you’re bumping up against context limits or brittle retrievers, it’s time to think less in tokens and more in latent memory.</p><ul><li><a href="https://huggingface.co/papers/2511.18659">Paper page - CLaRa: Bridging Retrieval and Generation with Continuous Latent Reasoning</a></li><li><a href="https://arxiv.org/abs/2511.18659">CLaRa: Bridging Retrieval and Generation with Continuous Latent Reasoning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84303d8e147e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Tests Marketing Can Trust: Structure, Decisions, and Sample Size]]></title>
            <link>https://medium.com/@naveritchev/a-b-tests-marketing-can-trust-structure-decisions-and-sample-size-454a3f169cd2?source=rss-6398ab22002c------2</link>
            <guid isPermaLink="false">https://medium.com/p/454a3f169cd2</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Nikita Averitchev]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 15:18:49 GMT</pubDate>
            <atom:updated>2025-11-22T15:18:49.815Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Marketing loves a good success story. Data doesn’t care about stories; it cares about causality. </em>Too often, what gets called an “A/B test” is just two variants, a dashboard, and a hopeful conclusion. What you actually want is a true randomized controlled experiment in the sense of: a proper control group, predefined metrics, and decision rules that hold up under scrutiny. This article is about that version of A/B testing and how to structure experiments marketing teams can actually trust.</p><h3>TL;DR</h3><p><strong>Problem:</strong> Many marketing “tests” rely on before/after comparisons or slicing audiences. They look quantitative but don’t answer the key causal question: <em>What would have happened without this change?</em></p><p><strong>Baseline:</strong> Online controlled experiments (A/B tests) do answer that by randomly assigning users (or clusters) to control vs. treatment and comparing outcomes on a predefined metric . Big tech companies run tens of thousands of such experiments annually because randomized experiments are the gold standard for establishing causality in product and marketing changes.</p><p><strong>Idea:</strong> Treat A/B tests as small scientific studies:</p><ul><li><strong>Define</strong> the experiment population and the unit of randomization (e.g. user, email, device, or store).</li><li><strong>Pick one primary metric</strong> that captures the objective, plus a few <strong>guardrail metrics</strong> to monitor side effects</li><li><strong>Phrase a concrete hypothesis</strong> (with an expected direction and magnitude of change).</li><li><strong>Commit to a decision rule and a sample size</strong> before you peek at any results.</li></ul><p><strong>Structure:</strong></p><ol><li><strong>Why experiments beat dashboards: </strong>Experiments provide causal answers; dashboards only show correlations.</li><li><strong>Anatomy of a trustworthy A/B test</strong> : The four key components every serious test needs.</li><li><strong>Hypothesis → Metric → Decision Rule: </strong>Formulating hypotheses, choosing metrics, and pre-defining what “success” looks like.</li><li><strong>Sample size and duration (without going full statistician): </strong>Intuition for how long to run tests and how many users you need.</li></ol><p><strong>Result:</strong> Fewer “we <em>think</em> it helped” slides, and more “We changed X, it moved metric Y by Z ± ε, so here’s what we’re doing next.” In other words, decisions backed by reliable data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HH7lCbls1o3C3l0sy5CdBA.png" /></figure><h3>Why Experiments Beat Dashboards</h3><p><strong>Dashboards</strong> show what happened. <strong>Experiments</strong> ask what <em>caused</em> it. In the world of web products, A/B testing (randomly splitting users into control vs. treatment) is the default way to decide between variants. Companies like Google, Amazon, and Booking.com run tens of thousands of experiments each year . Why? Because an experiment with a proper control group tells you what would have happened if you <em>hadn’t</em> made the change, something that attribution models or post-hoc analyses often fudge.</p><p>Marketing has the same need for causal insight. Consider the question:</p><blockquote><em>“If we hadn’t changed the subject line / landing page / promotion, how would revenue and retention have evolved?”</em></blockquote><p>You <strong>don’t</strong> get that answer from:</p><ul><li>Last-click attribution models.</li><li>Comparing “people who clicked” vs. “people who didn’t” (those groups differ in many ways).</li><li>Launching a change in Week 1 and eyeballing metrics in Week 2.</li></ul><p>All of those approaches might show differences, but they don’t establish causality, other factors could be at play. You <em>do</em> get a causal answer from <strong>randomization</strong> and a clean control group. A properly designed experiment ensures the only systematic difference between groups is the treatment itself, so any outcome difference can be attributed to that change .</p><p>In short, experiments turn “did our metric move?” into “did <em>our change</em> make the metric move?” That’s a huge difference. Teams that embrace experiments also embrace being proven wrong. (Fun fact: only about ~10% of A/B tests at even the best companies produce a positive improvement , which shows why validating with experiments is crucial — most intuitive ideas don’t pan out!) Instead of cherry-picking success stories, experiments keep us honest by letting the data tell the real story.</p><h3>Anatomy of a Trustworthy A/B Test</h3><p>At minimum, any credible A/B test in marketing should have four parts:</p><ol><li><strong>Treatment vs. Control</strong></li><li><strong>Randomization</strong></li><li><strong>A Primary Metric</strong></li><li><strong>Guardrail Metrics</strong></li></ol><p>Let’s break these down.</p><h3>1. Treatment vs. Control</h3><p>Every experiment needs a comparison point:</p><ul><li><strong>Control (A):</strong> The status quo (e.g. current subject line, current page design, no extra promo).</li><li><strong>Treatment (B):</strong> The new variant (e.g. new subject line, redesigned page, new promotion).</li></ul><p>Both groups must come from the <strong>same population</strong> in the same time frame:</p><ul><li>Same targeting criteria (e.g. all users in a certain segment, same country/language).</li><li>Same eligibility (e.g. “newsletter subscribers active in last 90 days”).</li><li>Same time window (run control and treatment concurrently).</li></ul><p>In experimental design this is called defining the <strong>experiment universe</strong> or population <em>before</em> splitting. Everyone in the test should have had an equal chance to see either variant. That way, the groups are comparable.</p><h3>2. Randomization: Who Gets What?</h3><p>Random assignment is the magic that makes an experiment causal. By randomly deciding who sees the control vs. treatment, you decouple the assignment from user characteristics . This eliminates selection bias and turns a simple comparison into a true cause-and-effect measurement.</p><p>Common randomization <strong>units</strong> in marketing experiments:</p><ul><li><strong>User-level (by user ID/account):</strong> Each user is consistently in A or B. (Good for apps, loyalty programs, logged-in experiences.)</li><li><strong>Email-address-level:</strong> Each email address is assigned to A or B. (Good for email subject line or content tests; easy to implement in email service providers.)</li><li><strong>Device or cookie-level:</strong> Each browser cookie or device ID gets A or B. (Common for anonymous web visitors. Be careful as the same person on two devices might get both variants.)</li><li><strong>Cluster-level (geo or store):</strong> Entire clusters (such as stores, cities, or regions) are assigned to A or B. (Used for things like TV ads, out-of-home marketing, or in-store experiments. Fewer units means higher variance, but sometimes clustering is necessary.)</li></ul><p>If you can’t point to <em>where and how</em> the randomization happens in your test setup, then <strong>you’re not actually doing an A/B test, </strong>you’re doing a simple comparison. Too many people call anything a test or experiment, but unless users are randomly split into control and treatment, it’s not a true experiment . Randomization is the core of trustworthiness: it ensures the groups are equivalent on average, so differences in outcomes can be credited to the treatment and not to pre-existing differences.</p><h3>3. One Primary Metric to Decide</h3><p>Experiments at scale often define an <strong>Overall Evaluation Criterion, </strong>a single metric that captures long-term value and on which the experiment’s “win” or “fail” is determined . In marketing contexts, your primary metric should clearly align with the campaign’s objective. For example:</p><ul><li><strong>Email campaigns:</strong> primary metric might be <em>revenue per recipient</em> or <em>purchase rate per email sent</em>, rather than just open or click rate.</li><li><strong>Landing page tests:</strong> primary metric could be <em>conversion rate to sign-up</em> or <em>to purchase</em> on that page.</li><li><strong>Ad campaigns:</strong> primary metric often <em>cost per acquisition (CPA)</em> or <em>return on ad spend (ROAS)</em> for the campaign.</li></ul><p>Two rules will save you from metric drama:</p><ol><li><strong>Align the metric with your goal.</strong> If your hypothesis is about increasing purchases, don’t use click-through rate as the deciding metric. Use a purchase or revenue-based metric that reflects actual business value.</li><li><strong>Choose only one primary metric.</strong> You can track many metrics, but declare one as the north star for the test outcome. Having one pre-picked winner metric prevents the common pitfall of fishing through dozens of metrics afterward to find something “significant” (which is a great way to fool yourself with noise). Deciding on one primary metric upfront enforces discipline.</li></ol><h3>4. Guardrail Metrics: Don’t Break Other Things</h3><p><strong>Guardrail metrics</strong> (also called countermetrics) are the safety checks, key metrics you <strong>don’t</strong> want to tank while focusing on the primary metric . They catch side effects and ensure you aren’t winning on the primary metric at the expense of hurting the business elsewhere.</p><p>For example, if you test an aggressive email subject line:</p><ul><li><strong>Primary metric:</strong> revenue per recipient (the goal is to increase sales from the email).</li><li><strong>Guardrails:</strong> unsubscribe rate, spam complaint rate, bounce rate. (Because a pushy subject might boost short-term clicks but also annoy users, drive unsubscribes, or trigger spam filters. You need to keep those within acceptable limits.)</li></ul><p>Another example: if you test a <em>deep discount</em> promotion:</p><ul><li><strong>Primary metric:</strong> conversion rate (immediate sales lift).</li><li><strong>Guardrails:</strong> average order value or profit margin per order, and repeat purchase rate. (A huge discount might increase conversions but could lower the average basket value or attract one-time bargain hunters who never come back, hurting longer-term revenue.)</li></ul><p>In practice, many teams require <strong>superiority</strong> on the primary metric <strong>and</strong> <strong>non-inferiority</strong> on guardrails. In plain language: <em>“We will ship the new variant only if it significantly improves the primary metric </em><strong><em>and</em></strong><em> it doesn’t worsen any guardrail metric by more than an acceptable amount.”</em> For instance, <em>“We roll out the new subject line if purchase rate goes up, and unsubscribe rate doesn’t increase by more than 0.2 percentage points.” </em>It’s essentially a form of risk management for experiments: the primary metric gives you the green light, and guardrails make sure there’s no red flag attached.</p><p>By setting these criteria upfront, you avoid the trap of declaring victory on a narrow metric while inadvertently causing harm elsewhere. Guardrails make your A/B test “trustworthy” by ensuring a balanced view of outcomes.</p><h3>Hypothesis → Metric → Decision Rule</h3><p>Most tests fail not because the statistics are wrong, but because the <strong>thinking</strong> was weak upfront. To design solid experiments, impose a simple structure on yourself:</p><p><strong>Hypothesis → Metric(s) → Decision Rule.</strong></p><p>Let’s unpack each part.</p><h3>Hypothesis: More Than “Let’s See What Happens”</h3><p>A good hypothesis is <strong>specific and testable</strong>. It’s not enough to say <em>“Let’s test if this works.”</em> You need a hypothesis that someone could <em>prove wrong</em>. This means being clear about the direction of the effect and the magnitude you expect.</p><ul><li><strong>Bad:</strong> “Test if this subject line works.” (Too vague — what does “works” mean, and compared to what?)</li><li><strong>Better:</strong> “If we shorten the subject line to under 40 characters for mobile-heavy subscribers, then the open rate will increase by <em>at least 5%</em>, <strong>because</strong> long subjects are truncated in mobile inboxes.”</li></ul><p>The second version is much stronger: it specifies the change (shorter subject line, targeted to a segment), the expected outcome (higher open rate), and even a rationale. It also states <em>“at least 5%”</em> — which is a <strong>minimum effect size of interest</strong>. That detail forces you to articulate what size of improvement would actually matter commercially.</p><p>This ties back to classical hypothesis testing (Neyman–Pearson framework): you define a clear alternative hypothesis with a threshold, rather than a fuzzy “maybe there’s some difference” guess. You don’t need to cite Neyman-Pearson in your marketing slides deck, but you <em>do</em> need a hypothesis that isn’t open-ended. In short, be <em>directional</em> (“increase” or “decrease”, not just “change”) and include a <em>because</em> (the rationale). Writing a hypothesis this way keeps you honest; it sets the stage for picking metrics and deciding what outcome counts as success or failure.</p><p>(<em>Quick check:</em> If your hypothesis were extremely true or extremely false, would your primary metric obviously reflect it? If not, reconsider your metric or your hypothesis wording.)</p><h3>Metrics: Driven by the Hypothesis</h3><p>Once you have a solid hypothesis, choosing metrics becomes straightforward:</p><ul><li>The <strong>primary metric</strong> should be the main outcome in the hypothesis (the key thing you expect to change — open rate, purchase rate, revenue per user, etc.).</li><li><strong>Guardrail metrics</strong> naturally fall out from the risks or side effects you identified (“what might go wrong if my hypothesis is true?”). Think about user experience, long-term effects, or other business metrics that could be impacted.</li></ul><p>If your hypothesis says “shorter subject lines will increase open rate by 5%,” the primary metric is clearly <em>email open rate</em>. Obvious guardrails might be <em>unsubscribe rate</em> or <em>spam complaints</em> (since a gimmicky subject could annoy users).</p><p>By letting the hypothesis drive the metrics, you ensure you’re measuring what actually matters for that test, rather than vanity metrics.</p><h3>Decision Rule: Define What Happens at the End</h3><p>An experiment is an expensive way to be indecisive. Before you launch the test, commit to a <strong>decision rule, </strong>a clear plan for how you’ll act on the results. This prevents wishy-washy outcomes where the team debates what the data “really” means.</p><p>A practical template for binary decisions (launch vs. don’t launch) is:</p><ul><li><strong>Significance level (α):</strong> e.g. 0.05 (5% chance of false positive you’re willing to accept).</li><li><strong>Power (1–β):</strong> e.g. 80% (chance of detecting the effect size if it’s real).</li><li><strong>Minimum Detectable Effect (MDE):</strong> e.g. +5% relative uplift (the smallest improvement that would justify implementing the change).</li><li><strong>Guardrail tolerance:</strong> e.g. “no metric worsens by more than X% or X points.”</li></ul><p>Now formalize the rule, for example:</p><ul><li><strong>Roll out</strong> the treatment <strong>if:</strong></li></ul><p>– The primary metric’s estimated uplift ≥ +5% (our MDE <strong>or better</strong>), <strong>and</strong></p><p>– The result is statistically significant (p &lt; 0.05), <strong>and</strong></p><p>– All guardrail metrics are within acceptable limits (no serious degradation, e.g. unsubscribe rate not up more than 0.2 percentage points).</p><ul><li><strong>Iterate or run another test</strong> (no decision yet) <strong>if</strong>:</li></ul><p>– The primary metric showed a positive trend <em>but</em> less than +5%, <strong>or</strong></p><p>– The confidence intervals are wide/uncertain (e.g. the effect could be positive or negative).</p><p><em>(In these cases, you didn’t hit the win criteria, but there’s some indication of potential, maybe refine the idea and test again, or simply need more data.)</em></p><ul><li><strong>Do not roll out</strong> (reject the hypothesis) <strong>if</strong>:</li></ul><p>– The primary metric’s uplift is basically zero or negative, <strong>or</strong></p><p>– Any guardrail was clearly violated (e.g. you got the conversion lift, but unsubscribe rate doubled, not worth it).</p><p>This kind of decision framework aligns with viewing tests as tools for decision-making under uncertainty, rather than p-value vending machines. It’s the approach recommended in modern experimentation platforms (e.g. Spotify’s experimentation platform maps multiple metrics to explicit decisions ). By deciding in advance what constitutes a win, you reduce the influence of biases or internal politics when results come in. It also spares you the “but our team really <em>likes</em> variant B, maybe we should launch it anyway?” discussions, the rules were set, now you follow them.</p><h3>Sample Size and Duration: A Quick Mental Model</h3><p>Two questions everyone asks before a test: <strong>(1)</strong> <em>How many users do we need?</em> and <strong>(2)</strong> <em>How long do we run this?</em> The rigorous answer comes from statistical formulas or online calculators , but you don’t need to dive into equations here. Instead, let’s build intuition with a few simple principles:</p><p><strong>Intuition 1: Smaller effects require more data.</strong></p><p>Detecting a huge uplift (+20%) is easy; detecting a tiny uplift (+2%) is hard. In fact, the sample size needed grows <strong>quadratically</strong> as you shrink the effect size. Roughly, if you cut the targeted effect in half, you need about <strong>4×</strong> the sample to get the same statistical power. So if you insist on chasing very small improvements, be prepared for very long tests (or consider whether such a small effect is even meaningful to pursue).</p><p><strong>Intuition 2: Rare events mean longer tests.</strong></p><p>If your metric is a binary event that doesn’t happen often (like purchases or conversions in a funnel), the variance on that metric is high. For example, if only 1% of users do the thing you care about (purchase, subscribe, etc.), most users in your test contribute nothing (a zero or a no-purchase), and a few contribute a lot. This noise means you need a larger sample to confidently detect changes. <strong>Rule of thumb:</strong> the lower the baseline rate, the larger the needed sample for the same relative uplift. This is why marketers often optimize earlier funnel events (like email click-throughs or add-to-cart) in initial tests; you move to the harder end metrics (like purchase rate or long-term retention) only when you have sufficient traffic or have already gotten big wins upstream.</p><p><strong>Intuition 3: Noisy metrics need more users.</strong></p><p>Metrics vary not just by frequency but by inherent noise. A binary metric (did user click or not) has a certain variance, but a <em>continuous</em> metric like revenue per user can have huge outliers (one big spender can skew the average). If a few “whale” customers dominate the metric, your results will jump around more. To deal with noisy metrics, you either (a) accept that you’ll detect only large effects (set a bigger MDE), (b) run the test a lot longer to average out the noise, or (c) choose a more stable primary metric (e.g. use conversion rate instead of raw revenue, and track revenue as a secondary metric for context).</p><p><strong>Intuition 4: Plan your stopping rule; don’t chase “green” p-values.</strong></p><p>A common rookie mistake is <strong>peeking</strong> at the results every day and stopping the test as soon as you see a p-value &lt; 0.05 “significant” result. This is very tempting — after all, who doesn’t want to call a win early? But making stopping decisions based on interim looks at the data inflates your false positive rate significantly . In other words, if you trawl the data daily, you’ll eventually catch a random swing that looks significant purely by chance, and if you stop there, you’ve basically tricked yourself. This is well documented in the experimentation literature: unchecked peeking can make your 5% false-positive threshold effectively much higher .</p><p>A <strong>safer pattern</strong> for fixed-horizon tests:</p><ol><li><strong>Use a sample size calculator</strong> (or power analysis) <em>before</em> the test. Input your chosen α (say 0.05), desired power (say 80%), the baseline conversion rate, and the minimum uplift you care about (MDE). It will tell you how many users (or conversions) per variant you roughly need .</li><li><strong>Estimate the duration</strong> based on your typical daily traffic. (If you need 10,000 users per group and you get 1,000 eligible users per day, you’re looking at about 10 days, etc. Always pad a little for variance or traffic dips.)</li><li><strong>Commit upfront</strong>: <em>“We will run the test for at least N users or Y days, unless we discover a serious issue (like a bug or a guardrail metric way off the charts). We won’t make a decision until we hit that mark.”</em> Stick to this plan. By fixing the analysis point in advance, you maintain the statistical guarantees of the test.</li></ol><p>Only after you reach the planned sample should you check significance and make the call per your decision rule. (Advanced note: There are sequential testing designs and Bayesian approaches that allow peeking with adjusted thresholds or priors. If you’re at the level of implementing those, you probably aren’t looking to Medium articles for advice — so we’ll leave that aside.)</p><h3>A concrete example</h3><p>Let’s apply the above to a quick example. Say you’re testing a new product page layout on your website:</p><ul><li><strong>Baseline conversion rate</strong> (old page): ~5.0% of visitors purchase.</li><li><strong>Minimum effect</strong> you care about: +10% relative (i.e. an uplift from 5.0% to 5.5% conversion). Below that, the change isn’t worth implementing.</li><li><strong>Statistical parameters:</strong> α = 0.05, power = 0.8 (80% power to detect that 10% uplift).</li></ul><p>Plug those into any standard sample size calculator for comparing two proportions. You’ll likely get a required sample on the order of several thousand users <em>per variant</em>. If the page gets, say, 4,000 visitors per day, you might need on the order of a week or less to reach the sample size. If it only gets 400 a day, you’re looking at multiple weeks to get a conclusive result.</p><p>Sometimes the honest (if disappointing) answer is <strong>“We just don’t have the traffic to test this properly.”</strong> In those cases, you either need to accept very low statistical power (risky), find a larger segment or proxy metric to test on, or invest in driving more traffic. Admitting “we can’t run a trustworthy experiment here” is far better than running a flimsy test and declaring victory on unreliable data. Remember, an underpowered test that “finds a win” is often a false alarm.</p><h3>Practical Guidance for Marketing Experiments</h3><p>If you’re eager to start running better experiments in your marketing efforts, here are some practical tips to get value quickly:</p><ul><li><strong>Start with email and landing page tests.</strong> These are typically the easiest places to implement A/B tests (you have clear control over who sees what content, and it’s straightforward to randomize and measure outcomes like open, click, or conversion rates). They can quickly demonstrate the power of experimentation to your team.</li><li><strong>Standardize an experiment design template.</strong> Create a one-pager or form that every test creator fills out <em>before</em> launch: define the population, the randomization unit, hypothesis, primary metric, guardrail metrics, the expected effect size (MDE), and the decision rule (criteria for success). This forces clarity and makes others review the plan critically. It’s much easier to spot a flaw on paper (e.g. “hey, what about impact on subscriber churn? Should that be a guardrail?”) than after the test is in the field.</li><li><strong>Pick one sample size calculator (and methodology) and stick to it.</strong> There are many online calculators and stats packages; different teams might use different assumptions (e.g. two-tailed vs one-tailed tests, different power levels). To avoid confusion, pick a standard tool or internal script for power analysis, and perhaps standardize on a default power (80% or 90%) and significance level (5%). The key is consistency, don’t let each test “negotiate” its own stats after seeing the data.</li><li><strong>Log the assignment and exposure cleanly.</strong> Make sure you record who was in control vs treatment, and whether they actually had a chance to be affected (for example, if someone in the email test never opened the email, you might log them but note they didn’t actually <em>see</em> content). Clear experiment logs are gold: without them, you can’t properly analyze results, and you can’t troubleshoot if something looks off (e.g. if traffic seems imbalanced). If a bug causes some users to miss the treatment, you want to know that from the logs.</li><li><strong>Maintain a centralized “experiment logbook.”</strong> This could be as simple as a spreadsheet or as fancy as an internal wiki or database. Each experiment gets an entry with its description, dates run, metrics, results, and the decision taken. Over time, this repository of past experiments becomes extremely valuable knowledge. It prevents duplicate efforts (“didn’t we test a similar subject line last year?”) and lets you learn from patterns (e.g. “personalized subject lines tend to work better for segment A than segment B, based on these 5 tests…”). It also demonstrates the impact of the experimentation program to stakeholders by aggregating wins and insights.</li></ul><p>By following these practices, you’ll build a culture where tests are run thoughtfully and results are acted on confidently. Nothing builds trust in experimentation faster than a track record of well-run tests that lead to clear wins or smart pivots.</p><h3>Limitations to Remember</h3><p>Before we conclude, note that even the best experiments have limitations. Being aware of these will prevent you from over-claiming or misapplying results:</p><ul><li><strong>External validity:</strong> An A/B test tells you what happened for the users who were in this experiment, under the conditions of the test. If you change the audience, context, or timing, the result might differ. (A campaign that worked in June might not play the same in December; a tactic that worked for one country might flop in another.) Don’t assume results generalize universally without further testing.</li><li><strong>Interactions between experiments:</strong> If you run multiple tests on overlapping user groups at the same time, you can get interference effects . For example, if one user is in both a subject line test and a promotion discount test simultaneously, the two treatments might influence each other’s outcomes in ways that muddy the data. Where possible, isolate experiments (e.g. use non-overlapping user samples or mutually exclusive test groups) especially if you suspect the tests could interact. At the very least, be aware of overlap and check afterwards if it impacted metrics.</li><li><strong>Long-term effects:</strong> Most experiments run for a short period (days or weeks). They capture immediate or short-term behavior changes. But some effects are long-term: a user might react positively now but churn later, or a promo might boost short-term sales but erode brand perception over months. Short tests can’t measure these long-horizon outcomes well. You may need holdout groups or long-term monitoring to truly quantify persistent effects.</li></ul><p>In summary, use A/B tests as a powerful tool, but stay humble about what they can and cannot tell you. They are excellent for identifying causal impacts in the tested scenario, but they won’t solve every decision problem magically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454a3f169cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster K-Means with Ptolemy’s Inequality: skipping distance calculations without changing results]]></title>
            <link>https://medium.com/@naveritchev/faster-k-means-with-ptolemys-inequality-skipping-distance-calculations-without-changing-results-e2151e9a8c89?source=rss-6398ab22002c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2151e9a8c89</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ptolemy]]></category>
            <dc:creator><![CDATA[Nikita Averitchev]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 12:21:41 GMT</pubDate>
            <atom:updated>2025-10-25T12:21:41.765Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Clustering loves distances. Your CPU doesn’t.</em> In our <a href="https://dl.gi.de/server/api/core/bitstreams/31155075-f767-40e6-9110-83c57cf8b59c/content">BTW 2025 short paper</a> we extend Elkan’s accelerated k-means by adding bounds derived from <strong>Ptolemy’s inequality</strong>. The result is identical cluster assignments with <strong>fewer point to centroid distance evaluations</strong> across a wide range of settings. Gains are most visible when the number of clusters is large and in lower dimensions.</p><h3>TL;DR</h3><ul><li><strong>Problem.</strong> Lloyd’s k-means spends most of its time on O(nk) distance evaluations per iteration.</li><li><strong>Baseline.</strong> Elkan’s algorithm maintains upper and lower point to centroid bounds from the triangle inequality and skips many distances when bounds suffice.</li><li><strong>Idea.</strong> Add <strong>Ptolemaic bounds</strong> that use two historical centroid positions to tighten those bounds during the update phase. First iteration remains Elkan because two history positions are required. Integration happens in <strong>Algorithm 2, Steps 6 and 7</strong> (optionally also Step 5).</li><li><strong>Evaluation.</strong> We compare the <strong>number of distance evaluations</strong> rather than wall-clock time, and report <strong>speedup = distances(Elkan) / distances(Ptolemy-Elkan)</strong>. Values above 1 indicate improvement.</li><li><strong>Result.</strong> The full Ptolemy variant reduces distance evaluations broadly. Benefits increase with k. On low-dimensional Gaussian data we see at least a two-fold speedup at k = 20 and k = 100. Upper-bound-only is often close. Lower-bound-only can underperform.</li></ul><h3>Why k-means is dominated by distance evaluations</h3><p>Lloyd’s algorithm alternates an assignment step and a centroid update step. The assignment step checks each point against each centroid. That costs n \times k distances per iteration and usually dominates runtime.</p><p>Elkan’s method reduces work by keeping for every point an <strong>upper bound</strong> to its current centroid and <strong>lower bounds</strong> to all others. If the current upper bound is less than competing lower bounds, the method <strong>skips</strong> explicit distances. Bounds come from the triangle inequality and are refreshed each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnpYDLmTuMNBInllnJ0amA.png" /></figure><h3>From triangle to Ptolemy: one more historical centroid buys tighter bounds</h3><p>Triangle relates three points. <strong>Ptolemy relates four.</strong> At the end of each iteration Elkan recomputes bounds between data points and <strong>new</strong> centroids, using the <strong>previous</strong> centroid positions. If we also keep the <strong>penultimate</strong> centroid, we can form a quadrilateral (x, c°_j, c_j, c’_j) and invoke Ptolemy’s inequality to compute <strong>tighter upper and lower bounds</strong> on d(x, c’_j).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*20kqYVq1Woq5jqij" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NZS-5V4VrUhIwtzS.png" /><figcaption>source: Wikipedia</figcaption></figure><p><strong>Ptolemaic bounds, simplified notation.</strong> Let u and l denote upper and lower bounds from prior iterations, and let d( . , . ) be Euclidean distance. With prior centroids c_j and c°_j and current centroid c’_j:</p><ul><li><strong>Upper:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UTbkPo9TqrRPpwZaFSysQ.png" /></figure><ul><li><strong>Lower:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0q-zS_j78Etm7JDrIWg3w.png" /></figure><p>These correspond to Equations (5) and (6) in the paper and follow by substituting safe bounds into Ptolemy’s inequality. The method remains <strong>exact</strong> because we only prune when the inequalities guarantee correctness.</p><h3>Where it plugs into Elkan’s loop</h3><p>We adopt Elkan’s structure and change only the <strong>bound update</strong>. Replace <strong>Step 6</strong> (upper bound update) and optionally <strong>Step 5</strong> (lower bound update) with the Ptolemaic formulas, then proceed with <strong>Step 7</strong> that swaps in the new centroids. The first iteration stays Elkan because it lacks a penultimate centroid. Hybrid variants that apply Ptolemy only to the upper or only to the lower bound are also possible and are evaluated separately.</p><h3>Experimental setup in one glance</h3><p>We implemented Lloyd, Elkan, and our Ptolemy extension in Python and report <strong>distance evaluations</strong>, not wall-clock time. Counting distances is implementation-agnostic and avoids confounders like optimization effort and hardware differences. Each algorithm runs three times per dataset with k = 3, 20, 100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8vxtkdIIG3Ee81NVo3LcA.png" /></figure><p><strong>Datasets</strong> (from Table 1):</p><ul><li><strong>Iris</strong>: 150 points, 4 dimensions. <strong>Wine</strong>: 178 points, 13 dimensions.</li><li><strong>Gaussian</strong>: 10 000 points at 10, 100, 300 dimensions.</li><li><strong>Uniform (Random)</strong>: 5 000 points at 10, 100, 300 dimensions.</li></ul><p>Results you can expect</p><ul><li><strong>More clusters help.</strong> The full Ptolemy variant improves over Elkan more as k grows. On the low-dimensional Gaussian dataset it reaches at least a <strong>two-fold</strong> distance-count speedup at k = 20 and k = 100.</li><li><strong>Dimensionality trend.</strong> Benefits are strongest at 10 dimensions and taper as dimensionality increases. Improvements persist, but are less pronounced at 100 and 300 dimensions.</li><li><strong>Variant behavior.</strong> Upper-bound-only is often close to the full method. Lower-bound-only can be comparable or worse than Elkan in tougher regimes. The full method is most robust.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8k-yCmX7-zaO3rHwhxeKQ.png" /></figure><p><strong>Limitations to remember.</strong> Reducing distance counts does not guarantee proportional wall-clock speedups because Ptolemy’s updates add arithmetic overhead. A broader set of real-world datasets and more varied initializations would improve external validity. These items are outlined as future work in the paper.</p><blockquote>A quick mental model for the math</blockquote><p>Elkan updates bounds using triangle inequality. Upper bounds expand by the movement of the current cluster and lower bounds shrink by the movement of competing clusters. Ptolemy’s inequality brings in one more historical centroid and lets you combine previous upper and lower bounds with inter-centroid distances to produce <strong>tighter</strong> updates for the new centroid. The paper’s Theorem 1 formalizes the two Ptolemaic updates and shows they are safe substitutions.</p><h3>Practical guidance</h3><ul><li>Keep Elkan’s structure and screening rules. They combine well with the new bounds.</li><li>Maintain three centroid positions per cluster in memory, namely penultimate, previous, and current. This is required by the Ptolemaic updates.</li><li>If you want a quick win, start with the <strong>upper-bound-only</strong> hybrid, then move to the full method after profiling. The full method is the most robust overall.</li><li>Expect larger benefits as k increases. Verify on your dimensionality and separability regime.</li></ul><h3>Related work</h3><p>This work sits in the family of <strong>fast k-means</strong> methods that improve exact clustering by pruning distances using geometric bounds and centroids. Elkan is the classic representative. Recent work explores alternative bounds and data structures. Our contribution imports Ptolemy’s inequality, previously successful in metric indexing, into Elkan’s bound update to improve pruning without changing results.</p><p>The research presented here originated in my bachelor’s thesis.”</p><h3>References and links</h3><p><a href="https://dl.gi.de/server/api/core/bitstreams/31155075-f767-40e6-9110-83c57cf8b59c/content"><strong>Paper</strong></a><strong>.</strong> <em>Extending K-Means Clustering with Ptolemy’s Inequality</em>, Proceedings of BTW 2025. DOI: <strong>10.18420/BTW2025–17</strong>.</p><ul><li><strong>Code.</strong> <strong>github.com/nikitaaveritchev/kmeans-Extension-Ptolemy</strong>.</li></ul><p><a href="https://github.com/nikitaaveritchev/kmeans-Extension-Ptolemy.git">GitHub - nikitaaveritchev/kmeans-Extension-Ptolemy</a></p><h3>Acknowledgments</h3><p>We built on an open-source Elkan implementation (MIT) and added the Ptolemaic updates. Thanks to collaborators and prior work on Ptolemaic access methods in metric spaces. See the paper for complete references.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2151e9a8c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>