Back to Streaming Sketching

Frequency Moments, Norms & Entropy

September 25, 2026 Wasil Zafar 13 min read

Estimate global norms and distribution statistics.

Table of Contents

  1. What the Shape of a Stream Reveals
  2. Moments, Norms and Entropy as Distribution Lenses
  3. From Random Signs to Moment Estimates
  4. Skew Detection, Capacity Planning and Anomalies
  5. Diagnose a Distribution with the Right Summary

What the Shape of a Stream Reveals

Imagine two music playlists with eight plays each. One plays four artists twice; another plays one artist five times and three artists once each. Both have eight plays and four distinct artists, yet the second is much more concentrated. Frequency moments summarize the shape of a distribution without asking for any specific artist: the total number of events, the number of distinct keys, and how much repeated activity is concentrated on a few keys. For counts $(2,2,2,2)$ the sum of squares is 16; for $(5,1,1,1)$ it is 28. Why might a cache, network operator, or fraud investigator care about this difference? Frequency estimation from the prerequisite chapter answers how often a nominated key appears; here the question concerns the entire frequency vector. The number of distinct keys is called its support size, not the size of the possible universe. Entropy measures uncertainty in a normalized distribution, so a stream length and a measurement window must be specified before comparing it across workloads.

Two playlists have the same size and support but different concentration Playlist A 2, 2, 2, 2 Playlist B 5, 1, 1, 1 Same totals N=8; F0=4 Different F2 16 versus 28
TermMeaning and exampleBoundary or non-exampleQuestion
Support $F_0$Four nonzero counts in $(5,1,1,1)$Four possible but unseen keys add zeroHow many distinct keys appeared?
Volume $F_1$$5+1+1+1=8$ with positive countsNet signed mass is not absolute massHow many insertions occurred?
Second moment $F_2$$25+1+1+1=28$It is not the square of the total $8^2$How concentrated are repeats?
Entropy $H$Uniform four-key counts give 2 bitsRaw counts need normalization firstHow uncertain is a sampled key?
Warm-up

What the Shape of a Stream Reveals

Compare A=$(2,2,2,2)$ with B=$(5,1,1,1)$. Checkpoint 1: each has $F_0=4$ and $F_1=8$. Checkpoint 2: square and sum to get $F_2(A)=16$ and $F_2(B)=28$. Their collision probabilities are $16/64=1/4$ and $28/64=7/16$. Expected conclusion: B has a higher chance that two independent draws match. Reflection: why cannot $F_1$ alone reveal this difference?

Moments, Norms and Entropy as Distribution Lenses

Fix a finite universe and a stream of unit insertions; let $f_i$ count occurrences of item $i$, and $N=\sum_i f_i>0$. The zeroth moment $F_0$ counts indices with $f_i>0$, $F_1=\sum_i f_i=N$, and for integer $k\geq2$, $F_k=\sum_i f_i^k$. More generally, for real $p>0$, $F_p=\sum_i \lvert f_i\rvert^p$ and $\lVert f\rVert_p=F_p^{1/p}$. In a signed turnstile stream, $F_1=\sum_i f_i$ can differ from $\lVert f\rVert_1=\sum_i\lvert f_i\rvert$; use absolute values and define support by $f_i\ne0$. For a probability distribution $p_i=f_i/N$ in the nonnegative model, Shannon entropy in bits is $H=-\sum_{i:f_i>0}p_i\log_2p_i$. It obeys $0\leq H\leq\log_2F_0$: a single occupied key attains zero, and uniform mass over $F_0$ keys attains the maximum. Collision probability is $\sum_i p_i^2=F_2/N^2$, so $N^2/F_2$ is the inverse-collision effective number of keys; it never exceeds $F_0$ by Cauchy–Schwarz. In the AMS sign estimator, choosing jointly four-wise independent unbiased signs $s_i\in\{-1,1\}$ makes $Z=\sum_i s_i f_i$ satisfy $\mathbb E[Z^2]=F_2$ and $\operatorname{Var}(Z^2)\leq2F_2^2$. Repetition and a median-of-means construction give relative error $\varepsilon$ with failure probability $\delta$ using order $\varepsilon^{-2}\log(1/\delta)$ counters, plus hash seeds, under a fixed-stream randomness model.

Frequency Moments, Norms & Entropy: Moments, Norms and Entropy as Distribution Lenses
flowchart TD
 A["Positive frequencies f"] --> B["Sum N and support F0"]
 A --> C["Squares give F2"]
 B --> D["Normalize p = f/N"]
 C --> E["Collision probability F2/N²"]
 D --> F["Entropy H"]
 A --> G["Four-wise random signs"]
 G --> H["Unbiased AMS estimate of F2"]
 classDef navy fill:#17365D,color:#fff
 classDef teal fill:#147D84,color:#fff
 classDef crimson fill:#C6284D,color:#fff
 classDef purple fill:#6C3BAA,color:#fff
 class A,B navy
 class C,E teal
 class D,F purple
 class G,H crimson
Frequency vector supplies support, mass, collision score and entropy Stream A A B C Vector f 2, 1, 1 Moments F0=3; F2=6 Distribution p=1/2,1/4,1/4
QuantityExact statementAssumption and limit
$F_0$Number of nonzero coordinatesIn a turnstile stream, a cancelled coordinate leaves support
$F_1$$\sum_i f_i=N$Holds for nonnegative unit insertions; signed net mass may differ from norm
$F_2$$\sum_i f_i^2=\lVert f\rVert_2^2$Equal $F_1$ need not imply equal $F_2$
Collision score$F_2/N^2=\sum_i p_i^2$Requires nonnegative $f$ and $N>0$
Entropy$-\sum_{p_i>0}p_i\log_2p_i$ bits$H\leq\log_2F_0$; equality at uniform probabilities
Effective diversity$N^2/F_2\leq F_0$Equality for equal positive counts by Cauchy–Schwarz

For a nonempty nonnegative vector, normalize by $N$ before interpreting entropy or collision probability. The bound $F_1^2\leq F_0F_2$ implies inverse collision probability $N^2/F_2\leq F_0$; moments do not disclose the identities of contributing keys.

From Random Signs to Moment Estimates

Why do signs work? Expand $Z^2=\sum_i f_i^2s_i^2+2\sum_{i\lt j}f_if_js_is_j$. Each diagonal term equals $f_i^2$, while pairwise independence and zero mean make each cross term vanish in expectation. For the variance, four-wise independence makes mixed products involving distinct indices vanish and yields $\operatorname{Var}(Z^2)=4\sum_{i\lt j}f_i^2f_j^2=2(F_2^2-F_4)\leq2F_2^2$. The equality requires the stated independence; pairwise independent signs are enough for unbiasedness but do not alone justify this variance calculation. Average $t$ independent copies: variance is at most $2F_2^2/t$; Chebyshev gives failure at most $2/(t\varepsilon^2)$, so taking $t\geq8/\varepsilon^2$ makes each group good with probability at least $3/4$. A median of order $\log(1/\delta)$ independent groups amplifies confidence. This analyzes a fixed frequency vector independent of the random seeds; an adaptive adversary who sees and reacts to hash choices needs a different guarantee. For $0\lt p\leq2$, symmetric $p$-stable random projections offer another route to $\ell_p$ scale because a weighted sum of independent $p$-stable variables has scale $\lVert f\rVert_p$; $p=2$ is Gaussian and $p=1$ is Cauchy. This is a distributional identity rather than a claim that one projection gives a precise estimate, and higher moments $k>2$ need separate methods and typically harder space tradeoffs.

Random sign expansion separates diagonal energy from cross terms Vector fA=2; fB=1 Signed sum Z=2sA+sB Square 5+4sAsB Average E[Z²]=5
Frequency Moments, Norms & Entropy: From Random Signs to Moment Estimates
flowchart TD
 A["Fixed vector and unbiased signs"] --> B["Pairwise independence"]
 B --> C["Cross terms cancel in mean"]
 C --> D["Expected Z² equals F2"]
 A --> E["Four-wise independence"]
 E --> F["Variance at most 2 F2²"]
 F --> G["Average groups; take median"]
 G --> H["Relative error with confidence"]
 A --> X["Adaptive updates after seed reveal"]
 X --> Y["Fixed-vector proof insufficient"]
 classDef navy fill:#17365D,color:#fff
 classDef teal fill:#147D84,color:#fff
 classDef crimson fill:#C6284D,color:#fff
 classDef purple fill:#6C3BAA,color:#fff
 class A,B,E navy
 class C,D teal
 class F,G,H purple
 class X,Y crimson
Worked Derivation

From Random Signs to Moment Estimates

For $f=(2,1)$, enumerate four equally likely independent sign pairs. If signs agree, $Z^2=9$; if they disagree, $Z^2=1$. Each case occurs with probability $1/2$, so $\mathbb E[Z^2]=(9+1)/2=5=F_2$. Next compute $\operatorname{Var}(Z^2)=((9-5)^2+(1-5)^2)/2=16$, matching $2(F_2^2-F_4)=2(25-17)=16$. Checkpoint: one sample can err by four; averaging reduces variance, not individual error. Variation: set both signs to the same random sign; each is individually unbiased but correlated, and $Z^2=9$ always. The missing assumption is pairwise independence for unbiasedness.

Reasoning toolEstablishesNeeded assumptionLimit or failure case
Pairwise sign cancellation$\mathbb E[Z^2]=F_2$Independent unbiased sign pairsFully correlated signs give cross-term bias
Four-wise moment expansion$\operatorname{Var}(Z^2)\leq2F_2^2$Four-wise independent signsPairwise alone does not prove this variance bound
Average then medianRelative error $\varepsilon$ and failure at most $\delta$Independent groups, fixed vectorAdaptive updates can correlate data with seeds
Stable projectionScale of projection follows $\lVert f\rVert_p$Independent symmetric $p$-stable variables, $0\lt p\leq2$One heavy-tailed Cauchy draw is noisy
Support inequality$F_1^2\leq F_0F_2$Nonnegative counts when $F_1=N$Signed cancellations defeat that interpretation

Skew Detection, Capacity Planning and Anomalies

An online store can compare product-view diversity between campaigns: equal traffic volumes may hide one campaign dominated by a single product. A CDN can use $F_2/N^2$ as a concentration signal for capacity planning across regional keys, while $F_0$ estimates the breadth of distinct cache objects. At production scale, assume 80 shards, roughly $10^8$ positive requests per hour, and a fixed one-hour event-time window. With shared hash seeds, each shard adds signed counts into the same AMS counters and merges them by summing before squaring; summing locally squared estimates would omit cross-shard terms and undercount global $F_2$. Entropy can distinguish a few dominant keys from a broad tail but cannot identify which keys cause the change; investigate candidates separately with heavy-hitter tools. An adversary can split traffic over rotating identities, raising apparent entropy without changing the underlying actor mix. Identity mapping, deduplication, and window boundaries determine whether the mathematical vector corresponds to the real operational question. A signed correction stream also makes $F_1=N$ and probability normalization inappropriate until final nonnegative counts are established.

Monitoring pipeline distinguishes trusted keys, merged counters and interpretation Ingest identity and clock Summaries shared-seed AMS Merge add before square Decision audit skew signal
Case Study

Skew Detection, Capacity Planning and Anomalies: Frequency Moments, Norms & Entropy

A small café has purchases for four products with counts $(4,2,1,1)$. Select an insertion-only event model and calculate $F_0=4$, $F_1=8$, $F_2=16+4+1+1=22$, and collision probability $22/64=11/32$. For comparison, $(2,2,2,2)$ has the same breadth and volume but collision probability $16/64=1/4$. Expected observation: the first distribution is more concentrated even though it has the same number of products. Success criterion: show each squared term, both normalized scores, and state why these statistics do not identify the product with count 4.

Production

Skew Detection, Capacity Planning and Anomalies: Frequency Moments, Norms & Entropy

A CDN sees $10^8$ positive requests per hour across 80 shards and wants a global collision probability estimate within 5% relative error on $F_2$ at 99% confidence. Assign shared sign seeds and event-time windows; each shard keeps AMS signed counters, and the aggregator sums matching counters across shards before squaring. If $F_1$ is exactly counted, use $\widehat F_2/F_1^2$ for collision probability with the same relative error. Budget order $\varepsilon^{-2}\log(1/\delta)$ independent counters plus hash-seed metadata, then benchmark constants, late events, dropped updates, and overflows. Evidence: exact replay samples, confidence coverage over independent seeds, shard merge parity, event-time alignment, and key normalization audits. Decision: deploy as a skew alert after those checks, investigate heavy keys with separate candidate discovery, and withhold semantic claims about unique human users if IDs can be rotated or forged.

Diagnose a Distribution with the Right Summary

First declare whether the desired result is distinct count $F_0$, total volume $F_1$, concentration $F_2/N^2$, a higher moment, a norm, or entropy. Record key identity, update model, observation window, permissible error, confidence, and whether the input can adapt to the estimator's randomness. Calculate exact small cases, compare sketches on replayable samples, and check merge ordering and window completeness. When a single key rather than a global shape matters, return to frequency estimation or heavy-hitter discovery. The exercises below ask for exact arithmetic, a justified AMS bound, and an operational decision that states where the model ceases to fit.

Practice

Practice: Diagnose a Distribution with the Right Summary

Tier 1: for $(3,1,0,2)$ compute $F_0=3$, $F_1=6$, $F_2=14$, $\lVert f\rVert_2=\sqrt{14}$, and $F_2/F_1^2=7/18$. Tier 2: for $(2,1)$ enumerate the four sign pairs; obtain squared values 9 and 1 with equal probability and mean 5. Tier 3: expand $Z^2$ and identify precisely why pairwise independence kills cross terms and why four-wise independence is used for variance. Tier 4: set $s_1=s_2$ and show the biased estimate 9; explain why an adaptive adversary also falls outside the fixed-vector proof. Tier 5: for two shards with frequencies $(2,0)$ and $(1,1)$, global $F_2=3^2+1^2=10$, whereas summing local $F_2$ gives $4+2=6$; specify correct shared-sign merge order. Deliver a calculation sheet, four-row sign table, proof outline, counterexample, and one-paragraph production policy. Rubric: 2 points for each tier, 8/10 minimum, with correct merge order required. Hint: expand the square before taking expectation. Debugging: if $F_0$ counts the zero coordinate, redefine support. Stretch: compute entropy in bits for $(2,1,1)$, namely 1.5 bits, and compare with its inverse-collision diversity $16/6$. Reflection: when would a window boundary change every statistic?

Decision checklist: choose a global question and its key/window definition; distinguish support, volume, concentration, norm and entropy; specify update signs, seed independence, error and confidence; merge signed counters before squaring and validate against exact traces. Moments describe shape rather than reveal heavy-key identities: use frequency-estimation point queries or heavy-hitter candidates for names, and carry the $\ell_2$ viewpoint into subsequent sketch analysis.

Next in the Series

In Quantiles, Ranks & Distribution Summaries, we'll explore Summarize ranks, quantiles, and distributions with bounded error..