<?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 Gaurav Chawla on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Chawla on Medium]]></description>
        <link>https://medium.com/@gc2713?source=rss-1fd7f71f253b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Coj6P7l7IBfkFrxHe9iiLw.jpeg</url>
            <title>Stories by Gaurav Chawla on Medium</title>
            <link>https://medium.com/@gc2713?source=rss-1fd7f71f253b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:33:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gc2713/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[One Formula to Map the Positional Encoding Landscape]]></title>
            <link>https://pub.towardsai.net/one-formula-to-map-the-positional-encoding-landscape-7534093c230c?source=rss-1fd7f71f253b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7534093c230c</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gaurav Chawla]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 22:01:01 GMT</pubDate>
            <atom:updated>2026-08-22T22:01:01.260Z</atom:updated>
            <content:encoded><![CDATA[<h4>Where Sinusoidal Embeddings, RoPE, and ALiBi Actually Live Inside the Attention Equation — and a 2×2 Grid to Keep Them All Straight</h4><p>Every survey of positional encoding I have read presents the methods as a chronological parade: sinusoidal, then learned, then relative, then RoPE, then ALiBi. That framing hides the most useful insight. Almost every technique is just a different answer to one question: <em>where, inside the attention computation, do you inject position?</em> In this article, I summarize the landscape through that lens. First, I revisit where positional encoding sat in the original Transformer paper. Second, I expand the attention formula fully and color-code the three places position information can enter. Third, I collapse the zoo of methods into a single 2×2 grid — absolute vs. relative on one axis, fixed vs. learned on the other — that has served me better than any timeline.</p><h3>Why Position Needs to Be Injected at All</h3><p>Self-attention is a set operation. As the ICLR 2025 blog post on positional embeddings puts it, “On its own, the Transformer architecture is position-invariant, i.e., it processes its input as an unordered set” [2]. Shuffle the tokens of a sentence and, without positional information, every attention score comes out the same. Shirley Li summarizes the fix concisely: “Positional encoding addresses, if not entirely solves, this issue by adding information about the token’s position within the sequence to its representation” [4]. The word <em>addresses</em> is doing real work in that sentence — as we will see, adding to the representation turned out to be only one of at least three options.</p><h3>1. Where Positional Encoding Sat in the Original Transformer</h3><p>In <em>Attention Is All You Need</em>, positional encoding is almost a footnote to the architecture: a vector p_i added to each token embedding x_i once, at the very bottom of the stack, before the first encoder or decoder layer. The input to the network is simply x_i + p_i. Vaswani et al. chose fixed sinusoidal vectors — sine and cosine waves of geometrically increasing wavelength — and hypothesized that this form “would allow the model to easily learn to attend by relative positions,” since the encoding of position pos + k is a linear function of the encoding of pos [5]. They also tried a learned lookup table instead and, in Li’s words, observed “nearly identical results” [4].</p><p>Two properties of this original design matter for everything that came after. Position is injected exactly once, and it then propagates upward entangled with the token’s semantic content. Later research questioned both choices: sinusoidal encodings turned out not to capture relative position effectively in practice [6], and they extrapolate poorly to sequences longer than those seen in training [8].</p><h3>2. Three Ways to Inject Position — One Expanded Formula</h3><p>The clearest way I know to compare methods is to stop writing attention as softmax(QKᵀ/√d)V and instead expand it fully for a single pair of tokens: the attention weight a_mn between query token m and key token n, followed by the output z_m. Every positional encoding technique touches exactly one colored region of this formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SV-gwZeQjB9Gcmhk76oROQ.jpeg" /><figcaption><em>The fully expanded attention computation. Each color marks one place where position information can enter. Source: Image by the author.</em></figcaption></figure><p><strong>Yellow — additive positional embeddings.</strong> Sinusoidal (and learned absolute) encodings modify the yellow term by replacing x_m with x_m + p_m before the projections W_Q, W_K are applied. Position enters <em>before</em> attention and rides along inside the embedding. This is the original Transformer recipe, and also that of BERT and GPT-2.</p><p><strong>Blue — manipulating the query and key matrices.</strong> RoPE injects position <em>during</em> the dot product, by rotating queries and keys according to their positions. Because a rotation by mθ against a rotation by nθ leaves behind only the angle (m − n)θ, the score q_m · k_nᵀ depends on relative position by construction [7]. Nothing is added to the embeddings; the projection outputs themselves are transformed. Arun Prakash arrives at the same idea from the decomposition of the pre-attention matrix: “one can add positional information directly in the attention layer as well!” [3]. Shaw et al.’s earlier relative position embeddings live here too: instead of adding position vectors to the input embeddings, they inject trainable relative-offset embeddings into the keys and values while attention is being computed [2], [6].</p><p><strong>Pink — a bias on the attention score before softmax.</strong> ALiBi skips embeddings and transformations entirely and adds a scalar penalty b_mn = −slope · |m − n| to the raw score, just before the softmax. Prakash captures its spirit: “The idea is very simple. Just add a bias (hand-crafted) after the query-key product” [3]. The farther apart two tokens are, the more their score is pushed down — a built-in recency bias that is the secret behind ALiBi’s famous length extrapolation [8]. T5’s learned relative bias occupies the same pink slot, but with a trained scalar per distance bucket instead of a hand-crafted slope.</p><p>What I like about this view is that RoPE and ALiBi, usually presented as rivals, are revealed as siblings: both refuse to touch the yellow term. As the ICLR 2025 blog post argues, the philosophy they share is that positional and semantic information are different things that should not be mixed into one vector — so both methods leave the word embeddings alone and instead modify the attention weights computed at every layer [2].</p><h3>3. The 2×2 Grid: Absolute vs. Relative, Fixed vs. Learned</h3><p>The injection point tells you <em>where</em> position enters; two more questions tell you <em>what kind</em> of position it is. Is position measured from the start of the sequence (absolute, as in Vaswani et al. [5]) or between pairs of tokens (relative, as in Shaw et al. [6])? And is the encoding fixed — deterministic, unchanged during training — or learned, a lookup table updated by gradient descent? Irani and Metsis organize their survey of the field along exactly these lines, examining “a variety of methods, including fixed, learnable, relative, and hybrid approaches” [1]. Crossing the two questions gives a grid that fits the whole landscape on a napkin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAk_hGhBqutui2KLn57hhQ.jpeg" /><figcaption><em>The positional encoding landscape in one grid. Source: Image by the author.</em></figcaption></figure><p>The fixed + absolute corner holds the sinusoidal encoding of the original Transformer. The learned + absolute corner is where BERT and GPT-2 sit, trading extrapolation for task-adapted flexibility; in PyTorch this quadrant is literally one line:</p><pre>import torch.nn as nn</pre><pre># learned absolute positions: one trainable vector per position<br>pos_embedding = nn.Embedding(max_seq_len, d_model)</pre><p>The learned + relative corner belongs to Transformer-XL and T5, which train embeddings or scalar biases for pairwise offsets, following the direction Shaw et al. opened in 2018 [6]. And the fixed + relative corner — RoPE and ALiBi — is where most modern LLMs live: relative by construction, with no positional parameters to train, and with the best length-extrapolation behavior of the four quadrants [2].</p><p>Overlaying the grid on the colored formula completes the map. The left column (absolute) mostly operates in yellow; the right column (relative) operates in blue and pink. The trend of the last several years is a steady migration from the top-left corner of the grid toward the right column — out of the embeddings and into the attention computation.</p><h3>Conclusion</h3><p>Positional encoding started as a single additive vector in the 2017 Transformer and grew into a design space of its own. My summary of that space needs only two artifacts: an expanded attention formula with three colored injection points — add to the embeddings (yellow), transform the queries and keys (blue), or bias the score before softmax (pink) — and a 2×2 grid crossing absolute vs. relative with fixed vs. learned. New methods keep appearing, but so far every one I have encountered still lands in one colored region and one quadrant. If you keep those two pictures in mind, the landscape stops being a parade of papers and becomes a small set of design choices.</p><h3>References</h3><p>[1] H. Irani and V. Metsis, “<a href="https://arxiv.org/pdf/2502.12370">Positional encoding in transformer-based time series models: A survey</a>,” arXiv preprint arXiv:2502.12370, 2025.</p><p>[2] “<a href="https://iclr-blogposts.github.io/2025/blog/positional-embedding/">Positional embeddings in transformer models: Evolution from text to vision domains</a>,” ICLR Blogposts Track, 2025.</p><p>[3] A. Prakash, “<a href="https://arunprakash-a.github.io/2024/02/02/PositionalEncodings.html">Positional encoding in transformers</a>,” Arun’s Blog, Feb. 2, 2024.</p><p>[4] S. Li, “<a href="https://medium.com/@lixue421/understanding-positional-encoding-in-transformers-2c7336728be5">Understanding positional encoding in transformers and beyond with code</a>,” Medium, Dec. 25, 2024.</p><p>[5] A. Vaswani et al., “<a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a>,” in Advances in Neural Information Processing Systems (NeurIPS), 2017.</p><p>[6] P. Shaw, J. Uszkoreit, and A. Vaswani, “<a href="https://arxiv.org/abs/1803.02155">Self-attention with relative position representations</a>,” in Proc. NAACL-HLT, 2018.</p><p>[7] J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, “<a href="https://arxiv.org/abs/2104.09864">RoFormer: Enhanced transformer with rotary position embedding</a>,” arXiv preprint arXiv:2104.09864, 2021.</p><p>[8] O. Press, N. A. Smith, and M. Lewis, “<a href="https://arxiv.org/abs/2108.12409">Train short, test long: Attention with linear biases enables input length extrapolation</a>,” in Proc. ICLR, 2022.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7534093c230c" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/one-formula-to-map-the-positional-encoding-landscape-7534093c230c">One Formula to Map the Positional Encoding Landscape</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anomaly Detector That Learns by Counting]]></title>
            <link>https://pub.towardsai.net/the-anomaly-detector-that-learns-by-counting-ad4c88703528?source=rss-1fd7f71f253b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4c88703528</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[conjugate-prior]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <dc:creator><![CDATA[Gaurav Chawla]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 21:01:01 GMT</pubDate>
            <atom:updated>2026-08-22T21:01:01.664Z</atom:updated>
            <content:encoded><![CDATA[<p>10,000 Bayesian models, no training loop: how conjugate priors caught red-team activity in a billion-event authentication log</p><p>Bayesian statistics gives you a principled way to combine prior knowledge with observed data. The catch is computational: updating beliefs usually means numerical integration, MCMC sampling, or an optimization loop you have to babysit.</p><p>There is a family of cases where none of that is necessary. Choose the prior from the right mathematical family — a <strong>conjugate prior</strong> — and the belief update collapses to arithmetic. No gradients, no convergence checks, no retraining.</p><p>This article works through the theory and then puts it to a real test: anomaly detection on the Los Alamos National Laboratory (LANL) cybersecurity dataset, which contains over one billion authentication events (1.6 billion events across all its sources). We train on a 29.4-million-event subset and build 10,413 independent per-computer models — each one updated by incrementing two integers.</p><h3>The Foundation: Bayesian Inference</h3><p>Every Bayesian analysis has three components. The <strong>prior</strong> P(θ) captures what you believe about the parameters before seeing data. The <strong>likelihood</strong> P(data | θ) says how probable the observed data is under given parameter values. The <strong>posterior</strong> P(θ | data) is your updated belief after observing the data.</p><p>Bayes’ theorem connects them:</p><p>P(θ | data) = P(data | θ) · P(θ) / P(data)</p><p>The denominator is where the trouble starts. The marginal likelihood</p><p>P(data) = ∫ P(data | θ′) · P(θ′) dθ′</p><p>rarely has a closed-form solution, which is why practitioners reach for MCMC sampling, variational approximation, or numerical integration. All three work, and all three bring approximation error, convergence monitoring, and computational overhead.</p><h3>What Conjugacy Buys You</h3><p>A prior P(θ) is <strong>conjugate</strong> to a likelihood P(data | θ) if the posterior P(θ | data) belongs to the same distributional family as the prior. When that holds, the intractable integral never has to be computed — Bayes’ theorem reduces to a parameter update you can write on one line.</p><h3>The Dirichlet–Categorical Conjugate Pair</h3><p>For categorical data — authentication types, user identities, event classes — the natural conjugate pair is Dirichlet–Categorical.</p><p><strong>Likelihood (Categorical):</strong> P(xᵢ = k | θ) = θₖ, where θ = (θ₁, …, θ_K) and θ₁ + … + θ_K = 1.</p><p><strong>Prior (Dirichlet):</strong> up to a normalizing constant,</p><p>Dir(α) ∝ θ₁^(α₁−1) · θ₂^(α₂−1) · … · θ_K^(α_K−1)</p><p><strong>Posterior:</strong> also Dirichlet. If the data contains n₁ observations of category 1, n₂ of category 2, and so on:</p><p>θ | data ~ Dir(α₁ + n₁, α₂ + n₂, …, α_K + n_K)</p><p>Add the observed counts to the prior parameters. That is the entire update. It translates directly into code — two increments per event:</p><pre>def update(self, observations):<br>    for obs in observations:<br>        self.counts[obs] += 1   # n_k += 1 for the observed category<br>        self.total += 1         # N += 1 -- total event count</pre><p>No matrix operations, no learning rate, no batch size. Each authentication event increments two integers.</p><p><strong>Posterior predictive.</strong> For a new observation, the probability of category k is</p><p>P(next = k | data) = (α + nₖ) / (K·α + N)</p><p>where K is the number of categories, N is the total number of observations, and α is the symmetric prior pseudo-count used throughout this article.</p><h3>Understanding the Prior Parameter α</h3><p>The parameter α controls how strongly you believe categories are equally likely before seeing any data. With α = 1 (a uniform prior), every category starts with one pseudo-observation and no category is favored. A larger α, say 10, takes more data to pull beliefs away from uniform — useful when you expect balance. An α below 1 encodes sparsity: most categories should be rare.</p><p>The choice matters most for categories the model has never seen. For a computer with N = 1,000 events across 4 auth types, the probability assigned to an unseen type is P(unseen) = α / ((K+1)·α + N):</p><pre>alpha   P(unseen)     Score   Effect<br>0.1     9.99 x 10-5   9.21    Very sensitive to novelty<br>1.0     9.95 x 10-4   6.91    Balanced<br>10.0    9.52 x 10-3   4.65    Conservative, harder to flag</pre><p>With large training data (N = 29.4M at the global level), different α values produce nearly identical scores — the prior washes out. At the per-computer level (N = 100–10,000 events), α meaningfully controls sensitivity. That is why α = 1 is a sensible default: it regularizes the small per-computer models without distorting the global picture.</p><h3>Case Study: Enterprise Authentication Anomaly Detection</h3><h3>The Dataset</h3><p>The LANL Comprehensive Multi-Source Cyber-Security Events dataset [6] records 58 days of activity from Los Alamos National Laboratory’s internal network: 1.6 billion events in total across its sources, of which the authentication log (auth.txt) contains just over one billion events covering 12,425 users and 17,684 computers. A red team exercise ran during the collection window, and its 749 attack events are documented in a separate ground-truth file. All user and computer identifiers are anonymized by the lab.</p><p>The dataset is released by LANL for public use under a CC0 license (approved for public release, LA-UR-15–23810), which permits commercial use.</p><p>Each authentication event contains:</p><pre>timestamp, source_user, dest_user, source_computer, dest_computer,<br>auth_type, logon_type, auth_orientation, success_status</pre><h3>The Modeling Approach</h3><p>We model two categorical distributions per computer, each with its own Dirichlet–Categorical model. Model 1 covers the <strong>authentication type</strong>: which protocols (Kerberos, NTLM, …) does this machine normally see? Model 2 covers the <strong>source user</strong>: which users normally authenticate to this machine?</p><p>These two features carry complementary signals. Machines specialize: domain controllers speak almost pure Kerberos, legacy servers lean on NTLM, workstations show mixed local-system authentications. And machines have social circles: a personal workstation is dominated by its owner, a server by its administrator group. An attacker moving laterally tends to violate both patterns at once — an unusual protocol from an unusual user.</p><p>We use α = 1 for all models: no domain bias, and no zero probabilities for categories a computer has never seen.</p><h3>Implementation and Evaluation Strategy</h3><p><strong>Temporal split.</strong> The model trains only on data before the first red team attack and is evaluated during and after the attack period. Never training on future data is what makes the evaluation resemble real deployment.</p><p><strong>Labels.</strong> Exact timestamp matching located only 3 of the 749 red team events in the authentication log — most attacks touched machines outside it. We therefore label any access to a compromised computer during the attack window as suspicious, which yields 1,247 suspicious-window events, enough signal for a reliable evaluation.</p><p><strong>Scoring.</strong> Each test event receives</p><p>auth_score = −log P(auth_type | computer history) user_score = −log P(source_user | computer history) combined_score = (auth_score + user_score) / 2</p><p>Higher score means more surprising, means more anomalous. The scoring function maps directly to code; note how the K → K+1 adjustment for unseen categories (explained in the worked example below) appears as a single conditional:</p><pre>def anomaly_score(self, category):<br>    n_k = self.counts.get(category, 0)          # 0 if never seen<br>    K = len(self.counts)<br>    if category not in self.counts:<br>        K += 1                                  # unseen: K -&gt; K+1<br>    alpha_0 = K * self.alpha_prior + self.total # denominator<br>    prob = (self.alpha_prior + n_k) / alpha_0<br>    return -np.log(prob)</pre><p>The full implementation, including per-computer models and a global fallback, is in the companion notebook on GitHub.</p><h3>A Worked Example: Scoring One Authentication Event</h3><p>Before looking at results at scale, let’s trace exactly what the algorithm computes for a single event. The setting is real: destination computer C457 and source computer C663 appear in authentication records discussed by Heard and Rubin-Delanchy [5], whose study of this same network identified C17693 as one of four confirmed red-team source machines (ranked 5th most anomalous out of 16,230). The training counts below are illustrative — round numbers chosen so the arithmetic is easy to follow — but the record structure, the machines, and the scoring formula are exactly those used in the full experiment.</p><p>Notation for this section: α is the symmetric prior pseudo-count (= 1 throughout), nₖ is the training count of category k, K is the number of distinct categories seen in training, N is the total training count, and the posterior predictive probability of category k is [4]:</p><p>P(k | data) = (α + nₖ) / (K·α + N)</p><p><strong>What the model knows about C457</strong> (illustrative: 5,000 training events, K = 3 auth types, K = 3 users, so the denominator is 3×1 + 5,000 = 5,003):</p><pre>Auth Type      n_k     P(k|C457)   Score = -log P<br>Kerberos       4,100   0.820       0.20<br>? (Unknown)      750   0.150       1.90<br>NTLM             150   0.030       3.50</pre><pre>Source User    n_k     P(u|C457)   Score = -log P<br>U31@DOM1       3,000   0.600       0.51<br>U45@DOM1       1,250   0.250       1.39<br>U58@DOM1         750   0.150       1.90</pre><h3>Scenario 1 — Normal Event</h3><p>This record structure appears in the LANL authentication log [5]:</p><pre>timestamp=3,  source_user=U31@DOM1,  source_computer=C663,<br>dest_computer=C457,  auth_type=Kerberos</pre><p>U31@DOM1 is C457’s dominant user; Kerberos is its dominant protocol. The figure traces each value from the training table (left) into its slot in the formula (right), with colors matched in the legend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NI3__xau0ukyUmIzHSNNQA.png" /><figcaption>Annotated walkthrough showing how the normal event’s training counts flow into the posterior predictive formula, producing a combined score of 0.35. <em>Source: Image by the author.</em></figcaption></figure><p>Combined score 0.35 — well within normal range.</p><h3>Scenario 2 — Suspicious Event (Confirmed Red-Team Machine C17693)</h3><pre>source_user=U842@DOM1 (never seen on C457),  source_computer=C17693,<br>dest_computer=C457,  auth_type=NTLM</pre><p>NTLM is known but rare on C457 (nₖ = 150). The user is the interesting part: U842@DOM1 never appeared on C457 during training, which triggers the K → K+1 rule. The denominator grows by one α unit to give the new category its share of prior mass, so the probability is small but never zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_E2gRcSSljdsrFR0ATQV8Q.png" /><figcaption>Annotated walkthrough of the suspicious event showing the unseen-user adjustment and a combined score of 6.01 <em>Source: Image by the author.</em></figcaption></figure><p>Combined score 6.01–17× higher than the normal event. The same arithmetic runs across all 10,413 computer models simultaneously.</p><h3>Results</h3><h3>What the Algorithm Learned</h3><p>The global authentication distribution over 29.4M training events (6 normalized auth types):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc0u1Tt0PHZ6zJuUVMDFEw.png" /><figcaption>Bar chart of the global authentication type distribution across 29.4 million training events .<em>Source: Image by the author.</em></figcaption></figure><pre>Auth Type                 Events        % Total   Score (global)<br>? (Unknown system auth)   17,004,222    57.8%     0.55<br>Kerberos                  10,367,997    35.2%     1.04<br>NTLM                       1,431,374     4.9%     3.02<br>Negotiate                    604,153     2.1%     3.89<br>MSAUTHPKG                    ~16,239     0.1%     7.82<br>Wave                               6     0.0%    15.25</pre><p>The “?” category represents local system authentications where the protocol type was not logged — a common artifact in enterprise Windows environments. The model learns this is the norm and scores it accordingly.</p><p>Each machine also develops its own authentication fingerprint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRbQttV6Zs4sfyyDTeyUvA.png" /><figcaption>Chart showing per-computer authentication type profiles for five representative machines .<em>Source: Image by the author.</em></figcaption></figure><pre>C586  (3.6M events):  49.9% Unknown system auth  -&gt; high-traffic domain resource<br>C625  (1.97M events): 56.2% Unknown system auth  -&gt; active infrastructure node<br>C988  (269K events):  48.0% Unknown system auth  -&gt; mid-tier server<br>C1020 (156 events):   74.4% Unknown system auth  -&gt; isolated/edge system<br>C1069 (149 events):   74.5% Unknown system auth  -&gt; isolated/edge system</pre><p>Deviations from these per-computer norms are what drive anomaly scores up.</p><h3>Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtyZ_5XSMGRYnLMJ2Bub4A.png" /><figcaption>ROC curve for the Dirichlet-Categorical anomaly detector showing AUC of 0.826 .<em>Source: Image by the author</em></figcaption></figure><p>The detector reached an <strong>AUC-ROC of 0.826</strong> on the temporal test split, training on 29.4 million events and building 10,413 computer models in a single pass, with 1,247 suspicious-window events identified for evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Kl8rrV9ULeTf8hq13t1BQ.png" /><figcaption>Overlapping histograms of anomaly scores for attack versus normal events, showing clear separation with means of 4.24 and 2.12 . <em>Source: Image by the author.</em></figcaption></figure><p>The score separation is clear: attack events average 4.24 versus 2.12 for normal events.</p><h3>The Effect of α, Confirmed on Real Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJg-17BC5-xQddGs8GPYIw.png" /><figcaption>Two-panel chart showing anomaly scores converging across alpha values as observations accumulate, and unseen-category scores as training data grows .<em>Source: Image by the author</em></figcaption></figure><p>The left panel shows anomaly scores falling as a category is observed more often — the model learning the normal pattern. All α values converge as observations accumulate. The right panel tracks the score of a completely unseen auth type as training data grows: at LANL scale (N = 29.4M) every α choice produces nearly identical results. The prior only matters when data is sparse — which is exactly when you need it, in the small per-computer models for edge systems.</p><h3>When to Use This Approach</h3><p>Reach for Dirichlet–Categorical conjugate priors when your problem has categorical inputs (authentication types, user identities, protocol classes), streaming updates with no retraining budget, many per-entity models to maintain at once, sparse data with unseen categories, and a hard interpretability requirement — every score here has a direct meaning, such as “this event type appeared 3 times in 5,000 observations.”</p><p>Look elsewhere when you have high-dimensional continuous features (Gaussian processes, kernel methods, neural networks), complex non-linear temporal dependencies (LSTMs, Transformers), or abundant labelled data where supervised models can learn richer representations.</p><h3>Implementation Details</h3><p>The companion notebook contains the full DirichletCategorical class, the EnterpriseAuthDetector orchestrator, data loading, and every plot shown here. It runs on standard Colab hardware in about 15 minutes. You can find the code in the <a href="https://github.com/getgaurav2/conjugate-priors-cybersecurity">GitHub repository</a> and the dataset on the <a href="https://csr.lanl.gov/data/cyber1/">LANL cybersecurity data page</a>.</p><h3>Conclusion</h3><p>Conjugate priors turn a hard computational problem into bookkeeping. Because the Dirichlet posterior has the same form as the prior, 29.4 million training events reduce to counting, 10,413 per-computer behavioral models come essentially for free, and every anomaly score can be traced by hand — as the C457 walkthrough showed. The resulting detector reached an AUC-ROC of 0.826 on highly imbalanced data with a single hyperparameter left at its default.</p><p>This is not a replacement for gradient-based models, neural networks, or ensembles — those remain the right tools for many problems. The point is narrower and, I think, more useful: when the problem structure matches the model assumptions — categorical data, streaming updates, a need for interpretability — the conjugate prior approach is analytically exact, transparent, and fast enough to be boring. Seeing why each quantity in the formula is what it is, on a concrete operational problem, is the kind of understanding that transfers well beyond this particular use case.</p><p><strong>References</strong></p><p>[1] A. Gelman, J. Carlin, H. Stern, D. Dunson, A. Vehtari and D. Rubin, Bayesian Data Analysis, 3rd Edition (2013), Chapman &amp; Hall/CRC</p><p>[2] K. Murphy, Machine Learning: A Probabilistic Perspective (2012), MIT Press</p><p>[3] C. Bishop, Pattern Recognition and Machine Learning (2006), Springer</p><p>[4] S. Tu, <a href="https://stephentu.github.io/writeups/dirichlet-conjugate-prior.pdf">The Dirichlet-Multinomial and Dirichlet-Categorical Models for Bayesian Inference</a> (2019), technical writeup</p><p>[5] N. Heard and P. Rubin-Delanchy, <a href="https://spiral.imperial.ac.uk/server/api/core/bitstreams/259ea697-900a-4534-9b74-32e7440c7afb/content">Network-wide anomaly detection via the Dirichlet process</a> (2016), IEEE Conference on Intelligence and Security Informatics (ISI)</p><p>[6] A. D. Kent, <a href="https://csr.lanl.gov/data/cyber1/">Comprehensive, Multi-Source Cyber-Security Events</a> (2015), Los Alamos National Laboratory — released for public use under a CC0 license (LA-UR-15–23810)</p><p><em>All results produced on the unmodified LANL dataset; illustrative values in the worked example are labeled as such. All images by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4c88703528" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/the-anomaly-detector-that-learns-by-counting-ad4c88703528">The Anomaly Detector That Learns by Counting</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>