\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{algorithm,algpseudocode}
\usepackage{bm}
\usepackage{hyperref}
\usepackage{float}
\usepackage{subcaption}
\usepackage{enumitem}
\usepackage{xcolor}
\definecolor{darkgreen}{rgb}{0.0, 0.5, 0.0}
\definecolor{aaltoBlue}{RGB}{0, 51, 102}
\definecolor{pinegreen}{cmyk}{0.92,0,0.59,0.25}
\definecolor{royalblue}{cmyk}{1,0.50,0,0}
\definecolor{lavander}{cmyk}{0,0.48,0,0}
\definecolor{violet}{cmyk}{0.79,0.88,0,0}
\definecolor{lightblue}{RGB}{173, 216, 230}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{calc,arrows.meta,positioning,fit,shapes.geometric,shapes.misc,intersections,patterns,decorations.pathreplacing,backgrounds,matrix}
\usepgfplotslibrary{fillbetween,groupplots}
\setcounter{secnumdepth}{-\maxdimen}
% Long unbreakable tokens (the ISO/IEC author names in citations, term names
% in the title) otherwise overflow the margin by a few points; a modest
% emergency stretch lets TeX loosen the paragraph instead.
\emergencystretch=2em
\usepackage{mleftright}
% Project macros used by this entry (auto-extracted).
\newcommand{\dataset}{\mathcal{D}}
\newcommand{\distof}[1]{\probdist^{(#1)}}
\newcommand{\featuredim}{d}
\newcommand{\featuremtx}{\mX}
\newcommand{\featurevec}{\vx}
\newcommand{\mC}[0]{{\bf C}}
\newcommand{\mX}[0]{{\bf X}}
\newcommand{\probdist}{\mathbb{P}}
\newcommand{\reals}{\mathbb{R}}
\newcommand{\samplecovmtxgeneric}{\widehat{\mC}}
\newcommand{\sampleidx}{r}
\newcommand{\samplemeanvecgeneric}{\widehat{\bm \mu}}
\newcommand{\samplesize}{m}
\newcommand{\vx}[0]{{\bf x}}

\begin{document}

\section{sample covariance matrix}

\subsection*{Author and editors}
Alexander Jung\textsuperscript{*}, Department of Computer Science, Aalto University, Espoo, Finland (ORCID \mbox{\href{https://orcid.org/0000-0001-7538-0990}{0000-0001-7538-0990}}) \\
Editors: Konstantina Olioumtsevits (ORCID \mbox{\href{https://orcid.org/0000-0003-2697-8659}{0000-0003-2697-8659}}), Ekkehard Schnoor (ORCID \mbox{\href{https://orcid.org/0000-0001-8252-1499}{0000-0001-8252-1499}}), Aalto University, Espoo, Finland \\
\textsuperscript{*}Corresponding author: \href{mailto:alex.jung@aalto.fi}{alex.jung@aalto.fi}



\subsection{Abstract}
The sample covariance matrix of a dataset is the
		covariance matrix of the random vector obtained by selecting one
		of its data points uniformly at random. Its diagonal
		entries are the sample variances of the individual
		features, and its off-diagonal entries are the
		covariances between different features. Two
		divisor conventions are in use: dividing the sum of outer
		products by the number $\samplesize$ of data points gives
		the covariance matrix under the empirical distribution, while
		dividing by $\samplesize-1$ gives an unbiased estimator of
		the covariance matrix of an underlying probability distribution. The two differ
		by the factor $\samplesize/(\samplesize-1)$ and therefore have
		the same eigenvectors, so a dimensionality reduction built on them
		does not depend on the choice.

\subsection{Definition}
Consider a dataset $\dataset$ of $\samplesize$
		data points, characterized by feature vectors
		$\featurevec^{(1)}, \,\ldots, \,\featurevec^{(\samplesize)} \in \reals^{\featuredim}$.
		A running example is the dataset of the $1824$ days of the
		years $2020$ to $2024$ at Krems an der Donau (Austria) with both
		readings on record, each day characterized by its air temperature
		at $06{:}00$ and at $15{:}00$ (UTC). The
		sample covariance matrix
		records how much each feature varies across the
		data points and how strongly two features vary
		together, without assuming any probabilistic model behind the
		measurements.
\par
		The sample covariance matrix of $\dataset$ is defined as the
		covariance matrix with respect to the empirical distribution
		$\distof{\dataset}$ induced by $\dataset$. It is given
		explicitly by
		$$\samplecovmtxgeneric = \frac{1}{\samplesize} \sum_{\sampleidx=1}^{\samplesize} \big( \featurevec^{(\sampleidx)}\!-\!\samplemeanvecgeneric \big) \big( \featurevec^{(\sampleidx)}\!-\!\samplemeanvecgeneric \big)^{\top} \text{,}$$
		where $\samplemeanvecgeneric$ denotes the sample mean of
		$\dataset$. Equivalently, $\samplecovmtxgeneric$ is the
		covariance matrix of the random vector obtained by selecting a
		data point of $\dataset$ uniformly at random. For the
		weather measurements, the two diagonal entries of
		$\samplecovmtxgeneric$ are $63.01$ and $85.72$ squared degrees
		Celsius and both off-diagonal entries are $65.40$
		(\texttt{pythondemos/samplecovmtx.py}).
\par
		Two conventions for the divisor are in use. The definition above
		divides by $\samplesize$, which is what makes
		$\samplecovmtxgeneric$ the covariance matrix of a data point
		selected uniformly at random, and what the
		maximum likelihood method returns for a Gaussian
		probabilistic model (Bishop, 2006, Sect.~2.3.4). Many texts and
		software libraries divide by $\samplesize - 1$ instead. Under
		the independent and identically distributed assumption (i.i.d.\ assumption), with the data points modeled as
		realizations of independent and identically distributed (i.i.d.) random vectors, that
		second version is an unbiased estimator of the
		covariance matrix of the underlying probability distribution, while the version
		above is smaller on average by the factor
		$(\samplesize-1)/\samplesize$ (Bishop, 2006, Sect.~2.3.4).
		The reason is that $\samplemeanvecgeneric$ is computed from the
		same data points: the centered vectors sum to the
		zero vector, so only $\samplesize-1$ of them can be chosen
		freely.
\par
		The two versions differ by the factor
		$\samplesize/(\samplesize-1)$, so the choice matters only when
		the dataset is small. For the $1824$ days it moves the
		first diagonal entry from $63.01$ to $63.05$ squared degrees
		Celsius. Fig.~\ref{fig_samplecovmtx_divisor} shows what happens
		for few data points: averaged over many datasets
		drawn from the $1824$ days, the divisor $\samplesize$ gives
		half the variance of the temperature at $06{:}00$ for two
		data points and is still two percent below it for one
		hundred, while the divisor $\samplesize-1$ sits on it
		throughout.
		\begin{figure}[H]
			\begin{center}
			\begin{tikzpicture}
			\begin{axis}[width=9.0cm, height=6.0cm, axis lines=left,
				xmode=log, log basis x=10,
				xlabel={number $\samplesize$ of data points in the
					dataset},
				ylabel={average estimate (squared degrees Celsius)},
				xmin=1.7, xmax=120, ymin=25, ymax=70,
				tick label style={font=\scriptsize},
				label style={font=\scriptsize},
				legend style={draw=none, fill=none, font=\scriptsize,
					at={(0.97,0.04)}, anchor=south east},
				legend cell align=left]
				\addplot[gray, line width=1.6pt, no markers, forget plot]
					coordinates {(1.7,63.014) (120,63.014)};
				\addplot[thick, mark=*, mark size=1.8pt]
					table[col sep=comma, x=size, y=divisor_m]
					{samplecovmtx_bias.csv};
				\addlegendentry{divisor $\samplesize$}
				\addplot[thick, dashed, mark=square, mark size=2.0pt]
					table[col sep=comma, x=size, y=divisor_m_minus_1]
					{samplecovmtx_bias.csv};
				\addlegendentry{divisor $\samplesize-1$}
				\node[font=\scriptsize, anchor=south east]
					at (axis cs:115,63.6) {value for all $1824$ days};
			\end{axis}
			\end{tikzpicture}
			\end{center}
			\caption{The two divisor conventions for the sample
			variance of the temperature at $06{:}00$ at Krems an der
			Donau, averaged over $4000$ datasets of each size
			drawn from the $1824$ days of $2020$ to $2024$. The divisor
			$\samplesize$ (solid curve, filled circles) approaches the
			value for all $1824$ days (thick gray line) from below; the
			divisor $\samplesize-1$ (dashed curve, open squares) matches
			it at every size. Data generated by
			\texttt{pythondemos/samplecovmtx.py}
			\label{fig_samplecovmtx_divisor}}
		\end{figure}
		Which convention to use follows from what the matrix is for. As
		a summary of the dataset at hand, the divisor
		$\samplesize$ is the one to pick: it makes
		$\samplecovmtxgeneric$ the covariance matrix of a data point
		selected uniformly at random, so every identity that holds for
		a covariance matrix holds for it. As an estimator of the
		covariance matrix of a probabilistic model behind the data points,
		the divisor $\samplesize-1$ removes the bias. Neither
		convention gives the smallest expected squared error: shrinking
		the entries toward a multiple of the identity matrix
		trades a bias for a smaller spread and beats both when
		$\featuredim$ is comparable to $\samplesize$
		(Chen et al., 2010).
\par
		In machine learning (ML), the sample covariance matrix of the
		feature vectors of a training set is what a method reads
		when it compares the features with each other rather than
		with the label. Principal component analysis (PCA) extracts the eigenvectors
		of $\samplecovmtxgeneric$ belonging to the largest
		eigenvalues and uses them as the new features (see
		dimensionality reduction). The choice of divisor does not move these
		directions: the two versions differ by a positive scalar factor,
		so they have the same eigenvectors, and their
		eigenvalues differ by that same factor
		(\texttt{pythondemos/samplecovmtx.py}). With centered
		features, $\samplecovmtxgeneric$ is also the matrix
		$(1/\samplesize) \featuremtx^{\top} \featuremtx$ built from the
		feature matrix $\featuremtx$, whose eigenvalues set the
		condition number that controls how many steps gradient descent (GD) needs for the
		empirical risk minimization (ERM) of linear regression (see condition number).

\subsection{Cross References}
covariance matrix, covariance, matrix, sample mean, sample variance, empirical distribution, variance, estimator, PCA

\subsection{References}
\begin{enumerate}
  \item Bishop (2006). Pattern Recognition and Machine Learning. Springer Science+Business Media, New York, NY, USA.
  \item Chen et al. (2010). Shrinkage Algorithms for MMSE Covariance Estimation. IEEE Trans. Signal Processing, 58(10), pp.~5016--5029.
\end{enumerate}

\end{document}
