{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "name": "samplecovmtx.ipynb"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# sample covariance matrix \u2014 Python demo\n\nNumerical companion to the entry [sample covariance matrix](https://dictionaryofml.org/terms/samplecovmtx.html) of the [Dictionary of Applied Machine Learning](https://dictionaryofml.org/): it recomputes what the entry states and prints one line per check.\n\nThe entry defines the sample covariance matrix of a dataset as the covariance matrix under the empirical distribution, and discusses the two divisor conventions, 1/m and 1/(m-1). This demo checks both readings on the daily weather measurements at Krems an der Donau, measures how the two conventions behave as the number of data points grows, and checks what the choice does to the eigenvectors. Self-contained (numpy/matplotlib only, stdlib urllib for the download), fixed seed.\n\nRequires NumPy and Matplotlib only, and uses fixed seeds, so the printed numbers reproduce exactly. Generated from [`pythondemos/samplecovmtx.py`](https://dictionaryofml.org/terms/samplecovmtx.py); CC BY 4.0.\n\nBefore running a downloaded copy, scan it: `uvx bandit -q -t B102,B307,B602,B605 samplecovmtx.py` (B102,B307,B602,B605 are the exec, eval and shell checks of [bandit](https://bandit.readthedocs.io/)) reports nothing: the script runs no shell command and evaluates no generated code."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# Notebook shim: the script resolves output paths relative to __file__,\n# which a notebook kernel does not define; everything lands in the\n# working directory instead.\nimport os\n__file__ = os.path.join(os.getcwd(), \"samplecovmtx.py\")\nos.makedirs(\"pythondemos\", exist_ok=True)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "\"\"\"\nsamplecovmtx.py \u2014 numerical companion to the glossary entry 'sample\ncovariance matrix'.\n\nThe entry defines the sample covariance matrix of a dataset as the\ncovariance matrix under the empirical distribution, and discusses the\ntwo divisor conventions, 1/m and 1/(m-1). This demo checks both\nreadings on the daily weather measurements at Krems an der Donau,\nmeasures how the two conventions behave as the number of data points\ngrows, and checks what the choice does to the eigenvectors.\nSelf-contained (numpy/matplotlib only, stdlib urllib for the\ndownload), fixed seed.\n\nBlocks\n------\n[B-krems]   The days of 2020 to 2024 at Krems an der Donau, each a data\n            point whose feature vector is the air temperature at 06:00\n            and at 15:00 UTC of that day, from the hourly archive; the\n            3 days with a missing reading are dropped, 1824 remain. The\n            sample covariance\n            matrix with the divisor m, and the same sum with the\n            divisor m-1: the two differ by the factor m/(m-1), which is\n            1.0005 for this dataset.\n[B-uniform] The divisor-m version is exactly the covariance matrix of\n            the random vector obtained by selecting a data point of the\n            dataset uniformly at random, computed here from the uniform\n            probability mass function rather than from the formula.\n[B-small]   Treating the 1824 days as the population and drawing small\n            datasets from it: averaged over many draws, the divisor-m\n            version comes out smaller than the population value by the\n            factor (m-1)/m, while the divisor-(m-1) version averages to\n            the population value. The gap matters for a handful of data\n            points and vanishes for many.\n[B-axes]    The two conventions differ by a positive scalar factor, so\n            they have the same eigenvectors and their eigenvalues\n            differ by that factor: the principal directions a\n            dimensionality reduction extracts do not depend on the\n            choice.\n\nOutputs\n-------\nsamplecovmtx_bias.csv : for each dataset size, the average estimate of\n                        the variance of the 06:00 temperature under\n                        both conventions, and the population value.\nsamplecovmtx.png      : preview figure (checking only).\n\nData generated by pythondemos/samplecovmtx.py.\n\"\"\"\n\n# /// script\n# requires-python = \">=3.10\"\n# dependencies = [\"matplotlib==3.10.7\", \"numpy==2.3.4\"]\n# ///\n\nimport json\nimport urllib.request\n\nimport numpy as np\nimport matplotlib\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nOUT_DIR = Path(__file__).parent\nARCHIVE = \"https://dataset.api.hub.geosphere.at/v1/station/historical/\"\nSTATION = 3805                      # Krems an der Donau\nHOURS = (\"06:00\", \"15:00\")          # the two readings of a day (UTC)\nSIZES = [2, 3, 5, 8, 12, 20, 35, 60, 100]\nNR_REPEAT = 4000\nSEED = 20261029\nreport = []\n\n\ndef check(name, ok):\n    report.append((name, bool(ok)))\n    print(f\"  [{'ok' if ok else 'FAIL'}] {name}\")\n\n\ndef fetch_days(start, end):\n    \"\"\"The temperature at HOURS on each day with both readings, from the\n    hourly archive of the GeoSphere Austria station.\"\"\"\n    url = (f\"{ARCHIVE}klima-v2-1h?parameters=tl\"\n           f\"&station_ids={STATION}&start={start}&end={end}\")\n    with urllib.request.urlopen(url, timeout=300) as resp:\n        payload = json.load(resp)\n    temp = np.array(payload[\"features\"][0][\"properties\"][\"parameters\"][\"tl\"]\n                    [\"data\"], dtype=float)\n    stamps = [t[:16] for t in payload[\"timestamps\"]]\n    by_hour = {h: {s[:10]: v for s, v in zip(stamps, temp) if s[11:] == h}\n               for h in HOURS}\n    dates = sorted(by_hour[HOURS[0]])\n    pairs = np.array([[by_hour[h][d] for h in HOURS] for d in dates])\n    complete = ~np.isnan(pairs).any(axis=1)\n    return pairs[complete], len(dates)\n\n\ndef sample_covmtx(data, divisor):\n    \"\"\"The sum of outer products of the centered rows over `divisor`.\"\"\"\n    centered = data - data.mean(axis=0)\n    return centered.T @ centered / divisor"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-krems]** The days of 2020 to 2024 at Krems an der Donau, each a data point whose feature vector is the air temperature at 06:00 and at 15:00 UTC of that day, from the hourly archive; the 3 days with a missing reading are dropped, 1824 remain. The sample covariance matrix with the divisor m, and the same sum with the divisor m-1: the two differ by the factor m/(m-1), which is 1.0005 for this dataset."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "days, nr_dates = fetch_days(\"2020-01-01T00:00\", \"2024-12-31T23:00\")\nm = days.shape[0]\nC_m = sample_covmtx(days, m)\nC_m1 = sample_covmtx(days, m - 1)\nprint(f\"[B-krems] {nr_dates} days, {nr_dates - m} dropped for a missing \"\n      f\"reading, {m} kept; divisor m gives [[{C_m[0, 0]:.2f}, \"\n      f\"{C_m[0, 1]:.2f}], [{C_m[1, 0]:.2f}, {C_m[1, 1]:.2f}]], divisor m-1 \"\n      f\"gives [[{C_m1[0, 0]:.2f}, {C_m1[0, 1]:.2f}], [{C_m1[1, 0]:.2f}, \"\n      f\"{C_m1[1, 1]:.2f}]]; factor {m / (m - 1):.4f}\")\ncheck(\"[B-krems]   five full years, two leap years; 1824 days carry both \"\n      \"readings\", nr_dates == 1827 and m == 1824 and not np.isnan(days).any())\ncheck(\"[B-krems]   the two conventions differ by exactly the factor m/(m-1)\",\n      np.allclose(C_m1, C_m * m / (m - 1)))\ncheck(\"[B-krems]   the divisor-m version matches numpy with bias=True\",\n      np.allclose(C_m, np.cov(days.T, bias=True)))\ncheck(\"[B-krems]   and the divisor-(m-1) version is what numpy returns by \"\n      \"default\", np.allclose(C_m1, np.cov(days.T)))\ncheck(\"[B-krems]   both are symmetric and positive semi-definite\",\n      np.allclose(C_m, C_m.T) and np.all(np.linalg.eigvalsh(C_m) > 0)\n      and np.all(np.linalg.eigvalsh(C_m1) > 0))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-uniform]** The divisor-m version is exactly the covariance matrix of the random vector obtained by selecting a data point of the dataset uniformly at random, computed here from the uniform probability mass function rather than from the formula."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "pmf = np.full(m, 1.0 / m)\nmean_pmf = pmf @ days\ncentered_pmf = days - mean_pmf\nC_pmf = (centered_pmf * pmf[:, None]).T @ centered_pmf\nprint(f\"[B-uniform] from the uniform pmf: [[{C_pmf[0, 0]:.2f}, \"\n      f\"{C_pmf[0, 1]:.2f}], [{C_pmf[1, 0]:.2f}, {C_pmf[1, 1]:.2f}]]\")\ncheck(\"[B-uniform] the divisor-m version is the covariance matrix of the \"\n      \"random vector drawn uniformly from the dataset\",\n      np.allclose(C_pmf, C_m))\ncheck(\"[B-uniform] whose mean vector is the sample mean\",\n      np.allclose(mean_pmf, days.mean(axis=0)))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-small]** Treating the 1824 days as the population and drawing small datasets from it: averaged over many draws, the divisor-m version comes out smaller than the population value by the factor (m-1)/m, while the divisor-(m-1) version averages to the population value. The gap matters for a handful of data points and vanishes for many."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "rng = np.random.default_rng(SEED)\npopulation = C_m[0, 0]\nrows = []\nfor size in SIZES:\n    draw = days[rng.integers(0, m, size=(NR_REPEAT, size)), 0]\n    centered = draw - draw.mean(axis=1, keepdims=True)\n    sq = np.sum(centered ** 2, axis=1)\n    rows.append((size, float(np.mean(sq / size)),\n                 float(np.mean(sq / (size - 1))), population))\n    print(f\"[B-small] size {size:3d}: divisor m gives {rows[-1][1]:6.2f}, \"\n          f\"divisor m-1 gives {rows[-1][2]:6.2f}, population \"\n          f\"{population:6.2f}\")\ncheck(\"[B-small]   the divisor-m version averages to (m-1)/m times the \"\n      \"population variance\",\n      all(abs(b - (s - 1) / s * population) < 0.06 * population\n          for s, b, _, _ in rows))\ncheck(\"[B-small]   the divisor-(m-1) version averages to the population \"\n      \"variance\", all(abs(u - population) < 0.06 * population\n                      for _, _, u, _ in rows))\ncheck(\"[B-small]   for two data points the divisor-m version is half the \"\n      \"population value\", abs(rows[0][1] / population - 0.5) < 0.05)\ncheck(\"[B-small]   and for one hundred the gap is below two percent\",\n      abs(rows[-1][1] / population - 1.0) < 0.02)\nwith open(OUT_DIR / \"samplecovmtx_bias.csv\", \"w\") as f:\n    f.write(\"size,divisor_m,divisor_m_minus_1,population\\n\")\n    for r in rows:\n        f.write(f\"{r[0]},{r[1]:.3f},{r[2]:.3f},{r[3]:.3f}\\n\")\nprint(f\"[B-small] {len(rows)} dataset sizes written\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "**[B-axes]** The two conventions differ by a positive scalar factor, so they have the same eigenvectors and their eigenvalues differ by that factor: the principal directions a dimensionality reduction extracts do not depend on the choice."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "val_m, vec_m = np.linalg.eigh(C_m)\nval_m1, vec_m1 = np.linalg.eigh(C_m1)\nprint(f\"[B-axes] eigenvalues {val_m[0]:.3f}, {val_m[1]:.3f} against \"\n      f\"{val_m1[0]:.3f}, {val_m1[1]:.3f}\")\ncheck(\"[B-axes]    the two conventions have the same eigenvectors\",\n      np.allclose(np.abs(vec_m.T @ vec_m1), np.eye(2)))\ncheck(\"[B-axes]    and their eigenvalues differ by the factor m/(m-1)\",\n      np.allclose(val_m1, val_m * m / (m - 1)))\n\n# ------------------------------------------------------------- preview\nsizes = np.array([r[0] for r in rows], dtype=float)\nfig, ax = plt.subplots(figsize=(6.2, 3.9))\nax.plot(sizes, [r[1] for r in rows], \"k-o\", ms=4,\n        label=\"divisor m\")\nax.plot(sizes, [r[2] for r in rows], \"k--s\", ms=4, mfc=\"none\",\n        label=\"divisor m - 1\")\nax.axhline(population, color=\"0.6\", linewidth=2.0,\n           label=\"population value\")\nax.set_xscale(\"log\")\nax.set_xlabel(\"number of data points in the dataset\")\nax.set_ylabel(\"average estimate (squared degrees Celsius)\")\nax.set_title(\"[B-small] the two divisor conventions for few data points\",\n             fontsize=10)\nax.legend(frameon=False, fontsize=9, loc=\"lower right\")\nfig.tight_layout()\nfig.savefig(OUT_DIR / \"samplecovmtx.png\", dpi=110)\nprint(f\"\\n{sum(ok for _, ok in report)}/{len(report)} checks passed\")\nassert all(ok for _, ok in report)"
  }
 ]
}