Median vs Moving Average
Median vs Moving Average
animation
analytics-ml
data-quality
Try Change Filter window size (odd) from 5 to 15.
Observe Compare Moving average and Median filter around the step change at index 25, and watch RMSE.
Explain Describe how window size affects the step change at index 25 and the response to spikes.
Technical boundaries. The clean signal is a step function plus a gentle sine over 50 samples. Both filters use available samples while their buffers fill.
NoteMedian vs Moving Average
{
const prng2 = (i) => ((Math.sin(i * 97.3 + 217.1) * 31415.9265) % 1 + 1) % 1;
const n = 50;
const win = med_window % 2 === 0 ? med_window + 1 : med_window; // force odd
// Clean signal: step function + gentle sine
const clean = Array.from({length: n}, (_, i) => {
const base = i < 25 ? 100 : 105;
return base + 1.5 * Math.sin(i * 0.2);
});
// Add spikes
const noisy = clean.map((v, i) => {
if (prng2(i) < med_spikeRate) {
return v + (prng2(i + 500) > 0.5 ? 1 : -1) * med_spikeSize;
}
return v + (prng2(i + 100) - 0.5) * 1.0; // small noise
});
// Moving average
const maBuf = [];
const maOut = noisy.map(v => {
maBuf.push(v);
if (maBuf.length > win) maBuf.shift();
return maBuf.reduce((a, b) => a + b, 0) / maBuf.length;
});
// Median filter
const medBuf = [];
const medOut = noisy.map(v => {
medBuf.push(v);
if (medBuf.length > win) medBuf.shift();
const sorted = medBuf.slice().sort((a, b) => a - b);
const m = Math.floor(sorted.length / 2);
return sorted.length % 2 === 0 ? (sorted[m - 1] + sorted[m]) / 2 : sorted[m];
});
const width = 620;
const height = 280;
const margin = {top: 30, right: 20, bottom: 35, left: 50};
const plotW = width - margin.left - margin.right;
const plotH = height - margin.top - margin.bottom;
const allV = [...noisy, ...maOut, ...medOut];
const yMin = Math.min(...allV) - 2;
const yMax = Math.max(...allV) + 2;
const xS = (i) => margin.left + (i / (n - 1)) * plotW;
const yS = (v) => margin.top + plotH - ((v - yMin) / (yMax - yMin)) * plotH;
const noisyPath = noisy.map((v, i) => `${i === 0 ? "M" : "L"}${xS(i).toFixed(1)},${yS(v).toFixed(1)}`).join(" ");
const maPath2 = maOut.map((v, i) => `${i === 0 ? "M" : "L"}${xS(i).toFixed(1)},${yS(v).toFixed(1)}`).join(" ");
const medPath = medOut.map((v, i) => `${i === 0 ? "M" : "L"}${xS(i).toFixed(1)},${yS(v).toFixed(1)}`).join(" ");
const cleanPath = clean.map((v, i) => `${i === 0 ? "M" : "L"}${xS(i).toFixed(1)},${yS(v).toFixed(1)}`).join(" ");
let maErr = 0, medErr = 0;
for (let i = 0; i < n; i++) {
maErr += (maOut[i] - clean[i]) ** 2;
medErr += (medOut[i] - clean[i]) ** 2;
}
const maRmse = Math.sqrt(maErr / n).toFixed(3);
const medRmse = Math.sqrt(medErr / n).toFixed(3);
return html`<div style="background: var(--bs-light, #f8f9fa); padding: 1rem; border-radius: 8px; color: var(--bs-body-color);">
<svg viewBox="0 0 ${width} ${height}" style="width:100%; max-width:${width}px; font-family: Arial, sans-serif;">
<text x="${width / 2}" y="16" text-anchor="middle" font-size="12" font-weight="bold" fill="var(--bs-body-color)">Median vs Moving Avg (window=${win}): spike=${med_spikeSize}, rate=${(med_spikeRate * 100).toFixed(0)}%</text>
<line x1="${margin.left}" y1="${margin.top}" x2="${margin.left}" y2="${margin.top + plotH}" stroke="var(--bs-body-color)" stroke-width="1"/>
<line x1="${margin.left}" y1="${margin.top + plotH}" x2="${margin.left + plotW}" y2="${margin.top + plotH}" stroke="var(--bs-body-color)" stroke-width="1"/>
${[yMin, (yMin + yMax) / 2, yMax].map(v => `<text x="${margin.left - 5}" y="${yS(v) + 4}" text-anchor="end" font-size="9" fill="var(--bs-body-color)">${v.toFixed(1)}</text><line x1="${margin.left}" y1="${yS(v)}" x2="${margin.left + plotW}" y2="${yS(v)}" stroke="#dee2e6" stroke-width="0.5"/>`).join("")}
<path d="${cleanPath}" fill="none" stroke="#16A085" stroke-width="1" stroke-dasharray="6,3"/>
<path d="${noisyPath}" fill="none" stroke="#7F8C8D" stroke-width="0.7" opacity="0.5"/>
<path d="${maPath2}" fill="none" stroke="#E67E22" stroke-width="1.8"/>
<path d="${medPath}" fill="none" stroke="#3498DB" stroke-width="2"/>
<text x="${margin.left + plotW / 2}" y="${height - 5}" text-anchor="middle" font-size="10" fill="var(--bs-body-color)">Sample (note the step change at index 25)</text>
<rect x="${margin.left + 5}" y="${margin.top + 5}" width="145" height="66" fill="var(--bs-body-bg, white)" stroke="#dee2e6" rx="3"/>
<line x1="${margin.left + 10}" y1="${margin.top + 17}" x2="${margin.left + 28}" y2="${margin.top + 17}" stroke="#16A085" stroke-width="1" stroke-dasharray="6,3"/>
<text x="${margin.left + 32}" y="${margin.top + 21}" font-size="9" fill="var(--bs-body-color)">Clean signal</text>
<line x1="${margin.left + 10}" y1="${margin.top + 31}" x2="${margin.left + 28}" y2="${margin.top + 31}" stroke="#7F8C8D" stroke-width="0.7" opacity="0.5"/>
<text x="${margin.left + 32}" y="${margin.top + 35}" font-size="9" fill="var(--bs-body-color)">Noisy + spikes</text>
<line x1="${margin.left + 10}" y1="${margin.top + 45}" x2="${margin.left + 28}" y2="${margin.top + 45}" stroke="#E67E22" stroke-width="1.8"/>
<text x="${margin.left + 32}" y="${margin.top + 49}" font-size="9" fill="var(--bs-body-color)">Moving average</text>
<line x1="${margin.left + 10}" y1="${margin.top + 59}" x2="${margin.left + 28}" y2="${margin.top + 59}" stroke="#3498DB" stroke-width="2"/>
<text x="${margin.left + 32}" y="${margin.top + 63}" font-size="9" fill="var(--bs-body-color)">Median filter</text>
</svg>
<p style="margin: 0.5rem 0 0 0; font-size: 0.9em;">
<strong>RMSE:</strong>
Moving avg = <span style="color:#E67E22; font-weight:bold;">${maRmse}</span> |
Median = <span style="color:#3498DB; font-weight:bold;">${medRmse}</span>
${parseFloat(medRmse) < parseFloat(maRmse) ? " -- Median wins, especially with spikes present." : " -- Moving average performs similarly; try increasing spike rate."}
Notice how the median preserves the step change at index 25, while the moving average smooths it out over ${win} samples.
</p>
</div>`;
}